- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class NumberGuess extends JFrame implements ActionListener
- {
- private static final long serialVersionUID = 1L;
- private JTextField txtGuess;
- private JButton btnExit;
- private JButton btnGuess;
- private JLabel lblLastGuess;
- private NumberGuess() {
- super("Number Guess!");
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setLayout(new GridBagLayout());
- this.setLocationByPlatform(true);
- JPanel mainPanel = new JPanel(new GridBagLayout());
- mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
- txtGuess = new JTextField("");
- btnExit = new JButton("Exit");
- btnExit.addActionListener(this);
- btnGuess = new JButton("Guess!");
- btnGuess.addActionListener(this);
- lblLastGuess = new JLabel("You guessed: Nothing yet");
- JPanel buttonPanel = new JPanel();
- buttonPanel.add(btnExit);
- buttonPanel.add(btnGuess);
- this.addItem(mainPanel, new JLabel("Enter a guess: "), 0, 0, 1, 1);
- this.addItem(mainPanel, txtGuess, 1, 0, 2, 1);
- this.addItem(mainPanel, lblLastGuess, 0, 1, 3, 1);
- this.addItem(mainPanel, buttonPanel, 1, 2, 2, 1);
- this.getRootPane().setDefaultButton(btnGuess);
- this.setContentPane(mainPanel);
- this.pack();
- this.setVisible(true);
- }
- public void actionPerformed(ActionEvent e) {
- if(e.getSource() == btnExit)
- System.exit(0);
- else
- lblLastGuess.setText("You guessed: " + txtGuess.getText());
- }
- public static void main(String[] args) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }
- catch(Exception e){}
- new NumberGuess();
- }
- });
- }
- private void addItem(Container p, Component c, int x, int y, int width, int height) {
- GridBagConstraints gc = new GridBagConstraints();
- gc.gridx = x;
- gc.gridy = y;
- gc.gridwidth = width;
- gc.gridheight = height;
- gc.ipadx = 1;
- gc.ipady = 1;
- if(c instanceof JTextField) {
- gc.fill = GridBagConstraints.BOTH;
- gc.weightx = 1.0;
- }else if( c instanceof JPanel )
- gc.anchor = GridBagConstraints.EAST;
- else
- gc.anchor = GridBagConstraints.WEST;
- p.add(c, gc);
- }
- }