gpt4 book ai didi

java - BorderLayout 重复按钮

转载 作者:行者123 更新时间:2023-12-01 13:42:41 24 4
gpt4 key购买 nike

我正在尝试创建一个可以在其中绘画的 Canvas ,以及一个将 Canvas 重置为空状态的按钮。然而,使用 BorderLayout 我的按钮会被复制,第二个按钮是第一个按钮的图像副本,但看起来仍然不太好。我的代码有什么问题吗?如何修复。

PaintCanvas.java

import javax.swing.* ;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
class framakryesore extends JFrame {
PaintCanvas p1 = new PaintCanvas();
JButton b1 = new JButton ("Reset");
public framakryesore (){


b1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
clearcanvas(p1);
repaint();
}
});

this.add(b1,BorderLayout.NORTH);
this.add(p1,BorderLayout.CENTER);




}
public void clearcanvas(PaintCanvas p){
p.setX(0);
p.setY(0);
}
}
public class PaintCanvas extends JPanel {
private int x = 0 ;
private int y = 0 ;
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public PaintCanvas() {
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e){
x=e.getX();
y=e.getY();
repaint();
}
public void mouseMoved(MouseEvent e){

}


});

}
@Override
protected void paintComponent (Graphics g){
if (x==0 && y==0){
super.paintComponent(g);
}
else
{
g.setFont(new Font("TimesRoman", Font.BOLD, 30));
g.drawString(".", x, y);
}

}


}

PaintCanvasTest.java

import javax.swing.JFrame;


public class PaintCanvasTest {
public static void main(String args[]){
framakryesore pikturo = new framakryesore();
pikturo.setVisible(true);
pikturo.setSize(640, 480);
pikturo.setTitle("Pikturo");
pikturo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}
}

最佳答案

if (x==0 && y==0){
super.paintComponent(g);

您应该始终调用super.paintComponent()。它负责在进行自定义绘画之前清除面板的背景。

关于java - BorderLayout 重复按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20585613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com