Very simple as am very new to java Eclipse. Using Eclipse IDE for Java Developers
Version: Helios Service Release 2. Created a button and Label. Using this button to increment a the value by 1 at time but nothing is happening. Not sure why its not. Please can someone have a look at. I don’t think I am too far off then again I maybr. Thanks in advance…
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class First
{
//int counter = 0; // tried it here -> unsuccesfull
// static int counter = 0; // tried it here -> unsuccesfull
public static void main (String [] args){
JFrame frame = new JFrame("att");
frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("+");
frame.add(panel);
panel.add(button);
JLabel label = new JLabel("1");
frame.add(panel);
panel.add(label);
// int counter = 0; // tried it here -> unsuccesfull
// final int counter = 0; // tried it here -> unsuccesfull. Getting error
// "The final local variable counter cannot be assigned, since it is
// defined in an enclosing type" *
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
label1.setVisible(true);
int counter = 0;
counter = counter + 1 ; // *
}
}
);
Modified the code and placed the int variable after class declartion and jut after button1.addActionListener(new ActionListener() method header and no success
You are setting to 0 the
countereverytime the button is been clicked.If what you want is to keep track of the amount of times the button has been clicked then you want to declare the variable out of the listener. Otherwise, everytime you click on the button
counterwill always be declared and set to 0. Hence, it will not increment in the way you expect.You should try something like this: