このプログラムを実行すると、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);
}
}