各位程序员大家好!我正在尝试将两个 JLabel 添加到 JFrame,但添加标签的第二个添加方法似乎已经覆盖了我的第一个添加方法。我尝试通过使用 2 个不同的标签变量并使用 setLocation 方法为每个标签提供不同的坐标点来解决这个问题。但我似乎无法解决它。为什么我不能在程序中添加两个标签?顺便说一句,我没有收到任何错误。似乎更像是我无法解决的逻辑错误。
这是我当前的代码:
import javax.swing.*;
public class test {
private static JLabel label;
private static JLabel label1;
public static void main(String[] args){
initializeLabel();
initializeImage();
initializeFrame();
}
private static void initializeLabel(){
label = new JLabel();
label.setText("hi");
label.setLocation(54,338);
}
private static void initializeImage(){
label1 = new JLabel();
label1.setText("sss");
label1.setLocation(55, 340);
}
private static void initializeFrame(){
JFrame frame = new JFrame();
frame.add(label1);
frame.add(label);
frame.setVisible(true);
}
}// class
最佳答案
按照以下方式更改您的代码。
private static void initializeFrame(){
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout()); // <-- you need this for now
frame.add(label1);
frame.add(label);
frame.setVisible(true);
// optional, but nice to have.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
请在此处详细了解 Swing 布局:A Visual Guide to Layout Managers
关于java - 在java中添加更多标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8046444/