我有一个Java框架中的按钮,按下按钮后它会从文本字段读取一个值,并使用该字符串作为端口名称来尝试连接串行设备。如果连接成功,则该方法返回true,否则它返回false。如果它返回true,我希望框架消失。在其他类中指定的一系列其他框架将随后出现,其中包含控制串行设备的选项。
我的问题是:按钮连接到一个动作监听器,当按下按钮时就会调用这个方法。如果我尝试使用frame.setVisible(true);方法,Java就会抛出抽象按钮错误,因为我实际上正在告诉它在按钮按下方法退出之前使包含按钮的框架消失。删除frame.setVisible(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
。小的 UI 元素可以弹出在JDialog
或JOptionPane
中,而CardLayout
或各种 Swing 组件可用于在容器中包含多个 UI(或“屏幕”)。 - Andrew Thompson