我正在尝试为类似于“想要成为百万富翁”的游戏创建一个界面。但我对布局没有好运。
我最近尝试的代码:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class GameGUI extends JFrame //implements ActionListener
{
Container contentPane = getContentPane();
JPanel pnl = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton btnQuestion = new JButton();
JButton btnAnsA = new JButton();
JButton btnAnsB = new JButton();
JButton btnAnsC = new JButton();
JButton btnAnsD = new JButton();
Color customDarkGrey = new Color(20, 20, 20);
public GameGUI()
{
super("Game");
setExtendedState(JFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(EXIT_ON_CLOSE);
contentPane.setBackground(customDarkGrey);
contentPane.add(pnl); pnl.setOpaque(false);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
pnl.add(btnQuestion, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0.5;
c.ipadx = 40;
c.gridx = 1;
c.gridy = 0;
pnl.add(btnAnsA, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 0;
c.gridy = 1;
pnl.add(btnAnsA, c);
setVisible(true);
}
}
中间和顶部的条带是按钮
我尝试过使用其他布局,但每次按钮看起来都太小而无法按预期使用。
任何人都可以建议布局的组合来实现所需的布局(中心的问题和2x2网格中的4个答案选择)?
注意: 我对stackoverflow完全不熟悉(不像我说的那样明显或任何事情)。我无法对帖子或其他评论发表评论,因为我没有任何声誉,所以我尽力与您沟通-user1803551-这是我能看到如何通过编辑的唯一方式。建议别的东西,我会坚持这一点,但在那之前,如果你不再回复帖子,我会很感激。
答案 0 :(得分:5)
在您的代码中,您只是添加btnQuestion
和btnAnsA
,因此难怪无法运作。
无论如何,我使用了您最初的GridBagLayout
方法。
public class GameGUI extends JFrame {
JButton btnQuestion = new JButton("This is the Question");
JButton btnAnsA = new JButton("This is answer A");
JButton btnAnsB = new JButton("This is answer B");
JButton btnAnsC = new JButton("This is answer C");
JButton btnAnsD = new JButton("This is answer D");
public GameGUI() {
super("Game");
JPanel pnl = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
getContentPane().add(pnl);
c.weightx = 0.5;
c.weighty = 0.5;
c.insets = new Insets(5, 5, 5, 5);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
pnl.add(btnQuestion, c);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 1;
pnl.add(btnAnsA, c);
c.gridx = 1;
c.gridy = 1;
pnl.add(btnAnsB, c);
c.gridx = 0;
c.gridy = 2;
pnl.add(btnAnsC, c);
c.gridx = 1;
c.gridy = 2;
pnl.add(btnAnsD, c);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GameGUI());
}
}
如果您不想搞乱GBL,复合布局方法将非常简单(可以根据要求进行演示)。