I am having difficulty trying to add JButtons to my JFrame.
I have created two methods (all within the same class for now). If I make the showGUI method static, then I receive errors:
//Listen for actions on buttons.
next.addActionListener(this); (CANNOT USE THIS IN A STATIC CONTEXT)
previous.addActionListener(this); (CANNOT USE THIS IN A STATIC CONTEXT)
classify.addActionListener(this); (CANNOT USE THIS IN A STATIC CONTEXT)
and when adding the JButton objects to my JFrame, I receive the following errors:
add(next); (Cannot make a static reference to the non-static method add(Component) from the type Container)
add(previous); (Cannot make a static reference to the non-static method add(Component) from the type Container)
add(classify); (Cannot make a static reference to the non-static method add(Component) from the type Container)
How can I overcome this? I have included my method below for reference:
public void showGUI(BufferedImage img){
next = new JButton("Next Image");
next.setMnemonic(KeyEvent.VK_N);
next.setActionCommand("disable");
previous = new JButton("Previous Image");
previous.setMnemonic(KeyEvent.VK_P);
previous.setActionCommand("disable");
classify = new JButton("Classify");
classify.setMnemonic(KeyEvent.VK_C);
classify.setActionCommand("disable");
//Listen for actions on buttons.
next.addActionListener(this);
previous.addActionListener(this);
classify.addActionListener(this);
add(next);
add(previous);
add(classify);
//Display image on the screen.
frame.setTitle("TITLE");
RMHC newContentPane = new RMHC();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new JLabel(new ImageIcon(img)));
frame.pack();
frame.setVisible(true);
frame.isResizable();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
I think the problem because you call the method showGUI from main method which is static, so the best thing is to initializing GUI Frame in main method (also in EDT), like: