10
SimpleGridBag
- import java.awt.event.*;
- import java.awt.*;
- public class SimpleGridBag {
- public static void main(String[] args) {
- ApplicationWindow appwin = new ApplicationWindow("Application");
- appwin.setVisible(true);
- }
- static class ApplicationWindow extends Frame implements ActionListener {
- Label prompt;
- Button yes, no;
- ApplicationWindow(String name) {
- super(name);
- addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
- Menu filemenu = new Menu("File", true);
- MenuItem quit = new MenuItem("Quit");
- quit.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- System.exit(0);
- }
- });
- filemenu.add(quit);
- MenuBar menubar = new MenuBar();
- menubar.add(filemenu);
- setMenuBar(menubar);
- setLayout(new GridBagLayout());
- GridBagConstraints c = new GridBagConstraints();
- prompt = new Label("Do you really want to quit?");
- c.weightx = 1;
- c.ipadx = 10;
- c.gridx = 0;
- c.gridy = 0;
- c.gridwidth = 2;
- c.gridheight = 1;
- c.insets = new Insets(20, 10, 10, 10);
- add(prompt, c);
- yes = new Button("Yes");
- yes.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- System.exit(0);
- }
- });
- c.gridx = 0;
- c.gridy = 1;
- c.gridwidth = 1;
- c.gridheight = 1;
- c.insets = new Insets(10, 0, 10, 0);
- add(yes, c);
- no = new Button("No");
- no.setActionCommand("no");
- no.addActionListener(this);
- c.gridx = 1;
- c.gridy = 1;
- c.gridwidth = 1;
- c.gridheight = 1;
- c.insets = new Insets(10, 0, 10, 0);
- add(no, c);
- pack();
- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
- int width = getSize().width;
- int height = getSize().height;
- int x = (screenSize.width - width) / 2;
- int y = (screenSize.height - height) / 3;
- setLocation(x, y);
- setResizable(true);
- }
- public void actionPerformed(ActionEvent e) {
- if (e.getActionCommand() == "no") {
- prompt.setForeground(new Color(255, 0, 0));
- prompt.repaint();
- }
- }
- }
- }
$ javac SimpleGridBag.java
$ java SimpleGridBag
Comments