我有一个全屏程序,它为我正在制作的游戏绘制了很多东西。画布是整个窗口,它应该是。现在我想在我的窗口中添加一个按钮或文本字段(JButton和JTextField等)。然而,当我添加一个按钮或其他任何东西时,它们会从画布开始。
你知道如何让按钮显示在画布上,这样我就可以点击它吗?
编辑:图纸代码:
public synchronized void draw(Graphics2D g) {
if (!welcome)
g.drawImage(background,0,0,null);
if (welcome) {
g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
}
else if (gettingName) {
setFont (new Font("Verdana", Font.ITALIC, 40));
g.draw3DRect(center.x -325, center.y -50, 650, 100, true);
g.drawString("Please enter your name", center.x -250, center.y -120);
g.drawString(name, center.x -315, center.y);
}
if (game) {
for (Player p: player) {
int x = center.x;
int y = center.y;
switch (p.getID()) {
case 1:
x -= name.length()*10;
y *= 1.4;
break;
case 2:
x -= name.length()*10;
y /= 1.4;
break;
case 3:
x *= 1.4;
x -= name.length()*10;
break;
case 4:
x *= 0.6;
x -= name.length()*10;
break;
default:
System.out.println("Error 2");
}
g.drawString(p.getName(),x,y);
}
for (int x = 0; x<13; x++) {
g.drawImage(diamonds[x].getImage(), (int) diamonds[x].getX(), (int) diamonds[x].getY(), null);
g.drawImage(clubs[x].getImage(), (int) clubs[x].getX(), (int) clubs[x].getY(), null);
g.drawImage(hearts[x].getImage(), (int) hearts[x].getX(), (int) hearts[x].getY(), null);
g.drawImage(spades[x].getImage(), (int) spades[x].getX(), (int) spades[x].getY(), null);
}
g.drawImage(put.getImage(), (int) put.getX(), (int) put.getY(), null);
}
if (won) {
g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
}
else if (lost) {
g.drawImage(new ImageIcon (getClass().getResource("images/backgroundWelcome.jpg")).getImage(), 0,0, null);
}
}
第2版:我的相框是JFrame。
很难从代码片段中分辨出多少(请考虑在未来发布SSCCE),但是:
- 不要在这个千年里对AWT进行编码
- 不要将Swing与AWT混合使用(至少在Java7之前)
- 不要在
draw()
方法(可能是从paintComponent()
方法调用的)中加载图像 - 请注意,Swing中的自定义绘制可以在
JComponent
或JPanel
中完成,如果类是后者,则可以添加其他组件的布局
您正在自己绘制画布,因此需要在其他地方添加按钮,或者绘制一个看起来像按钮的区域,并检查鼠标事件是否位于按钮的区域内。