JPanel not showing up

2019-03-04 09:34发布

问题:

Why is the UI not showing up in my code below:

public class GUI extends JPanel{

        public GUI(String name, String address, List<String> reviews, Icon icon){
            setSize(600,600);
            setLayout(new BorderLayout());
            JLabel iconLabel = new JLabel(icon);
            JLabel nameLabel = new JLabel(name);
            JLabel addressLabel = new JLabel(address);
            JPanel southReviewPanel = new JPanel();
            southReviewPanel.setLayout(new BoxLayout(southReviewPanel, BoxLayout.Y_AXIS));
            for (String review: reviews) {
                southReviewPanel.add(new JTextArea(review));
            }
            add(southReviewPanel);
            add(iconLabel, BorderLayout.WEST);
            JPanel northPane = new JPanel();
            northPane.add(nameLabel);
            northPane.add(addressLabel);
            add(northPane, BorderLayout.NORTH);
        }


    public static void main(String[] args) {
        ImageIcon ic = new ImageIcon();
        List<String> list = new ArrayList<String>();
        list.add("review1");
        list.add("review2");
        list.add("review3");
        list.add("review4");
        GUI test = new GUI("test", "test", list, ic);

          test.setVisible(true);

    }

}

回答1:

I guess JPanel cannot be a toplevel container. It has to be put inside a JFrame or JWindow to be shown

JFrame f=new JFrame();
f.add(test);
f.setVisible(true);


回答2:

Panels just don't show up in Swing. They have to be added to windows. Create JFrame or JDialog and add your panel to it.



回答3:

A JPanel isn't a top level container. You need to place that JPanel in a JDialog or JFrame. Make sure to add it to the content pane of that dialog or frame:

JFrame f = new JFrame();
f.getContentPane().add(test);