[英]JFrame, toFront(), ActionListener
我的問題是這個。 我得到了兩個可以一起工作並一起移動的窗口。
但是,如果我隨后打開瀏覽器或將出現在屏幕前面的內容,然后嘗試通過在任務欄上單擊它來在前面顯示我的程序,則只有一個窗口出現在前面。 對話框在后面,我不知道如何解決。
我知道有函數ToFront(),但是我仍然不知道如何在這種情況下使用它。
無需創建兩個JFrame,而是為您的主窗口創建一個JFrame並將所有其他窗口創建為非模式JDialogs,並以JFrame作為其所有者。 這將導致它們被堆疊為一個組。 每當用戶將某個產品帶到最前面時,所有產品都被帶到最前面。
正如VGR已經說過的那樣,這應該可以解決您的問題。非模式對話框將跟隨其父級:
public class FocusMain extends JFrame {
private static FocusMain frame;
private static JDialog dialog;
private JCheckBox checkBox;
private JPanel contentPane;
public static void main(String[] args) {
frame = new FocusMain();
frame.setVisible(true);
dialog = new JDialog(frame);
dialog.setSize(100, 100);
}
public FocusMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
checkBox = new JCheckBox("show dialog");
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (checkBox.isSelected()) {
dialog.setVisible(true);
} else {
dialog.setVisible(false);
}
}
});
contentPane.add(checkBox);
}
}
使用擴展的JDialog,您將需要通過構造器傳遞父框架,如果您的構造器看起來像這樣: public ExtendedJDialog(JFrame parentFrame)
則可以使用super(parentFrame);
將其與其父框架連接super(parentFrame);
作為構造函數的第一行...
public class FocusMain extends JFrame {
private static FocusMain frame;
private static FocusDialog dialog;
private JCheckBox checkBox;
private JPanel contentPane;
public static void main(String[] args) {
frame = new FocusMain();
frame.setVisible(true);
dialog = new FocusDialog(frame);
}
public FocusMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
checkBox = new JCheckBox("show dialog");
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (checkBox.isSelected()) {
dialog.setVisible(true);
} else {
dialog.setVisible(false);
}
}
});
contentPane.add(checkBox);
}
}
和擴展的JDialog
public class FocusDialog extends JDialog {
public FocusDialog(JFrame parentFrame) {
super(parentFrame);
setSize(100, 100);
}
}
如果需要對話框來阻止父級,請使用super(parentFrame, true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.