简体   繁体   中英

Prevent Multiple Instances of Java Frame

The application that I am working on involves frames that are created from a JPanel based upon what the user selects. I am trying to prevent a user from launching multiple instances of the same frame if the select the same item twice. Here is the condition what I wrote for that purpose.

Main class:

public void showPieGraphFrame()
{
    final PieGraph gPieGraph = new PieGraph("Traffic Type Distribution", counterOne, counterTwo);
    gPieGraph.pack();
    RefineryUtilities.positionFrameOnScreen(gPieGraph, 0.35, 0.03);

    if(!gPieGraph.isVisible())  
    {
    gPieGraph.setVisible(true);
    }
}

PieGraph class that I want to prevent multiple instances of:

public class PieGraph extends ApplicationFrame implements ActionListener {

    public PieGraph(final String title) {
        super(title);

        // create a menubar
        setJMenuBar(createMenuBar());

        // create a dataset...
        final PieDataset dataset = trafficTypeDataset();

        // create the chart...
        final JFreeChart chart = createChart(dataset);

        // add the chart to a panel...
        final ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(width, height));
        setContentPane(chartPanel);
    }

    private JFreeChart createChart(final PieDataset dataset) {

        final JFreeChart chart = ChartFactory.createPieChart("Test Chart", dataset, false, false, false);

        final PiePlot plot = (PiePlot) chart.getPlot();

        return chart;
    }

However, it is not working and you can still launch the same frame more than once. How can I prevent this?

How can I prevent this?

Swap the frame to a modal JDialog or a JOptionPane .

It simple doesn't allow you to call setVisible twice. Two windows will only appear when you have two JFame objects. Make your JFrame a Singleton .
Hope I could help.

Use the Singleton Pattern for the frame, eg:

public class MainFrame extends JFrame() {

 private static MainFrame instance;

 public static MainFrame getInstance(//parameters) {
   if (instance == null){
    instance = new MainFrame(//parameters)
 }
    return instance;
 }

 private MainFrame(//parameters){}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM