Simple windowed application: Difference between revisions

m
→‎{{header|Java}}: Fixed some small issues with the code
m (→‎{{header|Java}}: Fixed some small issues with the code)
Line 1,169:
{{libheader|Swing}}
<lang java>import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Line 1,174 ⟶ 1,175:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Clicks extends JFrame implements ActionListener{
private long clicks = 0;
private JLabel label;
private JButton clicker;
private String text;
 
public Clicks(){
super("Clicks");//set window title
text = "There have been no clicks yet";
JLabel label = new JLabel(text"There have been no clicks yet");
JButton clicker = new JButton("click me");
clicker.addActionListener(this);//listen to the button
new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0e) {
text = label.setText("There have been " + (++clicks) + " clicks");//change the text
}
}
);
setLayout(new BorderLayout());//handles placement of components
add(label,BorderLayout.CENTER);//add the label to the biggest section
add(clicker,BorderLayout.SOUTH);//put the button underneath it
label.setPreferredSize(new Dimension(300,100));//nice big label
setSize(300,200);//stretch out the window
label.setHorizontalAlignment(JLabel.CENTER);//text not up against the side
pack();//fix layout
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//stop the program on "X"
setVisible(true);//show it
}
public static void main(String[] args){
SwingUtilities.invokeLater( //Swing UI updates should not happen on the main thread
() -> new Clicks(); //call the constructor where all the magic happens
}
);
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == clicker){//if they clicked the button
text = "There have been " + (++clicks) + " clicks";
label.setText(text);//change the text
}
}
}</lang>
Anonymous user