开发者

Dont know how to call paint method

开发者 https://www.devze.com 2023-02-20 17:20 出处:网络
Hi i want to know how to call the paint method... I am a novice programmer and am really just experimenting with things开发者_JAVA百科 like paint.

Hi i want to know how to call the paint method...

I am a novice programmer and am really just experimenting with things开发者_JAVA百科 like paint.

The program i am trying to make is the game where there are 3 rungs and the aim of the game is to move different sized disks from the left/right rung to the right/left rung.

here is my code(no where near finished give me a break):

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int amount = 0;

    // get the amount of rectangles to draw to represent disks
    while (amount <= 1 && amount >= 5) {
        System.out.print("Please enter amount of discs to use(less than 7 more than one).");
        amount = scan.nextInt();            
    }
}

public void paint(Graphics g) {
    // draw a certain amount of rectangles in ascending order
    if (amount <= 1 && amount >= 5) {
        for (int i = 0; i < amount; i++) {
            g.fillRect(220 - (20 * i), 200 + (10 * i), 100 - (20 * i), 20);
        }
    }
}


The paint method will be called for the first time upon creation of the object.

To force the paint() method to be called again you can either call update(Graphics g) if you want to pass in a new Graphics object, but normally I would suggest using repaint() method, since this way it will be scheduled to be called asap.


You don't need to call it. Instead, you should use the main loop which Java creates for you.

The usual approach is to extend JPanel (see this question: How to make canvas with Swing?) and override the paint() method.

Now create a JFrame, add the new UI component to it and open the frame. Java will then make sure it gets rendered.


I am not expert or something else to teach others but you need to put your code to be painted to paintComponent(Graphics g) method instead of paint and then call repaint method.

0

精彩评论

暂无评论...
验证码 换一张
取 消