Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用鼠标而不是键盘选择按钮_Java_Button_Menu - Fatal编程技术网

Java 用鼠标而不是键盘选择按钮

Java 用鼠标而不是键盘选择按钮,java,button,menu,Java,Button,Menu,嗨,我为我的游戏制作了一个暂停菜单,你可以用键盘上的箭头键在其中导航。我的问题是,我该如何使用鼠标导航,然后单击按钮,而不必使用箭头键 代码如下: public class InGameMenu implements KeyListener { private String[] string = { "Resume Game", "Options", "Save Game", "Load Game", "Exit Game" }; private String[] optionStrings

嗨,我为我的游戏制作了一个暂停菜单,你可以用键盘上的箭头键在其中导航。我的问题是,我该如何使用鼠标导航,然后单击按钮,而不必使用箭头键

代码如下:

public class InGameMenu implements KeyListener {

private String[] string = { "Resume Game", "Options", "Save Game", "Load Game", "Exit Game" };
private String[] optionStrings = { "Help", "Back" };

public static int selected = 0;
private int space = 25;

public int width = 800;
public int height = 600;

public static boolean isInMenu = true;
public static boolean isInOptions = false;
public static boolean saving = false;
public static boolean loading = false;

public InGameMenu() {

}

public void tick() {

}

public void render(Graphics g) {

    g.setColor(new Color(0, 0, 0, 90));
    g.fillRect(0, 0, Component.width, Component.height);
    if (isInMenu) {
        g.setColor(Color.LIGHT_GRAY);
        if (saving) {
            g.drawString("Saving", Component.width / 2 / Component.pixelSize - (int) (Component.width / 25), 35);
        }
        if (loading) {
            g.drawString("Loading", Component.width / 2 / Component.pixelSize - (int) (Component.width / 25), 35);
        }

        for (int i = 0; i < string.length; i++) {
            if (selected == i) {
                g.setColor(Color.RED);
            } else {
                g.setColor(Color.WHITE);
            }
            g.drawString(string[i], Component.width / 2 / Component.pixelSize - (int) (Component.width / 17.5), Component.height / 8 + (i * space));
        }
    } else if (isInOptions) {
        for (int i = 0; i < optionStrings.length; i++) {
            if (selected == i) {
                g.setColor(Color.RED);
            } else {
                g.setColor(Color.WHITE);
            }
            g.drawString(optionStrings[i], Component.width / 2 / Component.pixelSize - (int) (Component.width / 17.5), Component.height / 8 + (i * space));

        }
    }

}

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    if (isInMenu) {
        if (key == KeyEvent.VK_UP) {
            selected--;
            if (selected < 0) {
                selected = string.length - 1;
            }
        }
        if (key == KeyEvent.VK_DOWN) {
            selected++;
            if (selected > string.length - 1) {
                selected = 0;
            }
        }
        if (key == KeyEvent.VK_ENTER) {
            if (selected == 0) {
                Component.isInMenu = false;
            } else if (selected == 1) {
                isInMenu = false;
                isInOptions = true;
                selected = 0;
            } else if (selected == 2) {
                saving = true;
                SaveLoad.save();
                saving = false;
            } else if (selected == 3) {
                loading = true;
                SaveLoad.load();
                loading = false;
            } else if (selected == 4) {
                System.exit(0);
            }
        }
    } else if (isInOptions) {
        if (key == KeyEvent.VK_UP) {
            selected--;
            if (selected < 0) {
                selected = optionStrings.length - 1;
            }
        }
        if (key == KeyEvent.VK_DOWN) {
            selected++;
            if (selected > optionStrings.length - 1) {
                selected = 0;
            }
        }
        if (key == KeyEvent.VK_ENTER) {
            if (selected == 0) {
                System.out.println("HELP");
            } else if (selected == 1) {
                isInOptions = false;
                isInMenu = true;
            }
        }
    }

}

public void keyReleased(KeyEvent e) {

}

public void keyTyped(KeyEvent e) {

}

}
您也可以实现MouseListener

您可以从MouseListener添加以下方法:

首先,必须获得文本的边界x、y、宽度和高度。 您已经有了x和y:

您可以通过FontgetStringBoundsString、FontRenderContext确定宽度和高度:

需要边界来确定鼠标在单击时是否悬停在文本上

接下来,必须维护每个菜单项的边界。 现在,您只在string和OptionString中维护名称。您需要维护每个菜单项的x、y、宽度和高度

由于每个菜单项都有自己的名称、大小和位置,因此创建由以下属性组成的新类型会更容易:

public class Label {    
    private String name;
    private Font font;
    private int x, y;
    private int width, height;

    public Label(String name, Font font, int x, int y, int width, int height) {
        this.name = name;
        this.font = font;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
}
您可以使用标签[],而不是字符串[]。尽管出于更高级别的功能,更倾向于使用列表:

public class InGameMenu implements MouseListener {
    private List<Label> labels;

