2

我有一个名为Jtable. 当我运行这个类时它工作正常,但是如果我运行这个类 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);
    }
}
4

2 回答 2

1

将以下修改添加到您的代码中:

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();
}
于 2014-03-05T08:39:53.403 回答
0

尝试这个。

在你的项目中创建一个类。例如称他为 InstanceCounter :

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

当你开始你的程序,使用

...
InstanceCounter.instanceCount++;

if(InstanceCounter.instanceCount>1)
    InstanceCounter.frame.dispose();

InstanceCounter.frame = myJFrame;
...

这只是一个想法。

于 2014-03-05T12:06:33.950 回答