[英]How i don't show same window more than one at a time
In my project, I create some buttons. 在我的项目中,我创建了一些按钮。 When a button is clicked then a frame is appeard.
单击按钮后,将显示一个框架。 But when I click the same button then the same window is come again.
但是,当我单击相同的按钮时,将再次出现相同的窗口。 It will decrease my project quality.
这会降低我的项目质量。 I want that when next time the same button is clicked then the frame is not come because the frame is already visible.
我希望当下次单击同一按钮时,该框不会出现,因为该框已经可见。 How can I do that?
我怎样才能做到这一点?
It depends on how you've implemented it. 这取决于您如何实现它。 Instead of creating a new frame every time, keep a reference to it, and if it's already been created just show the existing one.
与其每次都创建一个新框架,不如对其进行引用,并且如果已经创建,则仅显示现有框架。
Here's a simple example. 这是一个简单的例子。 It's a frame that has two buttons.
它是一个有两个按钮的框架。 One of them creates a new frame every time, and the other one creates a frame the first time you click it, and any time after that will just show that one frame.
其中一个每次创建一个新框架,另一个第一次单击时创建一个框架,此后的任何时间都将显示该框架。
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
class test {
public static void main(String[] args) {
JFrame main = new JFrame("Test");
JButton btnAlways = new JButton("Always");
JButton btnOnce = new JButton("Once");
btnAlways.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame frame = new JFrame(new Date().toString());
frame.setSize(400, 300);
frame.setVisible(true);
}
}
);
btnOnce.addActionListener(
new ActionListener() {
JFrame frame = null;
public void actionPerformed(ActionEvent e) {
if (frame == null) {
frame = new JFrame(new Date().toString());
frame.setSize(400, 300);
}
frame.setVisible(true);
}
}
);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.getContentPane().add(btnAlways, BorderLayout.NORTH);
main.getContentPane().add(btnOnce, BorderLayout.SOUTH);
main.setSize(300, 100);
main.setVisible(true);
}
}
The listener for btnOnce
has a frame
field initially set to null
. btnOnce
的侦听器的frame
字段最初设置为null
。 The first time you click the button, it will go through the if (...) {...}
, create a frame, and assign it to the frame
field, so that subsequent invocations don't have to, rather they will use the stored value. 第一次单击该按钮时,它将经历
if (...) {...}
,创建一个框架,并将其分配给frame
字段,这样以后的调用就不必了,而是使用存储的值。
一种可能的方式是使用SingleTone
设计图案用于使用所述帧class..access getInstance()
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.