Action Listener in a static method
So I am trying to make a button that opens a new frame.
The problem is that my main method is static so I can't put an action listener in the main part. I assume that I can make another class to make the action listener. So far I have this:
Code :
public class VertexAdd extends JPanel implements ActionListener {
JButton button;
public VertexAdd() {
super(new BorderLayout());
[U]Main.AddVert.addActionListener(this);[/U]
}
public void actionPerformed(ActionEvent e) {
createAndShowGUI();
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
It doesn't work right now and I am not sure how to make it so the action listener works. The button I want to attach it to is in my main class called 'AddVert'
Re: Action Listener in a static method
What do you mean by "doesn't work right now"? Are you getting an exception? If so, please post any exception messages/stack traces.
Also, if your VertexAdd class isn't used for anything other than being an ActionListener you don't need to extend the JPanel class.
Re: Action Listener in a static method
There isn't an exception. Its just that nothing is happening. The frame should pop up once I press the button but it does nothing.
Re: Action Listener in a static method
Quote:
Originally Posted by
Trunk Monkeey
There isn't an exception. Its just that nothing is happening. The frame should pop up once I press the button but it does nothing.
Thread moved to a more appropriate location.
Please post an SSCCE. We can only guess whether you are adding listeners, where you are adding listeners, or what is a part of what.
Re: Action Listener in a static method
Your program design is a bit strange. It suggests that your Main class has static GUI components which you should almost never do. I suggest you re-think your design, that you get rid of everything static other than the main method, the createAndShowGUI method and perhaps some constants -- that's it.