简体   繁体   中英

How to make menu buttons in Java?

I've made text appear inside of this menu I made with the Rectangle class. I want to know if I can make it so the text is able to be selected, and you can choose your selection with the keyboard arrows and then press Enter and it will then preform the next action. Here's what I have so far:

public Rectangle menuBorder;
    public Rectangle menu;
    BufferedImage character;
    private java.awt.Point characterLocation;
    private java.awt.Point borderLocation;
    private java.awt.Point menuLocation;
    public int charW = 24;
    public int charH = 36;
    public int borderW = 210;
    public int borderH = 80;
    public int menuW = 190;
    public int menuH = 60;


    public boolean right = false;
    public boolean left = false;
    public boolean up = false;
    public boolean down = false;

    public Keying(Display f, Images i) throws IOException
    {
        character = ImageIO.read(getClass().getResource("starting mon.png"));
        menuBorder = new Rectangle(10, 10, borderW, borderH);
        menu = new Rectangle(10, 10, menuW, menuH);
        characterLocation = new Point(175, 100);
        borderLocation = new Point(175, 270);
        menuLocation = new Point(185, 280);

//...


    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        this.setBackground(Color.white);
        g.drawImage(character, characterLocation.x, characterLocation.y, this);
        g.setColor(Color.black);
        g.fillRect(borderLocation.x, borderLocation.y, borderW, borderH);
        g.setColor(Color.white);
        g.fillRect(menuLocation.x, menuLocation.y, menuW, menuH);
        g.setColor(Color.black);
        g.setFont(new Font("Arial", Font.BOLD, 20));
        g.drawString("Battle", 190, 305);
        g.drawString("Feed", 320, 305);
        g.drawString("Pet", 200, 335);
        g.drawString("Age", 325, 335);
    }
//...

To start with, see my first comment about painting...

You will need some kind of "state" variable so you can determine what state you should paint, this could be achieved through the use of some kind of ListSelectionModel .

You will probably need a MouseListener and a MouseMotionListener to monitor the state of the mouse, see How to Write a Mouse Listener for more details.

You'll also probably want to take a look at How to Use Key Bindings .

Of course, you could just use a JList and save yourself the hassle...see How to Use Lists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM