代码之家  ›  专栏  ›  技术社区  ›  Yosi

Java Swing-JLabel位置

  •  4
  • Yosi  · 技术社区  · 16 年前


    我将内容窗格设置为一些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 回复  |  直到 16 年前
        1
  •  3
  •   Glorfindel Doug L.    7 年前

    Swing使用 Layout Managers

    你必须了解它们是如何有效使用的。您可以将布局管理器设置为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 );
    
        }
    }
    
        2
  •  1
  •   Jonathan M Davis    16 年前

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

    getContentPane().setLayout(null);
    
        3
  •  0
  •   ZeBlob    16 年前

    使用布局通常是一个更好的主意,因为它们允许动态调整组件的大小。下面是如何使用边框布局:

    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