在JPanel上的特定位置设置JButton

时间:2016-04-13 08:35:10

标签: java jpanel jbutton

我有一个带有动画的jpanel,我想添加两个或更多按钮,例如start \ pause,ffw等。 我试图使用JButton.setBorders(),也改变了布局。但是当我使用setLayout()时,按钮显示在顶部屏幕上或相互重叠。如何将这两个按钮放在屏幕底部的每一侧(左侧和右侧)。 这是我的代码:

public class Animation extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;

private Cell[][] cellMatrix;
private Options op;
private Dimension expectedDimension;

private JPanel startButtonPanel;
private JPanel pauseButtonPanel;

private JButton startButton;
private JButton pauseButton;

Animation(Options received) {

    this.setLayout(new BorderLayout());

    startButton = new JButton("Start");
    startButtonPanel = new JPanel();
    startButtonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
    startButtonPanel.add(startButton);
    this.add(startButtonPanel,BorderLayout.SOUTH);

    pauseButton = new JButton("Pause");
    pauseButtonPanel = new JPanel();
    pauseButtonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    pauseButtonPanel.add(pauseButton);
    this.add(pauseButtonPanel,BorderLayout.SOUTH);


    this.op = received;

    expectedDimension = new Dimension((op.getNumberOfCells()*10) , (op.getNumberOfCells()*10));
    setPreferredSize(expectedDimension);
    setMaximumSize(expectedDimension);
    setMinimumSize(expectedDimension);


    this.cellMatrix = new Cell[op.getNumberOfCells()][op.getNumberOfCells()];
}

这是截图 As you can see the pause button has a huge size and also overlaps the start button

1 个答案:

答案 0 :(得分:0)

您可能希望南方面板在X轴上使用BoxLayout

按钮之间的水平胶水将确保每个按钮位于面板的一侧:

JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BoxLayout(buttonsPanel,BoxLayout.X_AXIS));

JButton pauseButton = new JButton("Pause");
buttonsPanel.add(pauseButton);

// create a glue between buttons
buttonsPanel.add(Box.createHorizontalGlue());


JButton startButton = new JButton("Start");
buttonsPanel.add(startButton);

this.add(buttonsPanel,BorderLayout.SOUTH);