Threaded OverlayLayout仅打印空白方块而不是圆圈

时间:2017-09-18 13:59:33

标签: java multithreading swing

我在JFrame中打印了两个线程:
Thread-1:打印绿色方块
Thread-2:打印蓝色圆圈
为了使两个图形都出现在JFrame中,我将每个线程的布局设置为:

    setLayout(new OverlayLayout(this));
    setOpaque(false);

问题:蓝色圆圈在JFrame中显示为空白方块。只有绿色方块才能正确显示。

enter image description here

这是主要课程:

public class Main {

    public static void main(String[] args) {

        FigurePlacer circle = new FigurePlacer("circle");
        FigurePlacer square = new FigurePlacer("square");

        JFrame window = new JFrame();
        window.add(circle);
        window.add(square);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setTitle("Task");
        window.setSize(700, 700);
        window.setLocationRelativeTo(null);
        window.setVisible(true);
     }
}

这是螺纹类:

public class FigurePlacer extends JPanel implements Runnable{

    String figure;
    final int width = 700;
    final int height = 700;
    int x_pos = 0;
    int y_pos = 0;
    int x_width = 50;
    int y_height = 50;

    public FigurePlacer(String str){
        figure = str;
        randomCoord();
        Thread th = new Thread (this);
        th.start();
    }

    private void randomCoord(){ //this ramdomize x,y coord to place a new object
        Random random = new Random();
        x_pos = random.nextInt(width);
        y_pos = random.nextInt(height);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println(figure);
        switch (figure){
            case "square":     
            g.setColor(Color.GREEN);
            g.fillRect(x_pos, y_pos, x_width, y_height);
            break;

            case "circle":
            g.setColor(Color.BLUE);
            g.fillOval(x_pos, y_pos, x_width, y_height);
            break;
        }
    }

    @Override
    public void run(){ //paints the objects
        while (true){
            randomCoord();
            paintImmediately(x_pos, y_pos, x_width, y_height);
            try{
                Thread.sleep (50);
            }
            catch (InterruptedException ex){}
        }
    }  

}

1 个答案:

答案 0 :(得分:0)

setLayout(new OverlayLayout(this));
setOpaque(false);

在包含两个子面板的面板上设置非透明不会做任何事情。

   window.add(circle);
   window.add(square);

你需要制作" square"面板不透明,所以你可以看到"圆"面板。 (或使两个面板都不透明)。关键是当两个组件相互重叠时,顶部面板需要是非透明的。)

你的绘画代码仍然不正确。你有没有尝试调整框架的大小。如果你这样做,你会看到所有的方块都消失了。