当我运行此程序时,带有6个按钮的面板应显示在屏幕底部,并且前3个标签显示为它们应该和应该在哪里,但最后一个标签出现在大约中心位置屏幕。此外,当我单击并拖动窗口的右下角(调整窗口大小)时,面板和最后一个标签会移动,因此它们会保持与窗口大小相对的位置,但前3个标签会保留在指定的位置位置。当我向底部添加空白JLabel的代码行取消注释时,所有4个标签现在都在正确的位置,当我调整窗口大小时,只有面板移动。有人可以解释一下这里发生了什么吗?提前谢谢!
import javax.swing.*;
import java.awt.*;
public class X extends JFrame{
private JPanel panel;
private JButton buttons[];
private JLabel labels[];
private Icon images[];
public X()
{
panel = new JPanel();
panel.setPreferredSize(new Dimension(470,110));
buttons = new JButton[6];
labels = new JLabel[4];
Dimension dim = new Dimension(75,100);
labels = new JLabel[4];
images = new Icon[6];
for(int i = 0; i<6;i++)
images[i] = new ImageIcon(getClass().getResource("image" + i + ".gif"));
int j = 5;
while( j >= 0 ){
Icon image = images[j];
buttons[j] = new JButton(image);
buttons[j].setPreferredSize(dim);
panel.add(buttons[j]);
j--;
}
add(panel, BorderLayout.SOUTH);
j = 3;
while( j>=0){
Icon image = new ImageIcon(getClass().getResource("image6.gif"));
labels[j] = new JLabel(image);
labels[j].setPreferredSize(dim);
if (j==3){
labels[j].setBounds(200,135,75,100);
}
else if (j==2){
labels[j].setBounds(313,70,75,100);
}
else if (j==1){
labels[j].setBounds(425,135,75,100);
}
else if (j==0){
labels[j].setBounds(313,200,75,100);
}
add(labels[j]);
j--;
}
// add(new JLabel());
}
public static void main(String[] args) {
X frame = new X();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,500);
frame.setVisible(true);
}
}
答案 0 :(得分:0)
1)您应该阅读JPAnel / JButton / JLabel的Javadocs及其默认行为。
2)您应该确保您发布的代码编译
3)您应该确保发布的代码AS说明了您的问题
因为这是你的帖子不符合要求2)和3)你可能没有阅读足够的1)