Java Swing - 如何在另一個(gè)模態(tài)JDialog之上創(chuàng)建一個(gè)模態(tài)的JDialog
我們想知道如何在另一個(gè)模態(tài)JDialog之上創(chuàng)建一個(gè)模態(tài)的JDialog。
import java.awt.BorderLayout;
import java.awt.Window;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main {
public static JPanel newPane(String labelText) {
JPanel pane = new JPanel(new BorderLayout());
pane.add(newLabel(labelText));
pane.add(newButton("Open dialog"), BorderLayout.SOUTH);
return pane;
}
private static JButton newButton(String label) {
final JButton button = new JButton(label);
button.addActionListener(e -> {
Window parentWindow = SwingUtilities.windowForComponent(button);
JDialog dialog = new JDialog(parentWindow);
dialog.setLocationRelativeTo(button);
dialog.setModal(true);
dialog.add(newPane("Label"));
dialog.pack();
dialog.setVisible(true);
});
return button;
}
private static JLabel newLabel(String label) {
JLabel l = new JLabel(label);
return l;
}
public static void main(String[] args) {
JPanel pane = newPane("Label in frame");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
}