Java在JPanel具体位置上加入JLabel

怎么把一个JLable加到JPanel的具体位置 如确定X,Y坐标 中?
2024-12-18 20:10:07
推荐回答(2个)
回答1:

例如下面这一段 其中 .setBounds(jlabel的左上顶点与jpanel的左上顶点水平距离,垂直距离,组件长度,组件宽度)
public class LogOn extends JPanel implements ActionListener{

JLabel user=new JLabel("UserName:");
JLabel password=new JLabel("Password:");

JTextField userIn=new JTextField(10);
JPasswordField passwordIn=new JPasswordField(10);

JButton confirm=new JButton("continue");

public LogOn(){
add(user);
add(password);
add(userIn);
add(passwordIn);
add(confirm);

confirm.addActionListener(this);

setLayout(null);
user.setBounds(130,80,100,30);
password.setBounds(130,120,100,30);
userIn.setBounds(220,85,100,20);
passwordIn.setBounds(220,125,100,20);
confirm.setBounds(175,180,100,25);
}

回答2:

有个布局管理器,叫做LayoutManager,算了,干脆给你个例程:

import javax.swing.*;
import java.awt.*;
import tools.swing.Console;

public class BorderLayout1 extends JApplet {
public void init() {
Container cp=getContentPane();
cp.add(BorderLayout.NORTH,new JButton("North"));
cp.add(BorderLayout.SOUTH,new JButton("South"));
cp.add(BorderLayout.WEST,new JButton("West"));
cp.add(BorderLayout.EAST,new JButton("East"));
cp.add(BorderLayout.CENTER,new JButton("Center"));
}
public static void main(String[] args) {
Console.run(new BorderLayout1(),300,250);
}
}
//BorderLayout.NORTH 就是一种布局管理方案
//BorderLayout.CENTER 就是中间布局
//具体你去看API,在javax.swing.*;下BorderLayout