在 Jframe 上的位置
Location on Jframe
我正在研究 game,但 JLabel 的位置存在一些问题。我有这个:
作为我的董事会。我正在尝试做两件事:
- 位置 "Ledu" 在蓝色板的顶部
- 在它下面插入一个随机生成的数字,这样我每次按图片它都会改变!
这是我的代码:
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bp.removeAll();
bp.revalidate();
bp.repaint();
BufferedImage mFrame2= null;
try {
mFrame2 = ImageIO.read(new File("B2.png"));
}
catch (IOException e1) {
e1.printStackTrace();
}
bp = new BackgroundPanel(mFrame2);
bp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel hi1 = new JLabel ("Ledu");
Font fs = hi1.getFont();
hi1.setFont(fs.deriveFont(30f));
c.ipady = 0; //reset to default
c.ipadx = 0;
c.anchor = GridBagConstraints.FIRST_LINE_END;
c.insets = new Insets(10,0,0,0); //top padding
bp.add(hi1, c);
mainf.setContentPane(bp);
};
});
mainf.pack();
mainf.setVisible(true);
我如何将标签定位在蓝色框的顶部,我需要做什么才能生成随机数,类似于掷骰子?
1.Locate Ludo on the top of the blue-ish board
嗯,我不知道那是什么意思。是不是表示在蓝色区域的绝对中心。还是表示top/left、top/center、top/right?
描述性更强,这样我们就不必猜测了。
现在在我看来标签位于整个图像的中心。这是 GridBagLayout 的默认行为。如果您不希望图片居中,则需要使用 weightx/weighty 约束条件。
阅读 Swing 教程中关于 How to Use GridBagLayout 的部分,了解有关约束如何工作的解释。
但是,我认为这不会解决您的问题,因为您无法相对于较大图像的 "blue" 区域定位组件。我建议您需要两张图片,一张用于游戏板,一张用于蓝色区域。然后就可以开始在蓝色区域相对定位组件了。
2.Insert an randomly generated number under it so that it changes each time I press an image!
按照上面的建议拆分图片后,您可以在第二张图片上使用垂直 BoxLayout。然后你可以显示两个标签,一个是文本,另一个是数字。
我正在研究 game,但 JLabel 的位置存在一些问题。我有这个:
作为我的董事会。我正在尝试做两件事:
- 位置 "Ledu" 在蓝色板的顶部
- 在它下面插入一个随机生成的数字,这样我每次按图片它都会改变!
这是我的代码:
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bp.removeAll();
bp.revalidate();
bp.repaint();
BufferedImage mFrame2= null;
try {
mFrame2 = ImageIO.read(new File("B2.png"));
}
catch (IOException e1) {
e1.printStackTrace();
}
bp = new BackgroundPanel(mFrame2);
bp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel hi1 = new JLabel ("Ledu");
Font fs = hi1.getFont();
hi1.setFont(fs.deriveFont(30f));
c.ipady = 0; //reset to default
c.ipadx = 0;
c.anchor = GridBagConstraints.FIRST_LINE_END;
c.insets = new Insets(10,0,0,0); //top padding
bp.add(hi1, c);
mainf.setContentPane(bp);
};
});
mainf.pack();
mainf.setVisible(true);
我如何将标签定位在蓝色框的顶部,我需要做什么才能生成随机数,类似于掷骰子?
1.Locate Ludo on the top of the blue-ish board
嗯,我不知道那是什么意思。是不是表示在蓝色区域的绝对中心。还是表示top/left、top/center、top/right?
描述性更强,这样我们就不必猜测了。
现在在我看来标签位于整个图像的中心。这是 GridBagLayout 的默认行为。如果您不希望图片居中,则需要使用 weightx/weighty 约束条件。
阅读 Swing 教程中关于 How to Use GridBagLayout 的部分,了解有关约束如何工作的解释。
但是,我认为这不会解决您的问题,因为您无法相对于较大图像的 "blue" 区域定位组件。我建议您需要两张图片,一张用于游戏板,一张用于蓝色区域。然后就可以开始在蓝色区域相对定位组件了。
2.Insert an randomly generated number under it so that it changes each time I press an image!
按照上面的建议拆分图片后,您可以在第二张图片上使用垂直 BoxLayout。然后你可以显示两个标签,一个是文本,另一个是数字。