如何在JFrame中显示JButtons和JLabel?

时间:2014-03-11 05:41:57

标签: java swing layout jframe jlabel

我尝试使用此代码显示标记的窗口,但它只显示一个空白窗口。

    JFrame window = new JFrame("My Window");
    window.setVisible(true);
    window.setResizable(true);
    window.setSize(680,420);
    window.setContentPane(new Container());
    window.getContentPane().setLayout(new FlowLayout());
    JPanel panel = new JPanel();
    JLabel label = new JLabel("LABEL");
    label.setBackground(Color.BLACK);
    panel.add(label);
    window.add(panel);

3 个答案:

答案 0 :(得分:3)

请尝试最后致电setVisible

JFrame window = new JFrame("My Window");
//window.setVisible(true);
//window.setResizable(true);
//window.setSize(680,420);
//window.setContentPane(new Container());
window.setLayout(new FlowLayout());
JPanel panel = new JPanel();
JLabel label = new JLabel("LABEL");
label.setBackground(Color.BLACK);
panel.add(label);
window.add(panel);

window.setResizable(true);
// Pack will size the window to fit the content, 
// tacking into account the preferred size of the
// content...
window.pack();
window.setVisible(true);

另请注意,默认情况下JLabel是透明的,因此设置它的背景颜色将无效,除非您将其opaque属性更改为true < / p>

答案 1 :(得分:1)

添加所有componentset visibility frame后。

    JFrame window = new JFrame("My Window");
    window.setResizable(true);
    window.setSize(680,420);
    window.setContentPane(new Container());
    window.getContentPane().setLayout(new FlowLayout());
    JPanel panel = new JPanel();
    JLabel label = new JLabel("LABEL");
    label.setBackground(Color.BLACK);
    panel.add(label);
    window.add(panel);     
    window.setVisible(true);

答案 2 :(得分:0)

(因为你在启动时调用setvisible()方法).. 您还可以使用update()方法,以便更新或重新绘制jframe上的组件。