【问题标题】:Trouble with repaint() GUI in JavaJava中重绘()GUI的问题
【发布时间】:2014-05-21 17:36:24
【问题描述】:

我在重绘我的 GUI 时遇到问题。我想用画笔在我的中心元素上绘制一些绘图,但是当我拖动鼠标时,GUI 的所有元素都打印在我的中心元素上。你知道如何解决它吗?

我不能发图片,所以有图片链接:http://imgur.com/a/P3aYC

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class PunsClient extends JFrame {

    //GUI
    private JButton polacz, rozlacz;
    private JPanel topPanel;
    private Painter painter;
    //Klient
    private String nazwaSerwera = "localhost";
    private Klient watekKlienta;
    private PunsClient instancjaKlienta;
    private Puns serwer;
    private ClientImpl klient;

    public PunsClient() {
        super("Klient");
        instancjaKlienta = this;
        setSize(700, 500); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setLayout(new BorderLayout());
        topPanel = new JPanel(new FlowLayout()); 
        painter = new Painter();
        polacz = new JButton("Połącz");
        rozlacz = new JButton("Rozłącz");
        rozlacz.setEnabled(false);


        addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                rozlacz.doClick();
                setVisible(false);
                System.exit(0);
            }
        });

        topPanel.add(new JLabel("Serwer RMI: "));
        topPanel.add(host);
        topPanel.add(polacz);
        topPanel.add(rozlacz);

        add(topPanel, BorderLayout.NORTH);
        add(painter, BorderLayout.CENTER);
        add(wiadomosc, BorderLayout.SOUTH);
        setVisible(true);
    }

    public static void main(String[] args) {
        new PunsClient();

    }
}


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Painter extends JPanel {

    int xvalue = -10, yvalue = -10;

   public Painter() {  
      setPreferredSize(new Dimension(400, 400));
      addMouseMotionListener(new MouseMotionAdapter() {

          public void mouseDragged( MouseEvent event ) {
              xvalue = event.getX();
              yvalue = event.getY();
              repaint();
              }
          });
      }

   public void paint ( Graphics g ) {
       g.fillOval( xvalue, yvalue, 10, 10 );
    }
   }

【问题讨论】:

    标签: java user-interface jpanel graphics2d repaint


    【解决方案1】:

    自定义绘画是通过重写 paintComponent(..) 方法完成的,而不是 paint() 方法。

    不要忘记调用 super.paintComponent() 作为 paintComponent() 方法中的第一条语句。

    阅读 Custom Painting 上的 Swing 教程部分,了解更多信息和示例。

    另外,如果你想做增量绘画,那么你应该查看Custom Painting ApproachesDraw On Image 示例可能是您将使用的方法。

    【讨论】:

      猜你喜欢
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2010-09-06
      • 1970-01-01
      相关资源
      最近更新 更多