Three things...
One...
Use of null
layouts. Don't be surprised when things go wrong. When using JLabel
or JButton
, unless you intend to actually add something to them, you don't need to touch there layout managers.
Make use of approriate layout managers
Two...
Calling setVisible
on your frame before you've finished filling it out...
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
// No idea what you expect this to be doing...
pack();
//frame.setVisible(true);
frame.add(panel);
// This belongs here...and you shouldn't pack a window until
// it's ready to be made visible...
frame.setVisible(true);
Three...
You seem to expect that the lable will magically now that the value numCookies
has changed...
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
// ??????
}
You need to reassign the value to the label in order for the label to be updated...
For example...
public main(){
//JLabel
// Make the lable final...so we can access from witin
// the listener...
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
//JButton
JButton click = new JButton("Click");
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
cookies.setText("Cookies:" + numCookies);
}
});
Bonus
Make sure you read through and understand Initial Threads
...And just because null
layouts annoy me so much...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public int numCookies;
public Main() {
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cookies.setText("Cookies:" + (++numCookies));
}
});
//JFrame
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(cookies, gbc);
frame.add(click, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
new Main();
}
});
}
}