swingapplication.java

来自「java的书上例子」· Java 代码 · 共 58 行

JAVA
58
字号
//例13.2  Swing Button Demo
import javax.swing.*;          //引入所有有关swing的包
import java.awt.*;				//引入有关事件处理的包,事件处理机制同AWT
import java.awt.event.*;

public class SwingApplication {
    private static String labelPrefix = "You have clicked ";
    private int numClicks = 0;		//计数器,计算点击次数

    public Component createComponents() {
        final JLabel label = new JLabel(labelPrefix + "0    times");

        JButton button = new JButton("I'm a Swing button!");
        button.setMnemonic(KeyEvent.VK_I);
        button.addActionListener(new ActionListener() {			//处理点击事件的程序
            public void actionPerformed(ActionEvent e) {
                numClicks++;								//计数器加1
                label.setText(labelPrefix + numClicks + "    times");		//显示点击次数
            }
        });
        label.setLabelFor(button);
        JPanel pane = new JPanel();
        pane.setBorder(BorderFactory.createEmptyBorder(
                                        30, //top
                                        30, //left
                                        10, //bottom
                                        30) //right
                                        );
        pane.setLayout(new GridLayout(0, 1));
        pane.add(button);
        pane.add(label);

        return pane;
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(
                UIManager.getCrossPlatformLookAndFeelClassName());
        } catch (Exception e) { }

        //建立最高一级的容器,一个Swing风格的窗口
        JFrame frame = new JFrame("SwingButtonDemo");
        SwingApplication app = new SwingApplication();
        Component contents = app.createComponents();
        frame.getContentPane().add(contents, BorderLayout.CENTER);
		//添加事件监听器
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
		//显示窗口
        frame.pack();
        frame.setVisible(true);
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?