【发布时间】:2015-01-26 13:58:35
【问题描述】:
我正在尝试将三个按钮设置在此 JPanel 的中间,该按钮设置在另一个面板上方。
一切正常,但无论如何,三个按钮都保持在同一位置。
如何移动panel2 中心的三个按钮?现在这三个按钮位于panel2 的中心左侧。
我的面板代码在这里:
public AbcGeniusPanel()
{
//this.setVisible(false);
ImageIcon[] alphabets = new ImageIcon[26];
ImageIcon[] images = new ImageIcon[26];
setBackground(Color.yellow);
//Load the images for alphabet images into the alphabets array using a for loop
for(int i = 0; i < alphabets.length; i++)
{
alphabets[i] = new ImageIcon("C:\\Users\\Dip\\Desktop\\Java Projects\\AbcGeniusApp\\src\\Alphabets\\"+(i+1)+".png");
}
//Load the images images in the IMageIcon array
for(int i = 0; i < images.length; i++)
{
images[i] = new ImageIcon("C:\\Users\\Dip\\Desktop\\Java Projects\\AbcGeniusApp\\src\\Images\\"+(i+1)+".png");
}
//Create two JPanel objects
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
//Set a layoutManager on the panel
panel.setLayout(new GridLayout(2, 13, 5, 5)); //This is good for now
//Create an array for holdoing the buttons
buttons = new JButton[26];
/
//Try passing Images inside the JButton parameter later.
for(int i = 0; i < 26; i++)
{
buttons[i] = new JButton(alphabets[i]);
}
setLayout(new BorderLayout(2,0));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
//add the panel to the Border layout
add(panel,BorderLayout.SOUTH);
add(panel2);
//Add evenHandling mechanism to all the buttons
for(int k = 0; k<26; k++)
{
buttons[k].addActionListener(this);
}
for(int count1 = 0; count1<26; count1++)
{
panel.add(buttons[count1]);
}
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
}
【问题讨论】:
-
我对Center left 的真正含义感到困惑。是中心还是左边?无论如何,使用具有适当对齐方式的简单 FlowLayout 应该会给您预期的布局
-
这里是输出tinypic.com/r/1z4ki2b/8 的链接,按钮位于左侧,无法移动。但无论如何,谢谢,我会尝试不同对齐方式的 Flowlayout。
标签: swing jpanel awt layout-manager boxlayout