java學習10.17

臧博涛發表於2024-10-17

今天繼續Java圖形化頁面的學習
視窗的分別顯示
import java.awt.;
import java.awt.event.
;

public class _1016 {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setBounds(500, 500, 300, 300);
frame.setAlwaysOnTop(true);

    // 設定 GridLayout
    GridLayout gridLayout = new GridLayout(2, 3); // 2行3列
    frame.setLayout(gridLayout);

    Panel topPanel = new Panel();
    topPanel.setBackground(Color.ORANGE);
    topPanel.setLayout(new GridLayout(2, 3)); // 2行3列
    for (int i = 0; i < 6; i++) {
        topPanel.add(new Button(i + ". button"));
    }
    frame.add(topPanel);

    Panel bottomPanel = new Panel();
    bottomPanel.setBackground(Color.PINK);
    bottomPanel.setLayout(new FlowLayout());
    for (int i = 0; i < 5; i++) {
        bottomPanel.add(new Button(i + ". button"));
    }
    frame.add(bottomPanel);

    frame.setVisible(true);

    // 新增視窗關閉事件
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            frame.dispose(); // 關閉主視窗
            openSecondWindow(); // 開啟第二個視窗
        }
    });
}

// 開啟第二個視窗的函式
private static void openSecondWindow() {
    Frame frame2 = new Frame();
    frame2.setBounds(600, 600, 300, 300); // 修改位置以避免重疊
    frame2.setAlwaysOnTop(true);
    frame2.setVisible(true);

    // 新增關閉事件
    frame2.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            frame2.dispose(); // 關閉第二個視窗
        }
    });
}

}