1
\$\begingroup\$

I have been trying to figure out for quite some time on how to create a basic main menu for a game that just has a couple clickable labels, but I don't know how to write them. I have created a class that extends JFrame, made a JLabel and that is it. I don't know much to do after that.

\$\endgroup\$
1
\$\begingroup\$

Firstly, You may want to check google for basic tutorials. To make your class appear and work as expected, we first need to set it's size. You would do so with YourClass.setSize(x-dimension, y-dimension). Then, if you want it to close properly, you need to use YourClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE). This allows the frame to close and terminate the application that's running. finally, you set its visibilty to true, so you can see it with YourClass.setVisible(true), all the while replacing YourClass with an instance of your class. If you wish to add buttons, then before setting your frame's visibility, create a new JButton. Then, add it too your JFrame by using YourClass.add().

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

You should be able to do this by adding a mouse listener to the labels. E.g.

label.addMouseListener(someMouseListener).

Then you'll just have to handle the click events in the listener. If you need to do different things based on which label was clicked, then do something like this in the mouse listener's click method:

public void mouseClicked(MouseEvent e) {
    if (e.getSource() == label1) {
      ...
    } else if (e.getSource() == label2) {
      ...
    }
}

If you don't (want to) have a mouse listener that handles many sources like this, you can just add an anonymous listener to each of the labels:

label.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        ...
    }
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.