JLabel的分配问题:

时间:2018-02-24 21:06:39

标签: java 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

1 个答案:

答案 0 :(得分:0)

使用布局(默认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();
         }
      } );
   }
}