【发布时间】:2019-12-18 18:04:00
【问题描述】:
我有一个带有两个按钮的框架。第一个按钮打开了第二个框架,另一个按钮正在关闭它。有效。现在我想制作一个打开框架的按钮,然后再次单击它,框架将关闭。但它不起作用。我设置了布尔条件。将按钮从 false 设置为 true 后,单击该按钮。如果设置为“true”,则 actionListener 应该识别出另一个动作(关闭帧)将被执行。但什么也没有发生。代码在这里。
public class Main {
public static void main(String[] args) {
FrameOne frameOne = new FrameOne ();
}
}
.
public class FrameOne extends JFrame implements ActionListener {
private FrameTwo frameTwo;
private boolean frameIsOpen = false; // By clicking the button once the value is set to true.
private JButton btn = new JButton();
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
FrameOne(){
btn.addActionListener(this);
add(btn);
setSize(400,400);
setLocation(300, 250);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void actionPerformed(ActionEvent e) {
if(e.getSource() == btn && frameIsOpen == false) {
frameTwo = new FrameTwo(); // Opens the new frame
boolean frameIsOpen = true;} // Fulfills the condition for the else if statement.
else if (e.getSource() == btn && frameIsOpen == true) {
frameTwo.dispatchEvent(new WindowEvent(frameTwo, WindowEvent.WINDOW_CLOSING)); }
}
}
.
public class FrameTwo extends JDialog {
FrameTwo() {
setSize(400,400);
setLocation(900, 250);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
}
【问题讨论】:
标签: java swing if-statement boolean actionlistener