如何关闭后窗

时间:2014-03-05 08:10:23

标签: java swing jframe jscrollpane null-layout-manager

我有一个名为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);
    }
}

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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;
...

这只是一个想法。