gpt4 book ai didi

java - JLabel : 的对齐问题

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:14 26 4
gpt4 key购买 nike

我试图将 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();
}
} );
}
}

关于java - JLabel : 的对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48967609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com