我需要将JLabel
放在我的JFrame
中。我创建了一个标签并希望设置其位置,但setAlignment
和setBounds
都不起作用。标签始终位于面板顶部,不会移动。
import java.awt.GridLayout;
import javax.swing.*;
public class Start extends JFrame {
//JLabel label1 = new JLabel("HELLO!");
//JLabel label2 = new JLabel("CHOOSE LANGUAGE:");
public Start() {
super();
setSize(480, 360);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
setLayout(new GridLayout(2, 1));
//setLayout(new FlowLayout());
JPanel panel1 = new JPanel();
add(panel1);
JLabel label1 = new JLabel("HELLO!");
//label1.setBounds(20,20,100,20);
//label1.SetAlignmentX(20);
//label1.SetAlignmentY(20);
panel1.add(label1);
}
public static void main(String[] args) {
Start frame = new Start();
frame.setVisible(true);
}
}
你可以帮忙吗?
答案 0 :(得分:1)
以最小尺寸提供ASCII艺术或GUI的预期布局的简单绘图,如果可调整大小,具有更大的宽度和高度 - 以显示应如何使用额外空间。这是我能从当前描述中猜出的最佳要求。
它显示如何在红色面板中将标签的左侧和顶部(使用EmptyBorder
)填充20个像素,在蓝色面板中填充100 x 30。
阅读代码中的注释以获取更多提示,并查看Java Docs以了解与原始源代码不同的任何使用方法。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Start extends JFrame {
public Start() {
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1));
JPanel panel1 = new JPanel(new FlowLayout(SwingConstants.LEADING));
panel1.setBorder(new LineBorder(Color.RED, 4));
add(panel1);
JLabel label1 = new JLabel("HELLO!", SwingConstants.LEADING);
//label1.setBounds(20,20,100,20);
// to provide a 20 x 20 offset, an empty border will do nicely.
label1.setBorder(new EmptyBorder(20, 20, 0, 0));
// Did you actually check the Java Docs for these methods?
// They do not do what you seem to think they do.
//label1.SetAlignmentX(20);
//label1.SetAlignmentY(20);
panel1.add(label1);
JPanel panel2 = new JPanel(new FlowLayout(SwingConstants.LEADING));
panel2.setBorder(new LineBorder(Color.BLUE, 4));
add(panel2);
JLabel label2 = new JLabel("HELLO!", SwingConstants.LEADING);
label2.setBorder(new EmptyBorder(30, 100, 30, 100));
panel2.add(label2);
pack();
}
public static void main(String[] args) {
Start frame = new Start();
frame.setVisible(true);
}
}