java JPanel 不显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4211675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPanel not showing up
提问by aherlambang
Why is the UI not showing up in my code below:
为什么 UI 没有显示在我下面的代码中:
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);
}
}
回答by vinothkr
I guess JPanel cannot be a toplevel container. It has to be put inside a JFrame or JWindow to be shown
我猜 JPanel 不能是顶级容器。它必须放在 JFrame 或 JWindow 中才能显示
JFrame f=new JFrame();
f.add(test);
f.setVisible(true);
回答by MeBigFatGuy
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:
JPanel 不是顶级容器。您需要将该 JPanel 放在 JDialog 或 JFrame 中。确保将其添加到该对话框或框架的内容窗格中:
JFrame f = new JFrame();
f.getContentPane().add(test);
回答by Eugene Ryzhikov
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.
面板只是不显示在 Swing 中。它们必须添加到窗口中。创建 JFrame 或 JDialog 并将您的面板添加到其中。