2015-04-01 175 views
0

因此,我编写的这个程序应该每次点击面板时绘制一个圆圈。出于某种原因,我最初在启动时右上角有一个半圆,我无法画出一个圆。任何人都可以看到它有什么问题吗?圆的直径应为20px,并在中心点击点。Swing无法绘制圆圈

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

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声明将始终失败)