I'm new to Java and I'm wonder if someone can help me with this.
I have a class that's constructor makes a Gui window, and it's main calls this constructor. The problem is the event handling doesn't work because the event handling code can't access the GUI window variables (It just gives errors). I tried putting the Gui code inside main,but then I get errors about accessing non static variables from inside the static main.
This is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingMenu implements ActionListener{
public static void main(String[] args) {
SwingMenu s = new SwingMenu();
}
public SwingMenu(){
Toolkit toolkit = Toolkit.getDefaultToolkit();
// Get size
Dimension dimension = toolkit.getScreenSize();
JFrame frame = new JFrame(" ");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenuItem fileItem1 = new JMenuItem("Exit");
filemenu.add(fileItem1);
fileItem1.addActionListener(this);
menubar.add(filemenu);
frame.setJMenuBar(menubar);
JTextArea textArea = new JTextArea(27,27);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane);
JTextArea textArea2 = new JTextArea(3,3);
JScrollPane scrollPane2 = new JScrollPane(textArea2);
panel.add(scrollPane2);
frame.add(panel);
int height = dimension.height-30;
frame.setSize(dimension.width,height);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ev) {
// this is where I want to handle the events
}
}
Let me know if you need a better explanation.