【发布时间】:2016-06-22 12:16:42
【问题描述】:
我有这个程序,当用户点击面板时,椭圆形将向下移动面板。我使用 System.out.print 打印了 yLocation(y 坐标上椭圆的位置),我可以看到值发生了变化。但问题是我无法看到椭圆形移动。
public class OvalWithThreading {
public OvalWithThreading(){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
JFrame frame = new JFrame("Click On The Canvas");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new OvalPane());
frame.pack() ;
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
new OvalWithThreading();
}
//Panel that will hold the oval shape
public class OvalPane extends JPanel{
private int xPosition = 50;
private int yPosition = 50;
private int xSize = 50;
private int ySize = 50;
boolean clicked = true;
boolean horizontalBoundary = true;
boolean verticalBoundary = true;
private List<Ellipse2D> shapes;
public OvalPane(){
shapes = new ArrayList<>();
setBackground(Color.CYAN);
addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
if(clicked) clicked = false;
else if(!clicked) yPosition = 50;
shapes.add(new Ellipse2D.Double(xPosition, yPosition , 50, 50));
System.out.print("Clicked");
repaint();
}
});
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Ellipse2D shape : shapes) {
g2d.fill(shape);
Rectangle2D bounds = shape.getBounds2D();
double yPos = bounds.getY();
double xPos = bounds.getX();
shape.setFrame(xPos, yPos, bounds.getWidth(), bounds.getHeight());
}
}
【问题讨论】: