java无法将JButton置于中心位置
我需要一些帮助来调整我的钮扣。现在,它们水平居中,但它们拒绝垂直居中。这是两类游戏和菜单的代码。另外,是否可以使用blocklayout在我的按钮之间放置空格
游戏类:
package main;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JFrame{
private static final long serialVersionUID = -7071532049979466544L;
public static final int WIDTH = 1280, HEIGHT = WIDTH/12 * 9;
private Handler handler;
public STATE state = STATE.Menu;
JPanel screen;
//State of the game
public enum STATE{
Menu,
DeckConstructor,
Game;
}
//Game Launch
public Game() {
screen = new JPanel(new CardLayout());
screen.add(new Menu(this).getMenu(), "MENU");
screen.add(new DeckConstructor(this).getDeckConstructor(), "DECK_CONSTRUCTOR");
getContentPane().add(screen,BorderLayout.CENTER);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
setVisible(true);
}
public static void main(String[]args){
new Game();
}
}
菜单类:
package main;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Menu extends JFrame implements ActionListener{
private JPanel buttonPanel;
private JButton play;
private JButton deckConstructor;
private JButton quit;
private Game game;
public Menu(Game game){
this.game = game;
buttonPanel = new JPanel();
play = new JButton("Play");
play.addActionListener(this);
deckConstructor = new JButton("Deck Constructor");
deckConstructor.addActionListener(this);
quit = new JButton("Quit");
quit.addActionListener(this);
buttonPanel.add(play);
buttonPanel.add(deckConstructor);
buttonPanel.add(quit);
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
play.setAlignmentX(Component.CENTER_ALIGNMENT);
deckConstructor.setAlignmentX(Component.CENTER_ALIGNMENT);
quit.setAlignmentX(Component.CENTER_ALIGNMENT);
}
public JPanel getMenu(){
return buttonPanel;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(deckConstructor.equals((JButton) e.getSource())){
CardLayout c1 = (CardLayout)(game.screen.getLayout());
c1.show(game.screen, "DECK_CONSTRUCTOR");
}
}
}
# 1 楼答案
我使用了GridBagLayout和GridBagConstraints而不是BoxLayout
代码:
为了使它居中,我使用了GridBagConstraints#anchor并添加了间距, 我用了GridBagConstraints#insets
原始框架:
使用GridBagLayout的框架: