Java Swing - JLabel位置

4

我在设置JLabel位置时遇到了问题。
我将内容窗格设置为某个JPanel,然后创建并尝试添加我的JLabel。

    JLabel mainTitle = new JLabel("SomeApp");
    mainTitle.setFont(new Font("Arial",2 , 28));
    mainTitle.setBounds(0,0, 115, 130);
    getContentPane().add(mainTitle);

我希望我的JPanel位于应用程序的左上角,但我得到的是“SomeApp”位于顶部中心(而不是左上角)。

顺便说一下,我尝试添加JButton,但我无法更改JButton的宽度、高度、x和y。

3个回答

3

Swing使用布局管理器来放置组件。

您需要了解它们的工作原理才能有效地使用它们。您可以将布局管理器设置为null,并自行完成布局,但不建议这样做,因为您需要每次跟踪新组件,并在窗口移动、缩小等情况下自行执行布局计算。

布局管理器一开始可能有点难以理解。

您的窗口可能是这样的:

as simple as this

使用此代码:
import javax.swing.*;
import java.awt.Font;
import java.awt.FlowLayout;

class JLabelLocation  {

    public static void main( String [] args ) {

        JLabel mainTitle = new JLabel("SomeApp");
        mainTitle.setFont(new Font("Arial",2 , 28));
        //mainTitle.setBounds(0,0, 115, 130); //let the layout do the work

        JFrame frame = new JFrame();
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));// places at the left
        panel.add( mainTitle );

        frame.add( panel );// no need to call getContentPane
        frame.pack();
        frame.setVisible( true );

    }
}

1

一个特定的小部件在其容器中的位置取决于它使用的布局管理器。布局管理器确定如何调整和排列小部件以使它们适当地适应。显然,内容窗格的默认布局决定将JLabel放置在顶部中心是最好的选择。

如果您想不使用布局管理器,而只是自己放置所有内容(这通常不是布局的最佳方式),则添加:

getContentPane().setLayout(null);

非常感谢,我遇到了另一个问题 - 我想将按钮的外观和感觉定制为特定平台,例如对于Windows,我将获得窗口样式按钮,而对于Mac。这是我尝试过的 - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - Yosi

0

使用布局管理器通常是一个更好的主意,因为它们允许组件进行动态调整大小。以下是您如何使用边界布局实现:

this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add (new JLabel ("Main title"), BorderLayout.NORTH);

如果您想在标签右侧添加内容,可以创建一个具有自己布局的附加面板:
// Create a panel at the top for the title and anything else you might need   
JPanel titlePanel = new JPanel (new BorderLayout());
titlePanel.add(new JLabel ("Main title"), BorderLayout.WEST);

// Add the title panel to the frame
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(titlePanel, BorderLayout.CENTER);

以下是一些有用的链接,可帮助您开始使用布局:

http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/visual.html http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/using.html


当我尝试使用以下代码的选项时: final JLabel mainTitle = new JLabel("IronApp - Choose and Play"); mainTitle.setFont(new Font("Consolas",1 , 28)); mainTitle.setBounds(100, 100, windowWidth, 50); mainTitle.setForeground(Color.WHITE); getContentPane().add(mainTitle,BorderLayout.NORTH);我无法控制标题的位置,将其向左、向下或向右移动。 - Yosi
@Yosy 使用自定义边框:http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/components/border.html - OscarRyz
通常在使用布局时,我尽量不指定硬编码的大小,除了水平和垂直间隙。相反,我使用边界布局将屏幕上的元素推到所需位置。如果您查看第一个链接中边框布局的图像,您会发现放置在NORTH位置的任何内容将占据整个空间的长度,并且仅需要所需的高度。因此,假设我想将标签向右推,我只需创建一个新面板,并将标签添加到东区域,从而将其有效地推向右侧。要将其推向左侧,请使用WEST。 - ZeBlob

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接