buttondemo.java

来自「金旭亮的java教案」· Java 代码 · 共 42 行

JAVA
42
字号
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonDemo {
    // Note:  I have had a report that this does not display properly
    // on  JDK 1.2, 1.2.2 or 1.3 on Windows NT 4.0 W/S with SP5, but 
    // it works OK if you do the setVisible(true) AFTER adding all comp's. 
    // otherwise you only see the components if you resize or otherwise
    // cause a repaint event.   
    // the fix is to add a pack()

    static JFrame frame = new JFrame("Example");

    public static void setupFrame() {
        frame.setSize(400,100);
        frame.getContentPane().setLayout( new FlowLayout() );

        WindowListener l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        };
        frame.addWindowListener(l);
    }

    public static void main(String[] args) {
        setupFrame();
        final JButton jb = new JButton("pressure");

        jb.addActionListener( new ActionListener() {
              int i = 1;
                public void actionPerformed(ActionEvent e) 
                {  // this sets the size to a literal, make it variable
                   // jb.setSize(100,10);
                   System.out.println("pressed "+ i++); }
              } );

        frame.getContentPane().add( jb );
        frame.pack( );
        frame.setVisible(true);
    }
}

⌨️ 快捷键说明

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