如何关闭后窗



我有一个名为Jtable的Java类。当我运行这个类时,它工作正常,但是如果我运行这个类 10 次,那么会打开 10 个新窗口,我不希望这样,我希望如果我运行这个 java 类的任何时间,它应该关闭以前的窗口。

我的代码如下:

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Jtable extends JFrame {
    DefaultTableModel model;
    JTable table;
    String col[] = {"Name","Address","Phone","hi","","","","","",""};
    public static void main(String args[]) {
        new Jtable().start(); 
    }
    public void start() {
        model = new DefaultTableModel(col,9); 
        table = new JTable(model) {
            @Override
            public boolean isCellEditable(int arg0, int arg1) {        
                return false;
            }
        };
        JScrollPane pane = new JScrollPane(table);
        pane.setBounds(50,100,700,400);
        String s="hello";
        table.setValueAt(s,0,1);
        add(pane);
        setVisible(true);
        setSize(500,400);
        setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pane.setLayout(null);
    }
}

在代码中添加以下修改:

public class Jtable extends JFrame
{
    //add object of Jtable as class variable
    public static Jtable jtable = null;
    ...
}
public static void main(String args[])
{
    //completely change the main method code
    //checking whether is there any jtable object exists
    if (jtable != null)
    {
        //if exist it will dispose it
        jtable.dispose();
    }
    //creating a new jtable instance
    jtable=new Jtable();
    jtable.start();
}

试试这个。

在项目中创建一个类。例如,称他为实例计数器:

class IntanceCounter{
    public static int instanceCount = 0;
    public static JFrame frame;
}

启动程序时,请使用

...
InstanceCounter.instanceCount++;
if(InstanceCounter.instanceCount>1)
    InstanceCounter.frame.dispose();
InstanceCounter.frame = myJFrame;
...

这只是一个想法。

相关内容

  • 没有找到相关文章

最新更新