在这里,我试图将组件(按钮)锚定到面板的一侧,但我的 GridBagConstraints 显然缺少一些东西。如果可能的话,我希望他们有填充;知道我会怎么做这样的事情吗?我可以只使用插图作为填充吗?为任何帮助而欢呼。
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
@SuppressWarnings("serial")
public class PlayGamePanel extends JComponent{
@SuppressWarnings("unused")
JComponent GamePanel2() throws IOException {
JComponent GamePanel = new JLabel();
//Setting up the gridbaglayout
GamePanel.setLayout(new GridBagLayout());
GridBagConstraints gbLayout = new GridBagConstraints();
/*//Creating a button to test out switching panels
*
JButton testButton = new JButton ("test");
GamePanel.add(testButton);*/
//Creating buttons for answering the quiz
gbLayout.gridx = 0;
gbLayout.gridy = 0;
gbLayout.weightx = 1.0;
gbLayout.anchor = GridBagConstraints.NORTHWEST;
gbLayout.insets = new Insets(20, 20, 20, 20);
JButton AnswerOneButton = new JButton("Answer One");
GamePanel.add(AnswerOneButton);
GamePanel.add(AnswerOneButton, gbLayout);
gbLayout.gridx = 0;
gbLayout.gridy = 0;
gbLayout.weightx = 1.0;
gbLayout.anchor = GridBagConstraints.NORTHEAST;
gbLayout.insets = new Insets(20, 20, 20, 20);
JButton AnswerTwoButton = new JButton("Answer Two");
GamePanel.add(AnswerTwoButton);
GamePanel.add(AnswerTwoButton, gbLayout);
gbLayout.gridx = 0;
gbLayout.gridy = 0;
gbLayout.weightx = 1.0;
gbLayout.anchor = GridBagConstraints.SOUTHEAST;
gbLayout.insets = new Insets(20, 20, 20, 20);
JButton AnswerThreeButton = new JButton("Answer Three");
GamePanel.add(AnswerThreeButton);
GamePanel.add(AnswerThreeButton, gbLayout);
gbLayout.gridx = 0;
gbLayout.gridy = 0;
gbLayout.weightx = 1.0;
gbLayout.anchor = GridBagConstraints.SOUTHWEST;
gbLayout.insets = new Insets(20, 20, 20, 20);
JButton AnswerFourButton = new JButton("Answer Four");
GamePanel.add(AnswerFourButton);
GamePanel.add(AnswerFourButton, gbLayout);
return GamePanel;
}
}