Arp*_*pan 4 java swing jlabel jframe
我正在尝试在一个模式中创建40个动态JLabel,这工作得非常好但是最后一个JLabel没有根据模式放置.谁能告诉我我做错了什么?
这是我到目前为止所做的:
public class Booking2 {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setSize(700, 400);
jf.setLocationRelativeTo(null);
int c1 = 40;
int count = 0, count2 = 0, count3 = 0, count4 = 0, x;
JLabel[] jl = new JLabel[c1];
for (int i = 0; i <= c1 - 1; i++) {
jl[i] = new JLabel();
if (i <= 9) {
x = 25 * count;
jl[i].setBounds(x, 50, 20, 30);
count++;
}
if (i >= 10 && i <= 19) {
x = 25 * count2;
jl[i].setBounds(x, 80, 20, 20);
count2++;
}
if (i >= 20 && i <= 29) {
x = 25 * count3;
jl[i].setBounds(x, 110, 20, 20);
count3++;
}
if (i >= 30 && i <= 39) {
x = 25 * count4;
jl[i].setBounds(x, 130, 20, 20);
count4++;
}
// jl[i].setIcon(new
// ImageIcon(Booking2.class.getResource("booked.png")));
jl[i].setText("O");
jf.add(jl[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)

您正在使用绝对定位/ null布局,但您没有将布局设置为null.默认的jframe布局是边框布局.
添加此行
jf.setLayout(null);
Run Code Online (Sandbox Code Playgroud)
并在添加所有组件调用revalidate()和repaint()jframe方法之后.
例
public class Booking2 {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setLayout(null); // this is important
jf.setSize(700, 400);
int c1 = 40;
int count = 0, count2 = 0, count3 = 0, count4 = 0, x;
JLabel[] jl = new JLabel[c1];
for (int i = 0; i <= c1 - 1; i++) {
jl[i] = new JLabel();
if (i <= 9) {
x = 25 * count;
jl[i].setBounds(x, 50, 20, 20);
count++;
}
if (i >= 10 && i <= 19) {
x = 25 * count2;
jl[i].setBounds(x, 80, 20, 20);
count2++;
}
if (i >= 20 && i <= 29) {
x = 25 * count3;
jl[i].setBounds(x, 110, 20, 20);
count3++;
}
if (i >= 30 && i <= 39) {
x = 25 * count4;
jl[i].setBounds(x, 130, 20, 20);
count4++;
}
//jl[i].setIcon(new ImageIcon(Booking2.class.getResource("booked.png")));
jl[i].setText("O");
jf.add(jl[i]);
}
jf.revalidate();
jf.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)
产量

注意
1)你应该避免空布局.使用布局GRID布局似乎适合你的情况.如果这是一种游戏/动画,你应该看看这些例子https://www3.ntu.edu.sg/home /ehchua/programming/java/J8a_GameIntro-BouncingBalls.html.你可以使用paintComponent()方法在jpanel中绘制这个网格,这是有效的,你可以绘制任何类型的模式.如果你做一个大网格,例如100*100使用jlables它是不好的
2)最好将组件添加到jpanel而不是直接添加到jframe.你可以使用setContentPane()方法