I created a Jframe using netbeans drag-n-drop designer. After asking here , I can make the color changing works after changing the color of some item from recList
and paint(g)
on a new thread of my Draw
class.
Now I want to add another JComponent like DrawCar
that will add the car
image to the Jframe. I want this new JComponent because I don't want to re-render the "car" if the squares in the background change color.
So I created the DrawCar
with paint()
method like below:
public void paint(Graphics g) {
//This to make the (0,0) at the bottom-left not top-left as default.
Graphics2D g2 = (Graphics2D)g;
AffineTransform at = g2.getTransform();
at.translate(0, getHeight());
at.scale(1, -1);
g2.setTransform(at);
//Below is to draw the car
try {
image = ImageIO.read(new File("car.png"));
} catch (IOException ex) {
Logger.getLogger(Car.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
g.drawImage(image, 245, 0, null);
}
If I put these code to render the car in the paint()
method of Draw
class, it works, so no problem with this code!
In the Container
(the class with the GUI) class, I have a button handler. I want the car appear when I click that button, so I tried to add to the event handler with
private void starter_btnActionPerformed(java.awt.event.ActionEvent evt) {
Thread reDraw = new Thread(new Runnable() {
@Override
public void run() {
//draw1 below is the instance of "Draw" class
//draw1.paint2(draw1.getGraphics()); //This code works with repainting the square with new color as mentioned before
DrawCar draw2 = new DrawCar();
repaint();
revalidate();
}
});
reDraw.start();
}
but it won't work, I don't know what I missed here. Maybe some ways to add the DrawCar
to the current JFrame?
Thank you for your time!
EDIT:
I just make a simple project to make it clear. I created a JFrame named Test
and drop in it a button that will show the picture when I click on it. It's all auto-generated codes.
Now I create a new class call MyClass
public class MyClass extends JComponent{
private BufferedImage image;
MyClass(){
try {
image = ImageIO.read(new File("D://pic.jpg"));
} catch (IOException ex) {
Logger.getLogger(this.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image, 50, 50, null);
}
}
And in the Test
, the event handler of the button is like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MyClass mc = new MyClass();
add(mc);
repaint();
revalidate();
}
I clicked it and nothing happens. The picture is supposed to shows up on click. How do I make it happens? Thank you
EDIT 2:
This is the image of what I want to achieve, it's the little green car on the bottom, it should appears only when I click "Start!"