如何解决如何防止 JPanel 将上次单击的 J Components 对象复制到其面板中?
我正在为我的大学做最后的项目。而且我没有太多的 Java 知识来调试代码。该错误是有问题的。我将在这里删除 3 个类 Java 代码,Drawing Panel、Jframe 和 main() 一个。
main() 代码:
package test;
public class main {
public static void main(String[] agrs) {
Aaa a = new Aaa();
}
}
Aaa 代码(IDK 命名):
package test;
import java.awt.*;
import javax.swing.*;
public class Aaa extends JFrame{
JPanel panel = new JPanel();
JLabel text = new JLabel("please try click on the button first,then drawing,then click and draw again.");
JButton button = new JButton("bug here");
DrawingPanel drawingPanel = new DrawingPanel();
public Aaa() {
this.add(panel,BorderLayout.norTH);
panel.setBackground(Color.WHITE);
panel.add(text);
panel.add(button);
this.add(drawingPanel,BorderLayout.CENTER);
this.setSize(700,500);
this.setTitle("Submit to StackOverFlow");
this.setLocationRelativeto(null);
this.setVisible(true);
this.setResizable(false);
this.setDefaultCloSEOperation(EXIT_ON_CLOSE);
}
}
DrawingPanel() 类(个人怀疑这是 bug 所在。我在不同的项目中使用过它,它也有相同的 bug):
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawingPanel extends JPanel implements MouseListener,MouseMotionListener{
boolean mouse = false;
private int x1,y1,x2,y2;
protected int resetCount = 0;
public DrawingPanel() {
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
protected void paintComponent(Graphics g) {
if (mouse) {
if (resetCount == 0 ) {
super.paintComponent(g);
resetCount++;
}
g.setColor(Color.black);
g.drawLine(x1,y2);
}
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {
mouse = false;
}
public void mousepressed(MouseEvent e) {
mouse= true;
x2 = (int) e.getPoint().getX();
y2 = (int) e.getPoint().getY();
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
x1 = x2;
y1 = y2;
x2 = (int) e.getPoint().getX();
y2 = (int) e.getPoint().getY();
repaint();
}
}
将这 3 个代码一起运行,DrawingPanel 绘图面板会将 JButton 按钮复制到其面板的左上角。如果有 2 个或更多按钮,它将复制最后一个。第一次单击的按钮不会复制到其面板上。有时这个错误也适用于 JTextField。此外,我们可以在面板上绘画!这是图片 this
如果有人知道如何调试这个,我会全力修复它们,非常感谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。