我正在开发一个游戏菜单,我在 MenuPanel 上实现了三个 JButton,但是,我无法更改 JButton 的大小或位置。我尝试过 setBounds 函数,但没有任何结果。谁能帮我?
public class MenuPanel extends JPanel implements ActionListener
{
private JButton playKnop, highScoreKnop, quitKnop;
private MijnProject mainVenster;
public MenuPanel(MijnProject mainVenster)
{
this.mainVenster = mainVenster;
playKnop = new JButton("Play");
playKnop.addActionListener(this);
playKnop.setBounds(200, 200, 20, 20);
quitKnop = new JButton("Quit");
quitKnop.addActionListener(this);
highScoreKnop = new JButton("High Scores");
highScoreKnop.addActionListener(this);
this.add(playKnop);
this.add(quitKnop);
this.add(highScoreKnop);
}
最佳答案
您可以使用setSize(int width, int height)
方法。例如,如果您想要一个 100 像素宽、20 像素高的按钮作为 quitKnop 按钮,您可以编写以下行
quitKnop.setSize(100,20);
就位置而言,您应该查看布局管理器,正如 @Code-Apprentice 在问题下方的评论中首先提到的那样。它们将允许您组织按钮。您应该使用那里的边距来添加空间。如果您希望按钮转到特定点,可以使用 setLocation(int x, int y)
方法,但我不建议在这种情况下使用它。
关于java - 如何改变JButton的位置和大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55910972/