【发布时间】:2015-10-18 06:38:32
【问题描述】:
我有一个面板,其中包含已添加到其中的自定义组件。它正确绘制,除非当组件(具有自己的鼠标侦听器)被拖动时,它开始奇怪地绘制。
有趣的是,如果我稍微调整父面板的大小,它现在将按预期绘制。我知道父面板正在通过
重新绘制 super.paintComponent(g);
和面板内的打印语句
paintComponent(Graphics g):
方法。我尝试在拖动组件时重新验证(因为组件正在重新设置其边界)它变得无效。我仍然没有成功,想知道是否有人可以提供帮助。
是否有一些地方我没有正确重绘可能导致这种行为?
另外作为附录,我在面板及其组件上都有一个鼠标侦听器,有没有一种方法可以在单击组件时面板鼠标侦听器也响应(除了从组件返回到父类之外)
这是我遇到的问题的一个工作示例
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class testHome {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testHome window = new testHome();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public testHome() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new myPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
class myPanel extends JPanel {
MyComponent comp;
public myPanel() {
super(null);
comp = new MyComponent(5, 5);
this.add(comp);
revalidate();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Line2D.Double line = new Line2D.Double(10, 10, comp.getX(), comp.getY());
System.out.println(comp.getX() + " " + comp.getY());
g2d.draw(line);
}
}
class MyComponent extends JComponent implements MouseListener, MouseMotionListener {
int x;
int y;
int mx;
int my;
public MyComponent(int x, int y) {
this.setVisible(true);
this.setBounds(x, y, 15, 15);
this.x = x;
this.y = y;
addMouseMotionListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.fillRect(this.x, this.y, 15, 15);
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
System.out.println("dragging");
int dx = e.getX() - mx;
int dy = e.getY() - my;
this.setBounds(this.getX() + dx, this.getY() + dy, 15, 15);
}
@Override
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
}
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
-
顺便说一句 - 如果上面的大量文字中有问题,您可以在其末尾添加
?吗? -
完成并完成@AndrewThompson
-
“是否有一些地方我没有正确重新绘制可能会导致这种行为?” 可能。当您发布该 MCVE 时,我会进一步评论。 “完成并完成” 现在有一个“?” (添加一个很好)但仍然没有 MCVE/SSCCE。您是否按照链接并仔细阅读了文件?不可编译代码sn-ps不满足的缩写词/条件。
-
@user3466639 请检查您的代码,您是否在组件的一个paintComponent 方法中错过了
super.paintComponent(g)?
标签: java swing repaint invalidation