Rus*_*nip 1 java swing layout-manager gridbaglayout
我正在尝试为类似于"谁想要成为百万富翁"的游戏创建一个界面,但我对布局没有运气.
我最近尝试的代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
中间和顶部的条带都是按钮
我尝试过使用其他布局,但每次按钮看起来太小而无法按预期使用.
任何人都可以建议布局的组合,以实现所需的布局(中心的问题和2x2网格中的4个答案选择)?
注意:我对stackoverflow完全不熟悉(不像我说的那么明显或任何东西).我无法对帖子或其他评论发表评论,因为我没有任何声誉,所以我尽力与你沟通-user1803551-这是我能看到如何通过编辑的唯一方式.建议别的东西,我会坚持这一点,但在那之前,如果你停止恢复这个帖子,我会很感激.
在你的代码只添加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());
}
}
Run Code Online (Sandbox Code Playgroud)
如果你不想搞乱GBL,复合布局方法将非常简单(可以根据要求进行演示).