Skip to content

Instantly share code, notes, and snippets.

@mepcotterell
Last active December 14, 2015 07:28
Show Gist options
  • Select an option

  • Save mepcotterell/5050420 to your computer and use it in GitHub Desktop.

Select an option

Save mepcotterell/5050420 to your computer and use it in GitHub Desktop.
Swing examples from class.

Swing examples from class.

import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Form {
public static void main(String[] args) {
JFrame frame = new JFrame("Form!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(640, 480));
Form myForm = new Form();
FormPanel panel = myForm.getPanel();
// set layout manager
panel.setLayout(new GridLayout(3,2));
frame.add(panel);
frame.pack();
frame.setVisible(true);
} // main
private FormPanel getPanel() {
return new FormPanel();
} // getPanel
private class FormPanel extends JPanel {
public FormPanel() {
// name label
JLabel nameLabel = new JLabel("Name:");
add(nameLabel);
// name text field
JTextField nameField = new JTextField(10);
add(nameField);
} // FormPanel
} // FormPanel
} // Form
import javax.swing.JFrame;
public class PushCounter {
public static void main(String[] args) {
JFrame frame = new JFrame("Push Counter");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PushCounterPanel panel = new PushCounterPanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
} // main
} // PushCounter
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PushCounterPanel extends JPanel {
private int count;
private JButton push;
private JLabel label;
public PushCounterPanel() {
this.count = 0;
this.push = new JButton("Push Me!");
this.push.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Pushes: " + count);
} // actionPerformed
});
this.label = new JLabel("Pushes: " + this.count);
this.add(this.push);
this.add(this.label);
this.setBackground (Color.red);
this.setPreferredSize (new Dimension(300, 40));
} // PushCounterPanel
} // PushCounterPanel
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment