JLabel 的对齐问题:

Allignment issue with the JLabel:

我试图将我的 JLabel 对齐到屏幕顶部,但它却显示在底部。如果在setBounds中的Top-Bottom参数中设置一些负值是可以解决的,但是!我想知道为什么它会这样,以及如何以其他方式解决它。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class T2{
private JFrame jf;
private JLabel jL;
private JButton b1, b2;
private JRadioButton jr1;
private JTextField tf1, tf2;
private Font ft;

public void run(){
    //JFrame
    jf = new JFrame("Program");
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setVisible(true);
    jf.setLayout(null);
    jf.setBounds(0,40,500,500);

    //Container
    Container c = jf.getContentPane();

    //Font
    ft = new Font("Consolas",1,25);

    //JLABEL
    jL = new JLabel();
    jL.setText("Enter Name:");
    c.add(jL);;
    //Top-Bottom Positioning isn't working here..
    jL.setBounds(50, 0 , 600, 600);
    jL.setFont(ft);

    //JTextField
    tf1 = new JTextField("Type here...");
    c.add(tf1);
    tf1.setBounds(200, 0 , 200, 20);
}

public static void main(String args[]){
    T2 obj = new T2();
    obj.run();
}
}

截图如下: LINK

使用一个布局(默认的 BorderLayout 做你想做的),将你想要出现在顶部的组件添加到带有约束 "NORTH" 的布局中,然后神奇地一切正常。

代码中的进一步注释。

class T2 {

   private JFrame jf;
   private JLabel jL;
   private JButton b1, b2;
   private JRadioButton jr1;
   private JTextField tf1, tf2;
   private Font ft;

   public void run() {
      //JFrame
      jf = new JFrame( "Program" );
      jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
//      jf.setVisible( true ); // don't do this until the frame is composed
//      jf.setLayout( null );   // yucky in all respects
//      jf.setBounds( 0, 40, 500, 500 ); // use setSize() instead

      //Container
//      Container c = jf.getContentPane();  // normally you just call add()

      //Font
      ft = new Font( "Consolas", 1, 25 );

      // Make panel first         
      JPanel panelNorth = new JPanel();

      //JLABEL
      jL = new JLabel();
      jL.setText( "Enter Name:" );
      jL.setFont( ft );
      panelNorth.add( jL );
      //Top-Bottom Positioning isn't working here..
//      jL.setBounds( 50, 0, 600, 600 );

      //JTextField
      tf1 = new JTextField( "Type here..." );
//      c.add( tf1 );
      panelNorth.add( tf1 );
//      tf1.setBounds( 200, 0, 200, 20 );

      // now just add the panel to the "north" of the jframe border layout
      jf.add( panelNorth, BorderLayout.NORTH );

      // now make visible
      jf.setSize( 600, 480 );
      jf.setLocationRelativeTo( null );
      jf.setVisible( true );
   }

   public static void main( String args[] ) {

      // Swing is not thread safe, do on EDT
      SwingUtilities.invokeLater( new Runnable() {
         @Override
         public void run() {
            T2 obj = new T2();
            obj.run();
         }
      } );
   }
}