将物体放在框架上 [英] Putting objects onto Frames
问题描述
我正在创建一个简单的骰子滚动仿真,当按下按钮时,骰子滚动骰子.我尚未添加动作侦听器,因为在将对象显示在框架上时遇到了问题.我创建了一个类,该类生成一个骰子,并获得掷骰子的图像,并带有滚动的数字,但是我似乎无法将该对象添加到我的框架中.
I am creating a simple die rolling simulation that rolls dice when a button is pressed. I didn't add the action listener yet because I have a problem with showing up an object onto my frame. I created a class that generates a dice and gets an image of the dice with the number rolled but I can't seem to add the object onto my frame.
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.
Your class is extending JComponent.
add(panel, BorderLayout.NORTH);
您假设组件将使用BorderLayout.嗯,事实并非如此.它不使用任何布局管理器.
You are assuming the component will use a BorderLayout. Well it doesn't. It doesn't use any layout manager.
默认情况下,只有JFrame(JDialog)的内容窗格将使用BorderLayout.
Only the content pane of a JFrame (JDialog) will use a BorderLayout by default.
不扩展JComponent.它并非旨在用作容器,并且如果您尝试将其用作容器,则将无法正常工作.
Don't extend JComponent. It is not designed to be used as a container and will not work properly if you attempt to use it as a container.
相反,您可以扩展设计为用作容器的 JPanel
,尽管其布局管理器是FlowLayout,所以您需要将布局设置为 BorderLayout
.
Instead you can extend JPanel
which is designe to be used as a containter, although its layout manager is a FlowLayout, so you will need to set the layout to a BorderLayout
.
尽管您实际上也不应该扩展JPanel,因为您没有向面板添加新功能.相反,您应该创建一个类,该类将返回包含组件的面板.阅读有关如何使用菜单的Swing教程中的部分.. MenuLookDemo
有使用此方法的有效示例.
Although you really should not be extending JPanel either since you are not adding new functionality to the panel. Instead you should create a class that will return you a panel with the components. Read the section from the Swing tutorial on How to Use Menus. The MenuLookDemo
has a working example using this approach.
这篇关于将物体放在框架上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!