gpt4 book ai didi

java - Swing无法画圆

转载 作者:行者123 更新时间:2023-12-01 11:42:51 25 4
gpt4 key购买 nike

所以我编写的这个程序应该在每次单击面板时画一个圆圈。由于某种原因,我最初在启动时右上角有一个半圆,但我无法让它画一个圆。谁能看出它出了什么问题吗?圆圈的直径应为 20 px,以单击的点为中心绘制。

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



public class QuizActionsInitial extends JFrame {
public JButton redButton = new JButton("red");
public JButton clearButton = new JButton("clear");
boolean isRed = false;
int x1,y1;
boolean clear = false;
CirclePanel myPanel;


public QuizActionsInitial() {

myPanel = new CirclePanel();

add(myPanel, BorderLayout.SOUTH);
JPanel southPanel = new JPanel(new FlowLayout());

clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
clear = true;
}
});

myPanel.addMouseListener(new CircleListener());

southPanel.add(redButton);
southPanel.add(clearButton);
add(southPanel, BorderLayout.NORTH);
pack();
setVisible(true);
} // end constructor
public class CirclePanel extends JPanel {
public CirclePanel() {
setPreferredSize(new Dimension(400,300));
setBorder(BorderFactory.createLineBorder(Color.BLUE, 2));
}

public void paintComponent(Graphics gc){
super.paintComponent(gc);
gc.fillOval(x1-10,y1-10,20,20);
}
} // end class CirclePanel
// end class CirclePanel

public class CircleListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
if (clear = false){
x1 = e.getX();
y1 = e.getY();
}
repaint();
clear = false;
}
}

public static void main(String args[]) {
new QuizActionsInitial();
} // end main
} // end class QuizActionsInitial

最佳答案

int x1,y1;将值初始化为0,这样你总是会在-10x-10处绘制一个初始圆

尝试使用 java.awt.Point 类,当它为 null 时,不要绘制任何内容...

//int x1,y1;
private Point point;
//...
public void paintComponent(Graphics gc){
super.paintComponent(gc);
if (point != null) {
gc.fillOval(point.x-10,point.y-10,20,20);
}
}
//...
public void mouseClicked(MouseEvent e){
if (!clear){
point = evt.getPoint();
}
clear = false;
repaint();
}

哦,if (clear = false){ 是一个赋值(使 clear 等于 false,这样 if 语句总是会失败)

关于java - Swing无法画圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383234/

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