Skip to content

Instantly share code, notes, and snippets.

@dopamane
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dopamane/c99b90e72dfe1e150e81 to your computer and use it in GitHub Desktop.
Save dopamane/c99b90e72dfe1e150e81 to your computer and use it in GitHub Desktop.
How to create the basic Java UI with Swing
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Dimension;
public class MyFrame extends JFrame {
private JLabel label;
private JButton button;
public MyFrame() {
super("MyFrameTitle"); //Superclass constructor
setDefaultCloseOperation(EXIT_ON_CLOSE); //when close button pressed, program ends.
setBounds(500, 200, 300, 300); //x_pos=500px, y_pos=500px, width=300px, height=300px
setLayout(new BorderLayout());
initComponents();
addComponents();
setVisible(true); //make the frame visible
}
private void initComponents() {
label = new JLabel("Hello"); //Initialize label
button = new JButton("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source == button) {
if (label.getText().equals("Hello"))
label.setText("World!");
else label.setText("Hello");
}
}
});
}
private void addComponents() {
add(label); //add label to MyFrame
add(button, BorderLayout.SOUTH);
}
public void simulateLabelAdjustment() {
for (double val = 0.0; val < 100; val += 0.001) {
label.setText(val + "");
revalidate();
}
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
//frame.simulateLabelAdjustment();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment