我在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)。 –