jack sexton
jack sexton

Reputation: 1287

Java graphics, nothing shows up

I might be doing something really stupid and can't see it but I've been trying to animate the resizing of a rectangle to be used for a bar graph. The code complies but nothing is showing up in my frame. Its completely blank.

    package server2;

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Bar extends JPanel implements Runnable {

    int height = 0;
    Color barColor;
    Rectangle bar;
    Thread bartender;

    public Bar(int x, int y, Color barColor) {
        this.barColor=barColor;
        this.bar = new Rectangle(x, y, 15, this.height);
        this.bartender= new Thread(this);
    }

    public void update() {
        bar.setSize(this.bar.width, this.bar.height++);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(this.barColor);
        g2d.fill(this.bar);
    }

    public void callBarTender() {
        this.bartender.notify();
    }

    @Override
    public void run() {
        for(int i = this.bar.height; i<this.height; i++ ) {
            try {
                update();
                repaint();
                Thread.sleep(30);
            } catch(Exception e) {
                System.out.println(e);
            }
        }
        try {
            this.bartender.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(400, 400);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        Bar bar1 = new Bar(200,200, Color.blue);
        bar1.setVisible(true);
        frame.add(bar1);
        bar1.height = 10;
        bar1.bartender.start();

    }

Upvotes: 0

Views: 328

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

Change...

bar.setSize(this.bar.width, this.bar.height++);

to

bar.setSize(this.bar.width, this.bar.height + 1);

or

bar.setSize(this.bar.width, ++this.bar.height);

The assignment of this.bar.height++ is a post assignment which is getting ignored

You should also switch the order of these two lines...

bar1.setVisible(true);
frame.add(bar1);

so setVisible is called AFTER you've prepared the UI.

You should also consider using a Swing Timer which is safer for updating the UI or any data the UI might rely on for painting

Upvotes: 1

Related Questions