Reputation: 7530
I am having difficulty trying to add JButton
s 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);
}
Upvotes: 0
Views: 1855
Reputation: 4340
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:
public class MainApp {
public static void main(String... args) {
EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
JFrame frame= new YourFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
);
}
}
class YourFrame () extends JFrame implements ActionListener{
public YourFrame() {
}
public void showGUI(BufferedImage img){
}
private void add(JButtob button) {
}
}
Upvotes: 1
Reputation: 661
if something is static, you aren't in any instance. Therefore you cant use "this"...
Please learn the java basics before posting something like this.
If you need help, post the whole class that i know what you wanna do... otherwise I can't help you.
Upvotes: 1
Reputation: 109813
Use CardLayout, your GUI can be based on code example from tutorial
Upvotes: 1