2

I have a Java class named Jtable. When I run this class it works fine but if I run this class 10 times then 10 new windows open and I do not want that, I want that if I run this java class any number of time it should close previous windows.

My code is given below:

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);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • Will the different instances be created inside the same VM ? – Antoine Marques Mar 05 '14 at 08:22
  • I think it is another formulating of question: [How to implement a single instance Java application][1] : http://stackoverflow.com/questions/177189/how-to-implement-a-single-instance-java-application – Pavlo K. Mar 05 '14 at 08:50
  • Don't call you class Jtable. There is a Swing class `JTable` which is too confusing. – camickr Mar 05 '14 at 16:14

2 Answers2

1

Add the following modifications to your code :

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();
}
Mickäel A.
  • 9,012
  • 5
  • 54
  • 71
0

Try this.

Make a class in your project. For example call him InstanceCounter :

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

When you start you program, use a

...
InstanceCounter.instanceCount++;

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

InstanceCounter.frame = myJFrame;
...

That's only an idea.

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119