    public void mousePressed(MouseEvent event) {
        int x = event.getX();
        int y = event.getY();

        labels.forEach(label -> {
        //  if (mouse hovering over label)
        //     ...
        });
    }
}
现在,您可以轻松确定鼠标是否悬停在特定标签上:

public void mousePressed(MouseEvent event) {
    int x = event.getX();
    int y = event.getY();

    labels.forEach(label -> {
        if(label.containsPoint(x, y)) {
            //...
        }
    });
}
最后,您必须确定单击了哪个标签 有很多方法可以做到这一点。您可以独立维护标签并检查每个标签,而不是列表:

public class InGameMenu implements MouseListener {
    private Label startLabel;
    private Label loadLabel;

    public InGameMenu(Label startLabel, Label loadLabel) {
         this.startLabel = startLabel;
         this.loadLabel = loadLabel;
    }

    public void mousePressed(MouseEvent event) {
        int x = event.getX();
        int y = event.getY();

        if(startLabel.containsPoint(x, y)) {
            //start game
        } else if(loadLabel.containsPoint(x, y)) {
            //load game
        }
    }
}
但这并不是动态的,因为InGameMenu被迫知道它拥有的每个标签,添加标签将是一件痛苦的事情

更好的方法是在InGameMenu之外创建所有标签对象,如上例所示:

FontRenderContext renderContext = ...;
Font font = ...;

// start label
String labelText = "Start";
Rectangle2D labelBounds = font.getStringBounds(labelText, renderContext);
int x = ...;
int y = ...;
int width = (int) labelBounds.getWidth();
int height = (int) labelBounds.getHeight();
Label label = new Label(labelText, font, labelX, labelY, labelWidth, labelHeight);

// list of all labels for menu
List<Label> labels = new ArrayList<>();
labels.add(label);

InGameMenu menu = new InGameMenu(labels);
然后允许Label接受回调函数:

public class Label {    
    private String name;
    private Font font;
    private int x, y;
    private int width, height;
    private Runnable onClick;

    public Label(String name, Font font, int x, int y, int width, int height, Runnable onClick) {
        this.name = name;
        this.font = font;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.onClick = onClick;
    }

    public void click() {
        onClick.run();
    }

    //...
}
因此,当您创建标签对象时,您可以为它们提供利用外部数据的操作,例如GameStateManager或其他:

Runnable onClick = () -> System.out.println("Start button was clicked!");

Label label = new Label("Start", ..., onClick);

getButton指定按下了哪个鼠标按钮。它不能确定压力机发生在何处。你测试过这个吗?这是如何决定选择了哪一项的?@VinceEmigh捕捉得很好!对不起,关于那件事。我会解决的。提示:建议使用字体,这样他们就可以使用FontMetrics。使用metrics中的getWidth和getHeight,加上文本的x和y位置,您可以检查鼠标是否在该区域单击。有人找到了解决方案吗?@Artem是的,请查看我的答案。咖啡馆,你也可以去看看
public void mousePressed(MouseEvent event) {
    int x = event.getX();
    int y = event.getY();

    labels.forEach(label -> {
        if(label.containsPoint(x, y)) {
            //...
        }
    });
}
public class InGameMenu implements MouseListener {
    private Label startLabel;
    private Label loadLabel;

    public InGameMenu(Label startLabel, Label loadLabel) {
         this.startLabel = startLabel;
         this.loadLabel = loadLabel;
    }

    public void mousePressed(MouseEvent event) {
        int x = event.getX();
        int y = event.getY();

        if(startLabel.containsPoint(x, y)) {
            //start game
        } else if(loadLabel.containsPoint(x, y)) {
            //load game
        }
    }
}
FontRenderContext renderContext = ...;
Font font = ...;

// start label
String labelText = "Start";
Rectangle2D labelBounds = font.getStringBounds(labelText, renderContext);
int x = ...;
int y = ...;
int width = (int) labelBounds.getWidth();
int height = (int) labelBounds.getHeight();
Label label = new Label(labelText, font, labelX, labelY, labelWidth, labelHeight);

// list of all labels for menu
List<Label> labels = new ArrayList<>();
labels.add(label);

InGameMenu menu = new InGameMenu(labels);
public class InGameMenu implements MouseListener {
    private List<Label> labels;

    public InGameMenu(List<Label> labels) {
        this.labels = labels;
    }

    public void mousePressed(MouseEvent event) {
        int x = event.getX();
        int y = event.getY();

        labels.forEach(label -> {
            if(label.containsPoint(x, y))
                label.click();
        });
    }
}
public class Label {    
    private String name;
    private Font font;
    private int x, y;
    private int width, height;
    private Runnable onClick;

    public Label(String name, Font font, int x, int y, int width, int height, Runnable onClick) {
        this.name = name;
        this.font = font;
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.onClick = onClick;
    }

    public void click() {
        onClick.run();
    }

    //...
}
Runnable onClick = () -> System.out.println("Start button was clicked!");

Label label = new Label("Start", ..., onClick);