重绘我的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 );
}
}
答案 0 :(得分:1)
自定义绘制是通过覆盖paintComponent(..)
方法而不是paint()方法完成的。
并且不要忘记调用super.paintComponent()
作为paintComponent()方法中的第一个语句。
阅读Custom Painting上Swing教程中的部分,了解更多信息和示例。
另外,如果你想进行渐进式绘画,那么你应该看看Custom Painting Approaches。 Draw On Image
示例可能就是您要使用的方法。