【问题标题】:Why repaint doesn't call to paintComponent function?为什么 repaint 不调用 paintComponent 函数?
【发布时间】:2022-12-17 00:04:13
【问题描述】:

此代码是客户端的一部分。从服务器获取信息的部分正在工作,但它没有调用重绘函数(第 6 行)。

public class Client extends JPanel implements Runnable{


public Client() throws IOException{  
        f = new JFrame("Bad Ice Cream by - Rotem Hanoch");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(this.width,this.height);
        f.setResizable(false);
        f.setFocusable(false);
        f.setVisible(true);
        initBoard();
        f.add(this);
    }

    public void run(){
        while(true){
            try {
                Board.Type mat[][] = (Board.Type[][]) this.objectInputStream.readObject();
                updateBoard(mat);
                this.repaint();
            } catch (IOException ex) {} catch (ClassNotFoundException ex) {}
        }
    }

    public void paintComponent(Graphics g){
        System.out.println("hello");
    }
}

我试图弄清楚为什么它不起作用,因为它无法识别该功能。我希望它给我打印一条消息,这样我就知道它已经达到了功能。

【问题讨论】:

    标签: java client jpanel paintcomponent repaint


    【解决方案1】:

    看起来 paintComponent() 方法没有被调用,因为它没有被正确注册为您的 Client 类的绘画方法。为了在客户端组件需要重新绘制时调用 paintComponent() 方法,您需要覆盖 JPanel 类的 paintComponent() 方法,如下所示:

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println("hello");
    }
    

    每当客户端组件需要重新绘制时,Swing 框架将自动调用 paintComponent() 方法。发生这种情况的原因有多种,例如组件首次显示时、调整大小时或使用 repaint() 方法手动重绘时。

    还值得注意的是,repaint() 方法只为组件安排重绘;它不会立即重新绘制组件。实际的重绘将由 Swing 事件分派线程异步完成。这意味着您可能不会在调用 repaint() 后立即看到 paintComponent() 方法的输出。

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多