I am a beginner in java programming and would like to ask some questions that I could not found in the tutorials here and other topics.
I would like to create a simple application with a button and a label. The variable should start with 2 and every time when press the button should increase with 2.
I am on that stage and I stuck a bit because the button is just active once. I need a little help how to fix it, thanks.
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.*;
//import statements
//Check if window closes authomatically.Otherwise add suitable code.
/**
*
* @author I
*/
public class ButtonAndLabel extends JFrame implements ActionListener {
JLabel jlbLabel1 = new JLabel();
//JLabel jlbLabel2 = new JLabel();
JButton jbtMyButton = new JButton();
private int a;
public static void main(String args[]){
new ButtonAndLabel();
}
ButtonAndLabel(){
//layout tells the computer where to put all the components
FlowLayout floMyLayout = new FlowLayout();
setLayout(floMyLayout);
//creata the components
jlbLabel1.setText("Hello");
//jlbLabel2.setText("Whatever");
jbtMyButton.setText("Press me");
//put the components on the window
add(jlbLabel1);
add(jlbLabel2);
add(jbtMyButton);
a = 2;
// I want to keep an eye on the button to see when is has been pressed
jbtMyButton.addActionListener(this);
if (a>=2){
a = a+2;
}
else{
System.out.println("OUT");
}
this.setSize(100, 100);
//pack()
setVisible(true);
}
//what do we do when the button has been pressed?
public void actionPerformed(ActionEvent e){
jlbLabel1.setText("Result " + a);
}
}

New Topic/Question
Reply




MultiQuote



|