I have a fullscreen program, which draws a lot of things for the game I am making. The canvas is the entire 开发者_JS百科window, which it should be. Now I want to add a button, or textfield (JButton and JTextField etc...) to my window. However, when I add a button, or anything else, they go begind the canvas.
Do you have any idea how to get the button to show up ON the canvas, so I can click it?
Edit: Drawing code:
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);
}
}
Edit2: My frame is a JFrame.
It is difficult to tell much from the code snippet (please consider posting an SSCCE in future), but:
- Don't code AWT in this millennium.
- Don't mix Swing with AWT (at least until Java 7)
- Don't load images within the
draw()
method (which is presumably called from thepaintComponent()
method). - Note that custom painting in Swing can be done in a
JComponent
orJPanel
and that if the class is the latter, it can have a layout with other components added.
You are painting the canvas yourself so you will need to add the button elsewhere or paint an area that looks like a button and check if mouse events fall inside the button's area.
精彩评论