添加到JPanel的JButton没有显示

时间:2014-03-03 20:25:28

标签: java swing

我似乎无法将JButton添加到JPanel。 我有一个PropWindow(JFrame),其中包含PropView(JPanel)。似乎正确添加了PropView-JPanel,因为我可以使用paint()在其上绘制形状。 但是,当我使用它来尝试添加一个按钮时,它将无法显示所有:/

JButton testButton;

public PropView(int width, int height) {
    super(true);

    setLayout(null);
    setSize(width, height);

    //TestButton
    testButton = new JButton("Test");
    testButton.setLocation(10,10);
    testButton.setSize(100, 50);
    testButton.setVisible(true);

    add(testButton);

    setFocusable(true);
    setVisible(true);
}

JFrame和JPanel均为250x600像素。

2 个答案:

答案 0 :(得分:0)

我无法从您发布的代码段中看出来,但为了以下情况:请确保在后添加面板或任何其他组件的框架上调用pack ()。< / p>

此外,通常不鼓励扩展JPanel或JFrame,除非你有充分的理由去做,只是抬头。

Here你有一个关于显示框架的简短教程:

其中的一些示例代码可能有所帮助:

//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");

//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//3. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

//4. Size the frame.
frame.pack();

//5. Show it.
frame.setVisible(true);

答案 1 :(得分:-1)

确保使用myPropWindow.getContentPane().add(myPropPanel)将PropPanel添加到PropWindow,而不只是myPropWindow.add(myPropPanel)