Swing无法绘制圆圈

时间:2015-04-01 05:08:14

标签: java swing geometry

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

    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

1 个答案:

答案 0 :(得分:1)

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语句将始终失败)