user
user

Reputation: 158

Displaying GUI Issue

I am trying to display a gui but cannot get the frame to show here is the code so far:

The idea behind this is that the string path (which is the path to an image) is calculated in another class, it is then passed to this class where the image is to be displayed.

I cannot get the frame to be displayed, my usual method would be:

new displayWindow();

but this does not work.

What would be the best method of displaying the gui?

public class displayWindow {

    public displayWindow(String path) {

        JLabel label = new JLabel();
        ImageIcon icon = new ImageIcon(speed);
        label.setIcon(icon);
        label.setText(path);
        JPanel panel = new JPanel();
        panel.add(label);    
        JFrame frame = new JFrame("Speed Limit");
        frame.setSize(500, 500); 
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);   
        frame.setVisible(true);
        System.out.println(path);
        frame.setLayout(new BorderLayout());            
        frame.setLayout(new FlowLayout());
        frame.setSize(430, 430);           
        frame.getContentPane().removeAll();
        frame.getContentPane().add(panel);    
        frame.repaint();            
    }

    public static void displayWindow() {    
        new displayWindow();    
    }    
}

Upvotes: 0

Views: 50

Answers (1)

nachokk
nachokk

Reputation: 14413

With the code you provide, your code even compile cause you don't have a default constructor with no args. Your constructor takes one parameter.

So your method should be:

public static void displayWindow(String param) {
  SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
            new displayWindow(param);
        }

    });    
}

Using SwingUtilities.invokeLater(..) you ensure that will run in the EDT(Event Dispatch Thread.)

Is there a reason for this?

frame.setLayout(new BorderLayout());
frame.setLayout(new FlowLayout());
frame.setSize(430, 430);

In java by convention class names starts with upperCase so you class should be called DisplayWindow this is very important for readability.

And call setVisible(true) after you add components to your frame :)

Upvotes: 4

Related Questions