这是我的代码,我只想知道如何让我的程序等待我在第一个窗口上单击“确定”,然后打开下一个窗口,而不是同时打开它们。例如,我希望它弹出显示“嘿”的窗口,程序等待我单击“确定”,然后弹出显示“再见”的窗口,然后程序等待我单击“确定”(按钮)。
public class Interface extends JFrame implements ActionListener
{
JButton botonOk1 = new JButton("Ok");
JButton botonOk2 = new JButton("Ok");
JFrame frame1 = new JFrame();
JFrame frame2 = new JFrame();
public void createFirstInterface(String x){
botonOk1.addActionListener(this);
JLabel label = new JLabel(x);
label.setFont(new Font("Arial", Font.PLAIN, 20));
botonOk1.setBounds(270, 200, 150, 50);
label.setBounds(200, 10, 250,150);
frame1.setLayout(null);
frame1.setMinimumSize(new Dimension(700,365));
frame1.add(label);
frame1.add(botonOk1);
frame1.pack();
frame1.setVisible(true);
}
public void createSecondInterface(String y){
botonOk2.addActionListener(this);
JLabel label = new JLabel(x);
label.setFont(new Font("Arial", Font.PLAIN, 20));
botonOk2.setBounds(270, 200, 150, 50);
label.setBounds(200, 10, 250,150);
frame2.setLayout(null);
frame2.setMinimumSize(new Dimension(700,365));
frame2.add(label);
frame2.add(botonOk2);
frame2.pack();
frame2.setVisible(true);
}
public void call(){
createFirstInterface("hey");
createSecondInterface("bye");
}
public static void main(String[] args){
Interface interface = new Interface();
interface.call();
}
public void actionPerformed(ActionEvent e){
Object check;
check = new Object();
check = e.getSource();
if(check == botonOk1){
frame1.setVisible(false);
}
if(check == botonOk2){
frame2.setVisible(false);
}
}
}
答案 0 :(得分:0)
或更妙的是,使Windows modal 对话框(例如,将ModalityType设置为APPLICATION_MODAL的JDialog)。这样,程序流程会在继续处理之前等待对话框的处理(不再显示)。
例如:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import javax.swing.*;
public class Interface2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
Interface2 interface2 = new Interface2();
interface2.call();
});
}
public void call() {
createInterface("Hey");
createInterface("Bye");
System.exit(0);
}
private void createInterface(String text) {
JLabel label = new JLabel(text);
label.setFont(label.getFont().deriveFont(Font.BOLD, 40f));
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.setPreferredSize(new Dimension(600, 300));
centerPanel.add(label);
JButton okBtn = new JButton("OK");
okBtn.addActionListener(e -> {
// get the window that holds this JButton
Window win = SwingUtilities.getWindowAncestor((Component) e.getSource());
// now close/dispose of it
win.dispose();
});
JPanel btnPanel = new JPanel();
btnPanel.add(okBtn);
JDialog dialog = new JDialog(null, text, ModalityType.APPLICATION_MODAL);
dialog.add(centerPanel, BorderLayout.CENTER);
dialog.add(btnPanel, BorderLayout.PAGE_END);
dialog.pack();
dialog.setLocationByPlatform(true);
dialog.setVisible(true);
}
}
请注意,模态对话框是JOptionPanes如何停止程序流,直到处理完对话框为止。在这里,我们只是在做更直接的事情。