我正在创建一个简单的骰子滚动仿真,当按下按钮时,骰子滚动骰子。我尚未添加动作侦听器,因为在将对象显示在框架上时遇到问题。我创建了一个类,该类生成一个骰子,并获得掷骰子的图像,并带有滚动的数字,但我似乎无法将该对象添加到我的框架中。
public class DieFrame extends JComponent
{
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 240;
private JButton rollButton;
private JLabel player1Score,player2Score, playerTurn;
Die die1 = new Die(1);
Die die2 = new Die(1);
public DieFrame()
{
JPanel panel = new JPanel();
player1Score = new JLabel("Player 1 score: ");
player2Score = new JLabel("Player 2 score: ");
panel.add(player1Score);
panel.add(player2Score);
panel.setBackground(Color.yellow);
add(panel, BorderLayout.NORTH);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
createPlayerTurnPanel();
createDiePanel();
}
public void createPlayerTurnPanel()
{
JPanel turnPanel = new JPanel();
playerTurn = new JLabel("Player ");
rollButton = new JButton("Roll");
turnPanel.add(playerTurn);
turnPanel.add(rollButton);
add(turnPanel, BorderLayout.SOUTH);
}
public void createDiePanel()
{
JPanel diePanel = new JPanel();
diePanel.add(die1);
diePanel.setBackground(Color.BLACK);
add(diePanel, BorderLayout.CENTER);
}
}
public class DieFrame extends JComponent
您的课程正在扩展JComponent。
add(panel, BorderLayout.NORTH);
您假设组件将使用BorderLayout。好吧,不是。它不使用任何布局管理器。
默认情况下,仅[JFrame(JDialog)的内容窗格将使用BorderLayout。
不扩展JComponent。它不能用作容器,如果尝试将其用作容器,则不能正常工作。
相反,尽管其布局管理器是FlowLayout,但可以扩展设计为用作容器的JPanel
,因此您需要将布局设置为BorderLayout
。
尽管您实际上也不应该扩展JPanel,因为您没有向面板添加新功能。相反,您应该创建一个类,该类将返回包含组件的面板。阅读Swing教程中有关How to Use Menus的部分。 MenuLookDemo
有使用此方法的有效示例。