1
我试图以特定方式定位六个按钮,但目前输出几乎是正确的,但按钮并不是我希望它们处于的确切位置(与所有按钮触摸相邻的按钮,无间隙)。这是显示如下:在JPanel中以特定方式定位按钮
有人能看看我的代码,看看为什么定位不准确?
public void createDirectionButtonPanel() {
JButton northButton = new JButton("north");
JButton southButton = new JButton("south");
JButton westButton = new JButton("west");
JButton eastButton = new JButton("east");
JButton upButton = new JButton("up");
JButton downButton = new JButton("down");
JPanel directionButtonPanel = new JPanel();
// directionButtonPanel.setOpaque(false);
directionButtonPanel.setLayout(new BoxLayout(directionButtonPanel, BoxLayout.Y_AXIS));
JPanel directionRow_1 = new JPanel();
// directionRow_1.setOpaque(false);
directionRow_1.setLayout(new BoxLayout(directionRow_1, BoxLayout.X_AXIS));
directionRow_1.add(Box.createRigidArea(northButton.getPreferredSize()));
directionRow_1.add(northButton);
directionRow_1.add(Box.createRigidArea(northButton.getPreferredSize()));
directionRow_1.add(upButton);
JPanel directionRow_2 = new JPanel();
// directionRow_2.setOpaque(false);
directionRow_2.setLayout(new BoxLayout(directionRow_2, BoxLayout.X_AXIS));
directionRow_2.add(westButton);
directionRow_2.add(Box.createRigidArea(northButton.getPreferredSize()));
directionRow_2.add(eastButton);
directionRow_2.add(Box.createRigidArea(northButton.getPreferredSize()));
JPanel directionRow_3 = new JPanel();
// directionRow_3.setOpaque(false);
directionRow_3.setLayout(new BoxLayout(directionRow_3, BoxLayout.X_AXIS));
directionRow_3.add(Box.createRigidArea(northButton.getPreferredSize()));
directionRow_3.add(southButton);
directionRow_3.add(Box.createRigidArea(northButton.getPreferredSize()));
directionRow_3.add(downButton);
upButton.setMaximumSize(southButton.getPreferredSize());
northButton.setMaximumSize(southButton.getPreferredSize());
westButton.setMaximumSize(southButton.getPreferredSize());
southButton.setMaximumSize(southButton.getPreferredSize());
downButton.setMaximumSize(southButton.getPreferredSize());
eastButton.setMaximumSize(southButton.getPreferredSize());
directionButtonPanel.add(directionRow_1);
directionButtonPanel.add(directionRow_2);
directionButtonPanel.add(directionRow_3);
}
1,simpest是通过将12个JButtuns(休息不应该调用setVisible(假)),2。更好的是搜索这里操纵杆或东西,看起来像作为导航键(如电视遥控) – mKorbel 2014-12-04 11:03:25
所以上面的图像是你需要的吗?或者你从显示的代码中得到了什么?我很困惑..使用'GridLayout'很容易创建图像。 – 2014-12-04 11:23:22
'GridBagLayout' .... – MadProgrammer 2014-12-04 12:03:49