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。

4

3 回答 3

3

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

您必须了解它们如何工作才能有效地使用它们。您可以将布局管理器设置为 null,并自己进行布局,但不建议您这样做,因为您每次都必须跟踪新组件,并在窗口移动缩小时自行执行布局计算等。

布局管理器起初有点难以掌握。

你的窗口可能是这样的:

就这么简单

使用此代码:

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

    }
}
于 2010-07-19T17:57:44.683 回答
1

特定小部件最终在其容器中的位置取决于它使用的布局管理器。布局管理器决定如何调整和排列小部件以使其适合。显然,内容窗格的默认布局决定顶部中心是放置 JLabel 的最佳位置。

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

getContentPane().setLayout(null);
于 2010-07-19T17:41:03.447 回答
0

Using layouts is usually a better idea since they allow for dynamic resizing of components. Here's how you'd do it with a BorderLayout:

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

If you want to add something to the right of the label you could create an additionnal panel with it's own layout :

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

Here are some usefull links to get started with layouts:

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

于 2010-07-19T18:11:04.740 回答