我在java框架中有一個按鈕,當它按下時,它從文本框中讀取一個值,並將該字符串用作嘗試連接到串行設備的端口名稱。Java:Swing:按下按鈕後隱藏框架
如果此連接成功,則方法返回true,否則返回false。如果它返回true,我希望框架消失。然後在其他類中指定的一系列其他框架將顯示控制串行設備的選項。
我的問題是:按鈕被連接到一個動作監聽器,當按下這個方法時被調用。如果我嘗試使用frame.setVisible(true);方法java拋出一個抽象按鈕錯誤,因爲我有效地告訴它在按鈕按下方法退出之前消失了包含按鈕的框架。刪除frame.setVisible(true);允許程序正常運行,但我留下了一個不再有用的延續的連接框架。
如何在按下按鈕時使框架消失?
package newimplementation1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author Zac
*/
public class ConnectionFrame extends JPanel implements ActionListener {
private JTextField textField;
private JFrame frame;
private JButton connectButton;
private final static String newline = "\n";
public ConnectionFrame(){
super(new GridBagLayout());
textField = new JTextField(14);
textField.addActionListener(this);
textField.setText("/dev/ttyUSB0");
connectButton = new JButton("Connect");
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(connectButton, c);
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
boolean success = Main.mySerialTest.initialize(textField.getText());
if (success == false) {System.out.println("Could not connect"); return;}
frame.setVisible(false); // THIS DOES NOT WORK!!
JTextInputArea myInputArea = new JTextInputArea();
myInputArea.createAndShowGUI();
System.out.println("Connected");
}
});
}
public void actionPerformed(ActionEvent evt) {
// Unimplemented required for JPanel
}
public void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Serial Port Query");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
//Add contents to the window.
frame.add(new ConnectionFrame());
frame.setLocation(300, 0);
//Display the window.
frame.pack();
frame.setVisible(true);
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
System.out.println("Exiting Gracefully");
Main.mySerialTest.close();
((JFrame)(e.getComponent())).dispose();
System.exit(0);
}
});
}
}
這是不可能的應用程序。應該使用多個'JFrame'。小型用戶界面元素可能會彈出在「JDialog」或「JOptionPane」中,而「CardLayout」或各種Swing組件可用於在容器中包含多個UI(或「屏幕」)。 –
爲了更快提供更好的幫助,請發佈[SSCCE](http://pscode.org/sscce.html)。 –