简体   繁体   English

JLabel职位在Java中不起作用

[英]JLabel positions not working in Java

I'm trying to make positions for my labels i have created and added to a panel. 我正在尝试为已创建并添加到面板的标签定位。 Right now, I have some text, and an icon. 现在,我有一些文字和一个图标。 I want to change to position for the icon to be in the bottom. 我想更改为图标在底部的位置。

My code: 我的代码:

    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);

My goal is to make multiple labels on a panel, and control where they are going to be placed, like this example: 我的目标是在面板上制作多个标签,并控制它们的放置位置,例如以下示例:

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

Have tried thing like: 尝试过类似的事情:

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

This dont seem to help, because my labels are just positioned in the top. 这似乎没有帮助,因为我的标签仅位于顶部。

This doesn't make sense: 这没有道理:

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

since if you look at the JLabel API, you'll not find a constructor that takes a BorderLayout constant, nor would it make sense even if it were legal. 因为如果您查看JLabel API,您将找不到采用BorderLayout常量的构造函数,即使合法也无济于事。 We would sometimes call code like the above -- throwing poop at the wall and seeing what sticks. 有时我们会像上面那样调用代码-将便便扔在墙上,看看会发生什么。 This heuristic rarely works in programming. 这种启发式很少在编程中起作用。 You will want to use the Java API resource to avoid making up things like this. 您将需要使用Java API资源来避免像这样的事情。

As to your problem, you're adding your JLabel to a JPanel that uses a default FlowLayout. 对于您的问题,您正在将JLabel添加到使用默认FlowLayout的JPanel中。 If you want its contents to stack as in your image, give that JPanel a different layout. 如果您希望其内容像在图像中那样堆叠,请为该JPanel提供不同的布局。 Here a BoxLayout that uses the PAGE_AXIS sounds about right. 在这里,使用PAGE_AXIS的BoxLayout听起来不错。

Please check out the layout manager tutorials for more on this and other layouts. 请查看布局管理器教程,以获取有关此布局和其他布局的更多信息。

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

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