有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java组件显示不清晰

我做了这个例子作为练习,这个程序在面板上显示鼠标的协调,它工作得很好,我一直收到的每个“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


共 (1) 个答案

  1. # 1 楼答案

    你说:

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