如何解决JButton 的 GridBagLayout 格式
我和我的搭档正在为游戏编写这个程序。他为我们的网格使用了 GridBagLayout
,我正在尝试解决网格的一些问题。
代码如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@SuppressWarnings("serial")
public class NewGame extends JFrame{
private int width = 500,height = 500,xSquares = 4,ySquares = 4;
Font buttonFont = new Font("Times New Roman",Font.PLAIN,15);
endGame end = new endGame();
public NewGame() {
super("OnO");
// gridbaglayout is flexible but kinda complicated
GridBagLayout Griddy = new GridBagLayout();
this.setLayout(Griddy);
JPanel p = new JPanel();
p.setLayout(Griddy);
this.add(p);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 4;
c.gridheight = 4;
NewBoard board = new NewBoard(xSquares,ySquares);
// board at top left
c.gridx = 0;
c.gridy = 0;
this.add(board,c);
// find a way to make buttons smaller
JButton EndGame = new JButton("End");
EndGame.setBackground(Color.black);
EndGame.setForeground(Color.white);
EndGame.setFont(buttonFont);
EndGame.addActionListener(end);
JButton Undo = new JButton("Undo");
Undo.setBackground(Color.black);
Undo.setForeground(Color.white);
Undo.setFont(buttonFont);
JButton NewGame = new JButton("New Game");
NewGame.setBackground(Color.black);
NewGame.setForeground(Color.white);
NewGame.setFont(buttonFont);
// fit 3
c.gridwidth = 1;
c.gridheight = 1;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(EndGame,c);
c.gridx = 2;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(Undo,c);
c.gridx = 3;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(NewGame,c);
this.setPreferredSize(new Dimension(width,height));
this.setDefaultCloSEOperation(EXIT_ON_CLOSE);
this.pack();
this.setLocation(450,30);
this.setVisible(true);
}
public class endGame implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
}
public class newGame implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
}
当此代码与我们程序中的其他类一起运行时,endGame
、Undo
和 NewGame
按钮与板重叠:
我想找到一种方法,在单独的空间中显示板子上方或下方的 3 个按钮,但我已经修改了很长时间的代码,但还没有找到解决方案。我不确定我应该在这里做什么。
解决方法
首先,变量名不应以大写字符开头。学习并遵循 Java 命名约定。
我想找到一种方法来显示板子上方或下方的 3 个按钮
最简单的解决方案是不对框架使用 GridBagLayout。
只需使用框架的默认 BorderLayout
。然后,您可以将 JPanel 与 FlowLayout 用于按钮,并为板面板使用 GridLayout。
基本逻辑是:
JPanel buttons = new JPanel();
buttons.add(endGame);
buttons.add(undo);
buttons.add(newGame);
this.add(button,BorderLayout.PAGE_START);
NewBoard board = new NewBoard(xSquares,ySquares);
this.add(board,BorderLayout.CENTER);
默认情况下,JPanel 使用 FlowLayout
,因此按钮将显示在一行中。
阅读 Layout Managers 上的 Swing 教程,了解更多信息和工作示例,以更好地了解此建议的工作原理。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。