Reputation: 27
I have a JLabel
and a JButton
named increment. I want to increment JLabel
value everytime I click JButton
value.
When using this code, the JLabel
value changes to 1 only once and then nothing happens for extra click on the JButton
. Any Kind of help would be appreciated.
private void initialize() {
int value1 = 0;
frame = new JFrame();
frame.setBounds(100, 100, 790, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblCounter = new JLabel("Counter");
lblCounter.setFont(new Font("Tahoma", Font.BOLD, 20));
lblCounter.setBounds(334, 11, 115, 36);
frame.getContentPane().add(lblCounter);
JButton btnIncrement = new JButton("Increment");
btnIncrement.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setText(String.valueOf((value1+1)));
}
});
btnIncrement.setBounds(21, 98, 180, 198);
frame.getContentPane().add(btnIncrement);
lblNewLabel = new JLabel("Your number is " + value1);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(318, 117, 115, 105);
frame.getContentPane().add(lblNewLabel);
}
Upvotes: 1
Views: 474
Reputation: 5067
The issue with your code is that you are assigning everytime you click the button the same value (value1 + 1), hence you are actually doing the same actions several times but the result is the same. In order to have the desired behavior you should first increase the value of value1 and then assign it to the wanted label. For this you have to adapt the event handling to
btnIncrement.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setText(Integer.toString(++value1));
}
});
or
btnIncrement.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
value1 = value1 + 1;
lblNewLabel.setText(Integer.toString(value1));
}
});
Upvotes: 0
Reputation: 5629
int j = 0;
for(int i = 0; i < 10; ++i)
System.out.println(j + 1);
This statement print 1
10
times, because it is not changing the j
value. It is just displaying it.
Whereas,The below code changes the j
value.
int j = 0;
for(int i = 0; i < 10; ++i)
System.out.println(j++);
i += 1;// this evaluates to i = i + 1
i ++; // All these evaluate to
i = i + 1;// i = i + 1
i + 1//doesn't evaluate to i = i + 1
Here i
value is actually assigned.
Try this instead.
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setText(String.valueOf((value1++)));
}
Upvotes: 1
Reputation: 594
You have to assign the new value to your value1
its still 0.
public void actionPerformed(ActionEvent arg0) {
value1 += 1;
lblNewLabel.setText(String.valueOf(value1));
}
Upvotes: 2