Question

I have this java code:

public static void main(String[] args) throws IOException
    {
        JPanel panel = new JPanel();
        JFrame frame = new JFrame();

        frame.setLayout(new BorderLayout());
        frame.add(panel, BorderLayout.SOUTH);

        panel.add(new Label("south"));
        panel.add(new Button("Press here :)"));


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(loader);
        frame.getContentPane().addMouseListener(loader);
        //frame.getContentPane().addMouseMotionListener(loader);
        frame.pack();
        frame.repaint();
        frame.setVisible(true);

        //Deleted some unimportant content

        panel.setVisible(true);
        panel.add("south", panel);

        t.start();
    }

So I have this frame which has one button that currently does nothing. I have been looking quite a lot on the internet for a solution but I can't figure out how to add an actionlistener to the button since it has no name? Like how would I tell what button is pressed with an actionlistener? Besides that, I believe I have to implement it and therefore I thought it might be a bad idea to do this in the main method? I just wanted to try it out before moving it to another class or method.

Well, I hope you can provide me with some suggestions or advice, thanks in advance!

Was it helpful?

Solution

Let's look at this line:

panel.add(new Button("Press here :)"));

You create a new button and pass it to the add method of panel. If you want to do anything with the button, such as adding an ActionListener to it, then first create the button and assign it to a variable, before passing it to panel.add:

// Create a Button and assign it to a variable
JButton button = new JButton("Press here :)");

// Add an action listener to the button
button.addActionListener(...);

// Add the button to the panel
panel.add(button);

This is basic Java programming knowledge. See Oracle's tutorial, for example the one about variables, for more information on how to work with objects and variables.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top