试设计一个窗口,内含一个按钮。开始运行时,按钮显示“Click Me”字样,当按钮按下时,按钮显示为“Click Me Again”字样,再按一次,则按钮显示“Click Me”字样,依此循环。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main{

    public static void main(String[] args) {
        new NewFrame();
    }
}

class NewFrame extends JFrame{

    JFrame frame;
    JButton button;
    Police police;

    public NewFrame() {

        frame  = new JFrame("test");
        frame.setBounds(500, 400, 500, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        button = new JButton("button");
        button.setText("Click Me");
        police = new Police();
        button.addActionListener(police);
        frame.add(button);

        frame.validate();
        frame.setVisible(true);
    }

    class Police implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JButton but  = (JButton)(e.getSource());
            if (but.getText().equals("Click Me")) {
                but.setText("Click Me Again");
            }else {
                but.setText("Click Me");
            }
        }

    }

}

0

Leave a Reply

Your email address will not be published.