62,621
社区成员
发帖
与我相关
我的任务
分享
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class OnlyOneFrame extends JFrame {
private JFrame f = null;
public OnlyOneFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.setToolTipText("this will show only one frame");
setTitle("OnlyOneFrame Test");
getContentPane().add(button);
setLocation(300, 200);
// button.addActionListener(new ActionListener() {
//
// @Override
// public void actionPerformed(ActionEvent e) {
// showOnlyOneFrame();
// }
// });
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
showOnlyOneFrame();
}
});
pack();
}
private void showOnlyOneFrame() {
if(f==null){
f = new JFrame();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setTitle("OnlyOneFrame");
JLabel label = new JLabel("Hello Boy!");
f.getContentPane().add(label);
f.pack();
f.setLocation(200, 200);
}
f.setVisible(true);
}
public static void main(String[] hello) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new OnlyOneFrame().setVisible(true);
}
});
}
}