线程不想工作

时间:2014-02-15 02:44:53

标签: java multithreading swing paint

如果有这样的话,有人可以解释如何画画,以及为什么不画画会很棒!

public class Main extends JPanel implements Runnable {

    public void run() {

        System.out.println("g");
        repaint();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(50, 50, 200, 200);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Physics!");
        frame.setSize(500, 500);
        frame.setBackground(Color.BLUE);
        frame.setVisible(true);

        Main physics = new Main();
        Thread t = new Thread(physics);
        t.start();
    }

}

3 个答案:

答案 0 :(得分:1)

您必须将JPanel添加到JFrame:

    JFrame frame = new JFrame("Physics!");
    Main physics = new Main();
    Thread t = new Thread(physics);
    t.start();
    frame.setContentPane(physics); // Add it like this
    frame.setSize(500, 500);
    frame.setBackground(Color.BLUE);
    frame.setVisible(true);

答案 1 :(得分:1)

您永远不会将physics添加到JFrame

Main physics = new Main();
JFrame frame = new JFrame("Physics!");
frame.add(physics);

旁注

  • JPanel覆盖getPreferredSize()上进行绘画,以便面板具有首选尺寸时,您只需pack()框架,因为应该正在做,而不是设置它的大小

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 500);
    }
    ...
    frame.pack();
    // frame.setSize(500, 500);
    
  • 此外,paintComponent应为protected而不是public

  • 另请参阅Initial Threads在事件发送线程上运行Swing应用程序

答案 2 :(得分:-1)

尝试在t.start()之后将t.join()放在main方法中。您的main方法应该等待线程完成。