简体   繁体   English

图形用户界面不可见错误

[英]Graphical user interface not visible error

My Main code 我的主要代码

import javax.swing.JFrame;

public class PotLuck {

private static JFrame frame;

public static void main(String[] args) {
    frame = new JFrame("POT LUCK V1.0");
    PotLuckPanel panel3 = new PotLuckPanel();
    frame.add(panel3);
    frame.setSize(300,300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
}
}

My PotLuckPanel class 我的PotLuckPanel类

import java.awt.BorderLayout;

public class PotLuckPanel extends JPanel  {

private JLabel statusBar;
private int guessCounter=0;

public PotLuckPanel(){

JPanel panel = new JPanel(new BorderLayout());  
JPanel panel2 = new JPanel();

panel2.setLayout(new GridLayout(5,5));
for(int i=0 ; i< 25 ; i++){
    JButton buttoni = new JButton();
    panel2.add(buttoni);
}

statusBar = new JLabel("Number of guess:"+ guessCounter);
panel.add(statusBar, BorderLayout.NORTH);
panel.add(panel2, BorderLayout.SOUTH);
}
 }

Buttons are not visible, panels either. 按钮不可见,面板也不可见。 Only frame is appearing. 仅出现框架。 When I compile there is no error. 当我编译时没有错误。 What is my error? 我怎么了 How can I fix it? 我该如何解决?

Try to set layout to frame as 尝试将布局设置为框架

frame.setLayout(new FlowLayout());

Or any other layout in main method. 或main方法中的任何其他布局。 And it will be visible. 并且它将是可见的。

The problem is that your PotLuckPanel is a JPanel , but you never add any components to it. 问题在于您的PotLuckPanel是一个JPanel ,但是您从未向其添加任何组件。

There is no need for you to create the "panel" variable. 您无需创建“面板”变量。 You just set the layout of your class and than add the components directly to it: 您只需设置类的布局,然后直接向其中添加组件即可:

//JPanel panel = new JPanel(new BorderLayout());  
setLayout( new BorderLayout() ):

...

//panel.add(statusBar, BorderLayout.NORTH);
//panel.add(panel2, BorderLayout.SOUTH);
add(statusBar, BorderLayout.NORTH);
add(panel2, BorderLayout.SOUTH);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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