JLabel的职位不适用于Java

时间:2015-03-29 13:51:05

标签: java jlabel

我正在尝试为我创建的标签制作位置并添加到面板中。 现在,我有一些文字和一个图标。我想更改为图标的位置在底部。

我的代码:

    frame = new JFrame(); // Create a new frame
    frame.setVisible(true); // Makes it visible     
    frame.setSize(900, 500); // Sets size         
    frame.setTitle(""); // Sets title
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null); // Sets the window on the center of the screen   

    //Create temperature panel      
    temp_panel = new JPanel(); // Creates new JPanel
    temp_panel.setBackground(Color.decode("#f1c40f")); // Sets color

    //Create temperature label
    temp_label = new JLabel("Temperature");
    label1 = new JLabel(new ImageIcon(temp_icon));

    //Add label to temperature panel
    temp_panel.add(temp_label);
    temp_panel.add(label1);

    // Creates the main panel for all panels
    panel = new JPanel();
    panel.setLayout(new GridLayout(1, 3));
    panel.add(temp_panel);

    // Add panel to frame
    frame.add(panel);

我的目标是在面板上制作多个标签,并控制它们的放置位置,如下例所示:

--------------
|    TEXT    |            
|            |
|            |
|    Text    |
|            |
|            |
|            |
|    Icon    |
--------------   

尝试了类似的事情:

temp_label = new JLabel("Temperature", BorderLayout.END.PAGE);

这似乎没什么帮助,因为我的标签只位于顶部。

1 个答案:

答案 0 :(得分:1)

这没有意义:

temp_label = new JLabel("Temperature", BorderLayout.END.PAGE);

因为如果你看一下JLabel API,你就找不到一个接受BorderLayout常量的构造函数,即使它是合法的也不会有意义。我们有时会调用类似上面的代码 - 在墙上扔大便,看看有什么东西。这种启发式很少在编程中起作用。您将需要使用Java API资源来避免编写类似这样的内容。

关于您的问题,您将JLabel添加到使用默认FlowLayout的JPanel。如果您希望其内容像在图像中一样堆叠,请为该JPanel提供不同的布局。这里使用PAGE_AXIS的BoxLayout听起来很正确。

请查看layout manager tutorials以了解有关此布局和其他布局的更多信息。