【发布时间】:2011-11-12 04:09:20
【问题描述】:
我在 java 框架中有一个按钮,当按下它时,它会从文本字段中读取一个值,并将该字符串用作尝试连接到串行设备的端口名称。
如果此连接成功,则该方法返回 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。小的 UI 元素可能会在JDialog或JOptionPane中弹出,而CardLayout或各种 Swing 组件可用于在容器中包含多个 UI(或“屏幕”)。 -
如需尽快获得更好的帮助,请发帖SSCCE。
标签: java swing actionlistener