问题
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);
}
}
回答1:
public class DieFrame extends JComponent
Your class is extending JComponent.
add(panel, BorderLayout.NORTH);
You are assuming the component will use a BorderLayout. Well it doesn't. It doesn't use any layout manager.
Only the content pane of a JFrame (JDialog) will use a BorderLayout by default.
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.
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
.
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.
来源:https://stackoverflow.com/questions/62354207/putting-objects-onto-frames