JPanel无法在同步

时间:2017-08-31 16:35:36

标签: java multithreading swing japplet

我试图在while循环中调用repaint()来改变文本的位置,并在线程结束后调用第二个线程来执行另一个动作。我发现的问题是在第一个线程等待结束并调用第二个线程后,第一个线程中的repaint()将不会运行,但它会在第一个线程完成后运行。我怎么能在synchronized函数中调用repaint()?

这是我的代码:

package com.lab02.inClass;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JApplet;
import javax.swing.JPanel;

public class StarWarsTitle extends JApplet {

    @Override
    public void init() {
        super.init();

        FirstPanel firstPanel = new FirstPanel(this);
        SecondPanel secondPanel = new SecondPanel(this);

        add(firstPanel);
        add(secondPanel);

        synchronized (firstPanel.thread) {
            firstPanel.thread.start();
            try {
                firstPanel.thread.wait();
                System.out.println("Hello World");
            } catch (InterruptedException e) {
            }
            secondPanel.thread.start();
        }

    }

}

class FirstPanel extends JPanel implements Runnable {

    StarWarsTitle applet;
    Thread thread;
    int pos_x, pos_y, fontSize = 40;

    public FirstPanel(StarWarsTitle applet) {
        this.applet = applet;
        thread = new Thread(this);
    }

    @Override
    public void run() {
        pos_x = applet.getWidth() / 2;
        pos_y = applet.getHeight();

        while (pos_y > 100) {
            pos_y--;
            System.out.println(pos_y);
            if (pos_y % 20 == 0 && fontSize >= 0)
                fontSize--;
            repaint();
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
            }
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("in paint component");
        Graphics2D g2d = (Graphics2D) g;
        g2d.setFont(new Font("Cordia New", Font.PLAIN, fontSize));
        g2d.drawString("Hello", pos_x, pos_y);
    }

}

class SecondPanel extends JPanel implements Runnable {

    StarWarsTitle applet;
    Thread thread;

    public SecondPanel(StarWarsTitle applet) {
        this.applet = applet;
        thread = new Thread(this);
    }

    @Override
    public void run() {
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setFont(new Font("Cordia New", Font.PLAIN, 40));
        g2d.drawString("Hello", 100, 100);
    }
}

0 个答案:

没有答案