【问题标题】:Thread not wanting to work线程不想工作
【发布时间】:2014-02-15 02:44:52
【问题描述】:

如果是这样,有人可以解释如何让这幅画作画,以及为什么不画那会很棒!!!

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();
    }

}

【问题讨论】:

  • 它有自己的想法。

标签: java multithreading swing paint


【解决方案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 应用程序

【讨论】:

  • 在做维度的事情时,它只是把小框架?
  • 你还需要pack()你的框架,之前setVisible()之后add(physics)
【解决方案2】:

您必须将 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);

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-29
      • 2017-04-06
      • 2018-05-16
      • 2014-07-17
      • 2012-05-17
      • 2019-01-27
      相关资源
      最近更新 更多