我已经为我的骰子游戏创建了一个基本的UI。但是我的面板没有出现在JFrame
中。请帮我修复它。我是Java Swing的新手。
package View;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
*
* @author Akila
*/
public class MainUi extends JFrame {
public MainUi(){
initComponents();
}
public void initComponents() {
setTitle("Dice Game");
setVisible(true);
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
Container c = getContentPane();
// *******First Row Components*******
JPanel firstRow = new JPanel();
JLabel pc = new JLabel("PC Score");
JLabel user = new JLabel("User Score");
JLabel pcScore = new JLabel();
JLabel userScore = new JLabel();
// *******Second Row Components*******
JPanel secondRow = new JPanel();
JLabel pcFirstDice = new JLabel();
JLabel pcSecondDice = new JLabel();
JLabel pcThirdDice = new JLabel();
JLabel pcFourthDice = new JLabel();
JLabel pcFifthDice = new JLabel();
JCheckBox checkPcFirstDice = new JCheckBox();
JCheckBox checkPcSecondDice = new JCheckBox();
JCheckBox checkPcThirdDice = new JCheckBox();
JCheckBox checkPcFourthDice = new JCheckBox();
JCheckBox checkPcFifthDice = new JCheckBox();
// *******Third Row Components*******
JPanel thirdRow = new JPanel();
JLabel userFirstDice = new JLabel();
JLabel userSecondDice = new JLabel();
JLabel userThirdDice = new JLabel();
JLabel userFourthDice = new JLabel();
JLabel userFifthDice = new JLabel();
JCheckBox checkUserFirstDice = new JCheckBox();
JCheckBox checkUserSecondDice = new JCheckBox();
JCheckBox checkUserThirdDice = new JCheckBox();
JCheckBox checkUserFourthDice = new JCheckBox();
JCheckBox checkUserFifthDice = new JCheckBox();
// *******Fourth Row Components*******
JPanel fourthRow = new JPanel();
JButton throwDice = new JButton("Throw");
JButton updateScore = new JButton("Update Score");
// *******First Row GridBag Layout*******
firstRow.setSize(400, 100);
firstRow.setLayout(new GridBagLayout());
GridBagConstraints first = new GridBagConstraints();
first.weightx = 1;
first.weighty = 0.25;
// Add First Row Components
first.gridx = 1;
first.gridy = 0;
firstRow.add(pcScore,first);
c.add(firstRow,BorderLayout.NORTH);
}
}
最佳答案
您在这里遇到两个问题:
您忘记将行添加到框架:
c.add(secondRow);
c.add(thirdRow);
c.add(fourthRow)
c.add(firstRow);
您忘记将内容添加到行中(例如第一行的示例):
// *******First Row Components*******
JPanel firstRow = new JPanel();
JLabel pc = new JLabel("PC Score");
JLabel user = new JLabel("User Score");
JLabel pcScore = new JLabel();
JLabel userScore = new JLabel();
firstRow.add(pc);
firstRow.add(user);
firstRow.add(pcScore);
firstRow.add(userScore);
希望有帮助!