Newer
Older
Sample01 / src / FirstGUI.java
@motoki miura motoki miura on 11 Oct 2022 1 KB 4th lec
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

class MyJButton extends JButton implements ActionListener , Runnable {
    Thread thread;
    public MyJButton(String label){
        super(label);
    }
    public Dimension getPreferredSize(){
        return new Dimension(300, 100);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (thread == null){
            thread = new Thread(this);
            thread.start();
        } else {
            thread = null;
        }
        FirstGUI.jf.pack();
        System.out.println(e.getActionCommand());
    }
    int num = 0;
    @Override
    public void run() {
        while(thread != null){
            num++;
            setText("Second: "+num);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class MyThread extends Thread {

}

public class FirstGUI {
    static JFrame jf;
    public static void main(String[] args){
        System.out.println("FirstGUI");

        jf = new JFrame("FirstGUI");

        MyJButton jb = new MyJButton("Label Label Label");
        jb.addActionListener(jb);
        jb.addActionListener( e -> System.out.println("Button was pressed") );
        jb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(jb,"Button was pressed.");
            }
        });
        jf.getContentPane().add(jb);
//        jf.setSize(300,200);
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }
}