java - PaintComponent显示不清楚

标签 java swing events mouse paintcomponent

我做了这个例子作为练习,这个程序在面板上显示鼠标的协调,它工作正常,我在每个“paintComponent”示例中不断收到的问题是,显示永远不干净,刷新没有发生这是代码:

import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class mousedrag extends JFrame {
   public mousedrag() {
      drag canvas = new drag("JAVA");
      add(canvas);
   }

   public static void main(String[] args) {
      mousedrag f = new mousedrag();
      f.setTitle("events");
      f.setSize(300, 200);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
   }

   static class drag extends JPanel {
      String name = "welcome to java";
      int x = 20, y = 20;

      public drag(String s) {
         this.name = s;
         addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseMoved(MouseEvent e) {
               x = e.getX();
               y = e.getY();
               repaint();
            }

            @Override
            public void mouseDragged(MouseEvent e) {    
            }
         });

      }

      @Override
      protected void paintComponent(Graphics g) {
         g.drawString(String.format("%03d %03d", x, y), x, y);
      }
   }
}

这是我的问题:

screen

enter image description here

最佳答案

您声明:

the display is never clean the refresh isn't happening

原因是您没有在 PaintComponent 方法中调用 super 方法,因此组件永远无法进行图像清理工作。因此,要解决这个问题,请通过更改来调用 super 方法:

@Override   
protected void paintComponent(Graphics g){
    g.drawString(String.format("%d %d", x,y), x, y);
}

@Override   
protected void paintComponent(Graphics g){
    super.paintComponent(g); // **********
    g.drawString(String.format("%d %d", x,y), x, y);
}

关于java - PaintComponent显示不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25995054/

相关文章:

c# - 审讯组织、超时

android - 用于将 keyUp 事件的键码传递给应用程序的 Cordova 插件

java - 使用数学函数优化此 Java 代码的建议

java - 在 hibernate 实体中保留数据库约束是否有好处

java - 触发setCursor方法后光标图标没有变化

java - 在java中启动我的迷你项目数据包跟踪器时遇到困难

apache-flex - 如何从匿名组件中删除事件监听器?

java - 通过 jdbc 从 Postgres 列加载 JSON

java - 原子变量是否保证内存可见性?

java - ubuntu 使用什么外观?