我有一個代碼,打開一個JOptionPane對話框,一旦用戶點擊一個按鈕。我想要做的第一件事是當用戶點擊其中一個按鈕時關閉第一個JFrame。我試過這樣做如何在按好按鈕後打開新窗口?
setVisible(false); // Delete visibility
dispose(); //Delete window
但是原來的JFrame只要按下一個按鈕就不會關閉。目標是有兩個按鈕。當按下時,顯示一個JOptionPane框,而同時關閉第一個JFrame窗口。我該怎麼做?接下來,在新的JOptionPane中插入ok之後,我不會激發什麼是動作偵聽器。我通過調用方法
sinceyoupressedthecoolbutton();
在我的JOptionPane聲明後。這是第二個問題開始的地方,它顯示的JOptionPane完美,但不走的方法
sinceyoupressedthecoolbutton();
我不知道問題出在方法調用或方法的內容。基本上,在JOptionPane上按下ok後,我不想移動到另一個打開新JLabel的方法。
下面是代碼:
package Buttons;
import java.awt.Dimension;
import java.awt.FlowLayout; //layout proper
import java.awt.event.ActionListener; //Waits for users action
import java.awt.event.ActionEvent; //Users action
import javax.swing.JFrame; //Window
import javax.swing.JLabel;
import javax.swing.JButton; //BUTTON!!!
import javax.swing.JDialog;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane; //Standard dialogue box
public class ButtonClass extends JFrame {
private JButton regular;
private JButton custom;
public ButtonClass() { // Constructor
super("The title"); // Title
setLayout(new FlowLayout()); // Default layout
regular = new JButton("Regular Button");
add(regular);
custom = new JButton("Custom", b);
add(custom);
Handlerclass handler = new Handlerclass();
Otherhandlerclass original = new Otherhandlerclass();
regular.addActionListener(handler);
custom.addActionListener(original);
//THIS WAS MY FIRST PROBLEM, I WANT TO CLOSE THE FIRST JFRAME WINDOW AS THE USER HITS OK
setVisible(false); // Close the show message dialog box
dispose();
}
public class Handlerclass implements ActionListener { // This class is
// inside the other
// class
public void actionPerformed(ActionEvent eventvar) { // This will happen
// when button is
// clicked
JOptionPane.showMessageDialog(null, String.format("%s", eventvar.getActionCommand())); //opens a new window with the name of the button
}
}
public class Otherhandlerclass implements ActionListener {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,"Since you pressed that button, I will open a new window when you press ok, okay?");
//Code works up until here
sinceyoupressedthecoolbutton(); //THIS METHOD SHOULD OPEN A NEW WINDOW!
}
public void sinceyoupressedthecoolbutton() {
JDialog YES = new JDialog();
JLabel label = new JLabel("Here is that new window I promised you!");
add(label);
YES.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
YES.setSize(500, 500);
YES.setVisible(true);
}
public class okay implements ActionListener {
public void actionPerformed(ActionEvent ok) {
}
}
}
}
幫助將不勝感激!
感謝您的反饋,現在我已將dispose()方法從構造函數中移出,當按下「ok」按鈕時,窗口將關閉。現在還有另一個問題。我sinceyypressedthecoolbutton()方法沒有執行。它應該顯示一個具有JLabel的JDialog「這是我答應給你的新窗口!」這在「ok」被按下後不會顯示。我應該如何解決這個問題? –
'YES.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);'不能應用於對話框 – MadProgrammer
謝謝,所以JDialog已經內置了EXIT_ON_CLOSE功能?現在,當我按下「OK」後,一個新窗口打開,但它是空白的......它應該有一個JLabel說:「這是我答應你的新窗口!」爲什麼它是空白的? –