Is there any way I can make the oval disappear once I click on it. I cannot understand where and how to use the Mouse Listener in this case since the While loop is always running thus the repaint() as well. Thanks in advance.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class Game extends JPanel {
int x,y;
int offset=400;
int i; //j;
private void moveBall() {
double degrees=(double) i;
double radians=Math.toRadians(degrees);
double Sinu=Math.sin(radians);
double Sinu200=Math.sin(radians)*300;
int SinuInt=(int) Sinu200;
y=offset+SinuInt;
double Cos=Math.cos(radians);
double Cos200=Math.cos(radians)*300;
int CosInt=(int) Cos200;
x=offset+CosInt;
i++; // j--;
if (i==360) i=0;
}
private int sin(double radians) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.red);
g2d.fillOval(x, y, 50, 50);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Rolling album");
Game game = new Game();
game.i=90;
frame.add(game);
frame.setSize(1100, 1000);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.moveBall();
game.repaint();
Thread.sleep(30);
}
}
}
Ellipse2D
. ellipse.contains(x,y)
Under your function:
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.red);
g2d.fillOval(x, y, 50, 50);
}
This line g2d.fillOval(x, y, 50, 50);
is what is actually painting your circle on each repaint.
If your mouseListener gets a click while in the circle (using Andrew's answer), you probably want to use some flag to see if it is clicked.
if (!ovalClicked)
{
g2d.setColor(Color.red);
g2d.fillOval(x, y, 50, 50);
}
(It would be better to use paintComponent()
rather than paint()
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.