JPanel JButton并不总是表现出来

时间:2015-03-05 10:44:09

标签: java swing

好吧我不知道这里发生了什么。 JButton有时会在我编译我的程序时显示,有时候我只能看到没有按钮的JPanel,如果我有多个按钮随机显示它们,我不知道是什么导致这个。我还发现如果我最小化JFrame并且最大化按钮最终会显示出来。

public void controlPanel(){

    JPanel jp = new CreateJPanel();
    Color color = new Color(0,40,0);

    jp.setSize(f.getWidth()/2, (int) (f.getHeight() * 0.15));   
    jp.setBorder(BorderFactory.createLineBorder(color, 1));
    jp.setBackground(Color.GRAY);
    jp.setLocation(0, (int) (f.getHeight()* 0.50));
    jp.add (new JButton ("Button1"));
    f.add(jp);

}

JFrame类

public class CreateTranseperantJFrame extends JFrame{

public CreateTranseperantJFrame(){

    this.setSize(1420, 820);
    this.setUndecorated(true);
    this.setLocationRelativeTo(null);
    this.setResizable(false);
    this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
    this.setBackground(new Color(0,0,0,1));
    this.setLayout(null);
    this.setVisible(true);
    this.requestFocus();

    }
}

1 个答案:

答案 0 :(得分:1)

曾经有过类似的问题。

在我的情况下,由于许多子组件,我必须验证包含所有内容的组件。

在您的情况下,它会转化为:

jp.validate();

在方法结束时" controlPanel"

修改 事实证明,在大多数情况下,它应该足以验证最上面的组件,正如您在评论中所述。

因此:

this.validate();

在构造函数CreateTranseperantJFrame()

的末尾

此外,很可能您必须.validate()显示此行为的所有组件。

希望这有帮助!