[求助]主窗口和子窗口
我有一个主窗口JFrame,两个JButton和两个JInternalFrame,如何实现:按钮按下时,如果相应的子窗口不存在则创建一个子窗口,如果子窗口存在则把子窗口设置到最前。谢谢!
我的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
//主窗口
public class MainFrame extends JFrame {
//定义菜单栏
JMenuBar menuBar = new JMenuBar();
JMenu menuFile= new JMenu("File");
JMenuItem menuIn = new JMenuItem("窗口1");
JMenuItem menuOut = new JMenuItem("窗口2");
JMenuItem menuExit = new JMenuItem("退出");
//定义内部窗口容器
static JDesktopPane desktop = new JDesktopPane();
//构造函数
public MainFrame() {
super("主窗口");
//设置菜单栏
menuFile.add(menuIn);
menuFile.add(menuOut);
menuFile.add(menuExit);
menuBar.add(menuFile);
this.setJMenuBar(menuBar);
this.getContentPane().add(desktop);
//定义菜单监听
menuIn.addActionListener(new InnerFrame1());
menuOut.addActionListener(new InnerFrame2());
menuExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//设置窗体属性
this.setSize(500,500);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
this.setLocation( (screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
this.setVisible(true);
//定义窗口关闭
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MainFrame mainFrame = new MainFrame();
}
}
//窗口1
class InnerFrame1 extends JInternalFrame implements ActionListener{
//构造函数
public InnerFrame1() {
//设置窗体属性
super("窗口1",true,true,true,true);
this.setSize(500,500);
this.setLayout(null);
}
//定义响应菜单事件
public void actionPerformed(ActionEvent e) {
// if (i==0){
// i++;
try {
InnerFrame1 Frame1 = new InnerFrame1();
MainFrame.desktop.add(Frame1);
Frame1.setMaximum(true);
Frame1.show();
} catch (Exception eg) {
eg.printStackTrace();
}
// }
// this.toFront();
}
}
//窗口2
class InnerFrame2 extends JInternalFrame implements ActionListener{
//构造函数
public InnerFrame2() {
//设置窗体属性
super("窗口2",true,true,true,true);
this.setSize(500,500);
this.setLayout(null);
}
//定义响应菜单事件
public void actionPerformed(ActionEvent e) {
// if (i==0){
// i++;
try {
InnerFrame2 Frame2 = new InnerFrame2();
MainFrame.desktop.add(Frame2);
Frame2.setMaximum(true);
Frame2.show();
} catch (Exception eg) {
eg.printStackTrace();
}
// }
// this.toFront();
}
}