【发布时间】:2017-04-18 21:58:46
【问题描述】:
我想在我的 JPanel 上放置 2 个 JButton,其中一个居中,另一个位于 JPanel 的右上角。 JPanel 与包含 JPanel 的 JFrame 大小相同。如何使用 GridBagLayout 和 GridBagConstraints 做到这一点?
public class MyPanel extends JPanel {
public MyPanel() {
JButton btnGame1 = new JButton("Game 1");
JButton btnExitFrame = new JButton("Exit");
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_START;
c.weighty = 1;
c.gridx = 0;
add(btnGame1, c);
c.gridx = 1;
c.anchor = GridBagConstraints.FIRST_LINE_END;
add(btnExitFrame, c);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
camickr 的 MCVE
public class MyPanel extends JPanel {
static JFrame frame = new JFrame();
public MyPanel() {
JButton btnGame1 = new JButton("Game 1");
JButton btnExitFrame = new JButton("Exit");;
setLayout(new BorderLayout());
JPanel top = new JPanel( new FlowLayout(FlowLayout.RIGHT) );
top.add( btnExitFrame );
JPanel center = new JPanel(new GridBagLayout());
center.add(btnGame1, new GridBagConstraints());
add(top, BorderLayout.PAGE_START);
add(center, BorderLayout.CENTER);
}
public static void main(String[] args) {
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
固定 SOL'N:
public class MyPanel extends JPanel {
static JFrame frame = new JFrame();
public MyPanel() {
JButton btnGame1 = new JButton("Game 1");
JButton btnExitFrame = new JButton("Exit");;
int nOfCells = 3;
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1;
for(int i = 0; i < nOfCells; i++){
for(int j = 0; j < nOfCells; j++){
c.gridx = i;
c.gridy = j;
if(i == 1 && j == 0) {
c.anchor = c.PAGE_START;
add(btnGame1, c);
c.anchor = c.CENTER;
}
else if(i == 2 && j == 0) {
c.anchor = c.FIRST_LINE_END;
add(btnExitFrame, c);
c.anchor = c.CENTER;
}
else {
c.fill = c.BOTH;
add(Box.createRigidArea(new Dimension(frame.getWidth()/nOfCells, frame.getHeight()/nOfCells)), c);
c.fill = c.NONE;
}
}
}
}
public static void main(String[] args) {
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
【问题讨论】:
标签: java swing jbutton gridbaglayout