Last active
August 29, 2015 14:02
-
-
Save dopamane/c99b90e72dfe1e150e81 to your computer and use it in GitHub Desktop.
How to create the basic Java UI with Swing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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