How to call 2 different paint methods in the same program? - java

I'm trying to make a simple guess the number game and when the user guesses a number between a specific range from the actual answer it will draw a rectangle with a different colour. As of now i'm just testing and have created 2 paint methods and want to now how to call the method "paint2".
import java.awt.*;
import hsa.Console;
import javax.swing.JFrame;
import java.util.Random;
import java.awt.Canvas;
import java.awt.Graphics;
public class MashGuessTheNumber extends Canvas {
static Console c; // The output console
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("My Drawing");
Canvas canvas = new MashGuessTheNumber();
canvas.setSize(400, 400);
frame.getContentPane().add(canvas);
frame.pack();
frame.setVisible(true);
MashGuessTheNumber sm = new MashGuessTheNumber();
c = new Console();
int loop = 0;
while (loop == 0) { // loop used to continue looping the questions after one is answered
int answer = 0;
c.println("Welcome to the guess the number game!");
c.println("What is your name?");
String name = c.readLine();
c.print("why, hello there ");
c.println(name);
c.println("What diffuculty would you like to play?(easy/medium/hard)");
String diff = c.readLine();
if (diff.equalsIgnoreCase("easy")) {
// *Location of random number generator*
c.println("So you chose easy, huh");
c.println("I'm thinking of a number between 1 and 10");
int guess = 1;
answer = (int) (Math.random() * ((10 - 1) + 1));
while (guess != answer) {
c.println("What is it?");
guess = c.readInt();
c.println(answer);
if ((((guess - answer) < 3) && ((guess - answer) > 0))
|| (((answer - guess) < 3) && ((answer - guess) > 0))) {
c.println("EXTREMELY HOT");
}
}
if (guess == answer) {
c.println("You did it!");
}
}
if (diff.equalsIgnoreCase("medium")) {
// *Location of random number generator*
c.println("So you chose medium, huh");
c.println("I'm thinking of a number between 1 and 100");
c.println("What is it?");
String guess = c.readLine();
answer = (int) (Math.random() * ((100 - 1) + 1));
}
if (diff.equalsIgnoreCase("hard")) {
// *Location of random number generator*
c.println("So you chose hard, huh");
c.println("I'm thinking of a number between 1 and 1000");
c.println("What is it?");
String guess = c.readLine();
answer = (int) (Math.random() * ((1000 - 1) + 1));
}
c.println("Would you like to play again?(y/n)"); // if answerd with "y" the loop will repeat
String cont = c.readLine();
if (cont.equalsIgnoreCase("y")) {
loop = 0;
} else {
for(int i=1;i<=24;i++){
c.println(" ");
c.setCursor(12, 30);
c.println("See you next time. Bye!");
loop = 1; // Stops the loop and says bye to the user
}
}
// Place your program here. 'c' is the output console
}
public void paint(Graphics g) {
int x[] = { 35, 75, 75, 35 };
int y[] = { 10, 10, 200, 200 };
g.setColor(Color.black);
int numberofpoints = 4;
g.drawPolygon(x, y, numberofpoints);
}
public void paint2(Graphics g) {
int x[] = { 35, 75, 75, 35 };
int y[] = { 10, 10, 200, 200 };
g.setColor(Color.blue);
int numberofpoints = 4;
g.drawPolygon(x, y, numberofpoints);
}
// main method
} // MashGuessTheNumber class
I'm just trying to draw a different rectangle as of now over top the first one whenever I want and if there is another way that doesn't use two methods that would also be helpful

I'm not seeing where you call paint() at all, but I would make a second parameter that would act as a flag telling me whether to draw a blue or black rectangle. This would get rid of repeated code.
public void paint (Graphics g, Color color)
{
int x[] = {35, 75, 75, 35};
int y[] = {10, 10, 200, 200};
g.setColor (color);
int numberofpoints = 4;
g.drawPolygon (x, y, numberofpoints);
}
I don't know if 'Color' is the correct object to use to pass in a color, but the point is to pass in something that will help you choose what color to make the rectangle so that way you don't have to write two very similar methods. You will call paint() like this:
if(some condition) {
paint(g, Color.blue);
}
else {
paint(g, Color.black);
}

In the Java Swing framework, you don't call Canvas.paint() yourself. But, you can use your own intance variables.
If you add an instance variable to your MashGuessNumber class
private Color myColor = Color.BLACK;
Then modify your if statement
if (count == answer) {
System.out.println("You did it1);
myColor == Color.BLUE;
repaint(); // already a Canvas method
}
Then modify your paint() method
public void paint (Graphics g, Color color)
{
int x[] = {35, 75, 75, 35};
int y[] = {10, 10, 200, 200};
g.setColor (myColor);
int numberofpoints = 4;
g.drawPolygon (x, y, numberofpoints);
}
This should do the trick.
The call to repaint() tells Swing to redraw the canvas by calling your paint() method. Otherwise the system would have no way of knowing that your Canvas needs to be redrawn.

Related

Need to draw 0 in a for loop, but it keeps getting skipped

I'm trying to make a drawing panel that draws little circles with numbers in it, going from 0 to 9. However, the for loop, for one reason or another, keeps skipping 0. I've tried setting i to -1, but that doesn't change anything. Conversely when I set the condition to i < 11, it draws all numbers from 1 to 10.
Here's the code so far:
`
// Draws boxed ovals using a while loop.
import java.awt.*;
public class DrawLoop
{
public static void main(String[] args)
{
DrawingPanel panel = new DrawingPanel(502, 252);
panel.setBackground(Color.CYAN);
Graphics g = panel.getGraphics();
String iValue = "";
int sizeX = 50; // size of boxes
int sizeY = 25;
int i;
for (i = 0; i < 10; i++) { // start at i = 0
int cornerX = i*50; // calculate upper left corner
int cornerY = i*25;
g.setColor(Color.WHITE);
g.fillOval(cornerX + 5, cornerY + 5, sizeX-10, sizeY-10);
g.setColor(Color.BLACK);
g.drawRect(cornerX, cornerY, sizeX, sizeY);
iValue = "" + i;
g.drawString(iValue, cornerX - 29, cornerY - 8);
}
}
}
`
Tried to make a drawing panel that drew numbers from 0-9, loop skips 0 and only does 1-9.

Drawing lines the full height of JPanel

I've gotten my code to work for the most part except for one last thing. When the number of lines drawn > 20, the lines aren't being drawn to take up the full amount of panel
** Look at the bottom right side of my screenshot. The lines go part way down the full height of the panel. I need it to go the full length of the height down. **
Here's my code for DrawPanelTest
// Creating JPanel to display DrawPanel
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class DrawPanelTest
{
public static void main(String[] args)
{
int nValue = 0; // declare variable to store user input. Default value 0.
Boolean flag = true; // initalize flag to true for argument value of while-loop
// while-loop to prompt user input
while (flag) {
// prompt user for the value of N
nValue = Integer.parseInt(JOptionPane.showInputDialog("Enter number of lines between 2 and 100."));
// user input validation. Valid input is nValue [2, 100]
if (nValue < 2 || nValue > 100) {
nValue = Integer.parseInt(JOptionPane.showInputDialog("Enter number of lines between 2 and 100."));
} else {
flag = false; // if user input is correct, while-loop will end
} // end if-else
} // end while-loop
// displays the value of N to make sure it really is correct; This works
// String message = String.format("The value of n is: %d ", nValue);
// JOptionPane.showMessageDialog(null, message);
// create a panel that contains our drawing
DrawPanel drawPanel = new DrawPanel(nValue);
// create a new frame to hold the panel
JFrame application = new JFrame();
// set the frame to exit when closed
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(drawPanel); // add panel to the frame
application.setSize(600, 600); // set the size of the frame
application.setVisible(true); // make the frame visible
}
} // end class DrawPanelTest
Here's my code DrawPanel
// Using drawLine() to connect the corners of a panel
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel extends JPanel
{
int numLines;
// constructor initializes DrawPanel and initializes
// numLines with the argument value of n
public DrawPanel(int n)
{
numLines = n;
}
// draws a X from the corners of the panel
public void paintComponent( Graphics g)
{
// call paintComponent to ensure the panel displays correctly
super.paintComponent(g);
int width = getWidth(); // total width
int height = getHeight(); // total height
int x1 = 0; // starting x-coordinate
int y1 = height / 2; // starting y-coordinate
int x2 = width; // initial value for end x-coordinate
int spaceValue = 0; // represents the space between the lines
int stepValue = height/numLines; // represents the increment value starting from top right corner
for (int i = 0; i <= numLines; i++) {
if (numLines == 2) {
g.drawLine(x1, y1, x2, 0);
g.drawLine(x1, y1, x2, height);
break;
} // end numLines == 2
else if (numLines >= 3) {
g.drawLine(x1, y1, x2, spaceValue);
spaceValue += stepValue;
} // end else if
} // end for-loop
} // end paintComponent
} // end class DrawPanel
I think my problem lies in DrawPanel line 41. I don't think I'm calculating the spaces between the lines correctly so that they end up taking the entire height of the panel.
Thanks in advance for your help.
Your calculation of the "stepValue" has two problems:
the stepValue is to small, so the last line will never appear at the bottom
the stepValue is truncated because of integer math so each addition of the truncated value to the "spaceValue" will yield a slightly less accurate value.
Lets say you have a panel with a height of 600 and the number of lines is 3.
Your calculation is:
int stepValue = 600 / 3 = 200
which I would suggest is wrong as you would draw 3 lines with a "spaceValue" of 0, 200, 400, so the last line (at 600) would never be drawn.
In reality I think the calculation should be:
double stepValue = (double)height / (numLine - 1);
which gives:
double stepValue = 600 / (3 - 1) = 300.
which will give lines with a "spaceValue" of 0, 300, 600 which would be a line at the top, middle and bottom.
So your painting loop simply becomes:
for (int i = 0; i < numLines; i++)
{
g.drawLine(x1, y1, x2, spaceValue);
spaceValue += stepValue;
}
I think (one of) the issue you're having is a "integer division" issue.
int stepValue = height / numLines;
is truncating the result. For example, if the height is 400 and the number of lines is 6 the stepValue will be 66 instead of 67 (which would allow 66.6666 to be rounded up)
Now, you could "round" the value up yourself, but I'd prefer to make use of the available APIs to do these things for me.
Line2D.Double supports double precision parameters, which makes it perfect for this job
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (lineCount > 1) {
double gap = getHeight() / (double)(lineCount - 1);
for (int i = 0; i < lineCount; i++) {
Line2D line = new Line2D.Double(0, getHeight() / 2, getWidth(), i * gap);
g2d.draw(line);
}
} else {
g2d.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
}
g2d.dispose();
}
Runnable example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(new EmptyBorder(32, 32, 32, 32));
frame.setContentPane(contentPane);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private int lineCount = 1;
public TestPane() {
setBorder(new LineBorder(Color.RED));
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
lineCount++;
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
FontMetrics fm = g2d.getFontMetrics();
g2d.drawString(Integer.toString(lineCount), 10, fm.getAscent());
if (lineCount > 1) {
double gap = getHeight() / (double) (lineCount - 1);
for (int i = 0; i < lineCount; i++) {
Line2D line = new Line2D.Double(0, getHeight() / 2, getWidth(), i * gap);
g2d.draw(line);
}
} else {
g2d.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
}
g2d.dispose();
}
}
}
In the for loop, change
for (int i = 0; i < numLines; i++) {
to
for (int i = 0; i <= numLines; i++) {
to iterate the full height of the component. The i must equal numLines to reach unity.

In Race Program, can not seem to declare winner when it collides with finish line- java

I am creating a code that contains moving graphics in a JPanel. It is a race code with 3 racers. Every time the timer goes through, there is a 75% chance they move, and a 25% chance they hold.
My problem is with getting the program to print out the winner in the system console. For some reason, it always says "Orange" is the winner, just because it is the last color I added.
The intersections are just when the runners touch the finish line. There are a few custom commands but those are just to draw the background and set up the JPanel. Those work fine. The problem is that for some reason, the X value of the 4 runners seems to be every single value at once.
public class Rivals extends JFrame{
Rivals(){
Make.frame(this,new RivalsPane(), 512,512,JFrame.EXIT_ON_CLOSE, false);
}
public static class RivalsPane extends JPanel implements ActionListener{
Timer t = new Timer(1,this);
static int x=70,x2=70,x3=70,x4=70,speed=5;
static boolean done=false;
static String win = " wins", winner;
RivalsPane(){
Make.panel(this,512,512,null);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Make.FootRaceTrack(g);
Run(g);
t.start();
}
public void Run(Graphics g) {
Paint.setPen(Color.blue);
Paint.shadeOval(g,x,90,30,30);
Paint.setPen(Color.pink);
Paint.shadeOval(g,x2,190,30,30);
Paint.setPen(Color.green);
Paint.shadeOval(g, x3, 290, 30, 30);
//This is the last one I set, and it always wins
Paint.setPen(Color.ORANGE);
Paint.shadeOval(g, x4, 390, 30, 30);
Rectangle r1 = new Rectangle(x-30,60, 60, 60);
Rectangle r2 = new Rectangle(x-30,160, 60, 60);
Rectangle r3 = new Rectangle(x-30,260, 60, 60);
Rectangle r4 = new Rectangle(x-30,360, 60, 60);
Rectangle r5 = new Rectangle(400,0,512,512);
if(r1.intersects(r5)) {
speed = 0;
winner ="Blue";
done = true;
} else if(r2.intersects(r5)) {
speed=0;
winner = "Pink";
done = true;
} else if(r3.intersects(r5)) {
speed=0;
winner = "Green";
done = true;
} else if(r4.intersects(r5)) {
speed=0;
winner = "Orange";
done = true;
}
if(done==true) System.out.println(winner + "wins");
}
public void actionPerformed(ActionEvent e) {
double rand1 = Math.random();
double rand2 = Math.random();
double rand3 = Math.random();
double rand4 = Math.random();
if(rand1<.75)x+=speed;
if(rand2<.75)x2+=speed;
if(rand3<.75)x3+=speed;
if(rand4<.75)x4+=speed;
repaint();
}
}
public static void main(String[] args) {
Do.showFrame(new Rivals());
}
}
Cause of your x position for all rectangles depends on x variable and not x2, x3, x4. From comment.
All my bounding rectangles were using x with applies to blue only. Change the x's to x2,x3, and x4 and it works. Credit to #Alex

Moving Graphics Smoothly Rather Than Skipping in Java

I was practicing moving graphics in Java and I seem to be coming to a problem. What I drew right now is 2 alien faces. At the moment my program is set up to move the faces 1 step at a time in a certain direction based on user input. What I would like to do is have the alien faces move from point A to point B. For example, right now it moves 1 step at a time because I have the parts of the faces increase by 1 on it's x and y. My thoughts were to start a loop before the method MoveHorizontal(), that way it would run so many times and I would have a smooth transition from one point to another. It's not working like that for me though. It would skip from where it started to where the loops ends rather than 1 step at a time. So my question is, how would I be able to do that? lol. Thank you.
//First Class
import javax.swing.JFrame;
import java.util.Scanner;
public class AlienFace
{
public static void main(String[] args)
{
String userInput;
Scanner input = new Scanner(System.in);
JFrame frame = new JFrame();
frame.setSize(700, 700);
frame.setTitle("An Alien Face");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FaceComponent component = new FaceComponent();
frame.add(component);
frame.setVisible(true);
System.out.println("Which direction would you like the Alien faces to move? ");
System.out.print("H/h for horizontally, V/v for vertically, D/d for diagonally, or Q/q to quit: ");
userInput = input.nextLine();
System.out.println(userInput);
while (!userInput.equals("q") || !userInput.equals("Q"))
{
System.out.println("Which direction would you like the Alien faces to move? ");
System.out.print("H/h for horizontally, V/v for vertically, D/d for diagonally, or Q/q to quit: ");
userInput = input.nextLine();
if (userInput.equals("H") || userInput.equals("h"))
{
component.MoveHorizontal();
frame.repaint();
}
if (userInput.equals("V") || userInput.equals("v"))
{
component.MoveVertical();
frame.repaint();
}
if (userInput.equals("D") || userInput.equals("d"))
{
component.MoveDiagonal();
frame.repaint();
}
}
if (userInput.equals("q") || userInput.equals("Q"))
{
frame.setVisible(false);
}
}
}
//Second Class
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
public class FaceComponent extends JComponent
{
int head2X = 5;
int head2Y = 10;
int head3X = 105;
int head3Y = 115;
int eye2X = 25;
int eye2Y = 75;
int eye3X = 125;
int eye3Y = 175;
int mouth2X1 = 30;
int mouth2Y1 = 110;
int mouth3X1 = 130;
int mouth3Y1 = 210;
int mouth2X2 = 80;
int mouth2Y2 = 110;
int mouth3X2 = 180;
int mouth3Y2 = 210;
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Graphics2D g3 = (Graphics2D) g;
Ellipse2D.Double head = new Ellipse2D.Double(head2X, head2Y, 100, 150);
g2.draw(head);
Ellipse2D.Double head1 = new Ellipse2D.Double(head3X, head3Y, 100, 150);
g3.draw(head1);
g2.setColor(Color.GREEN);
Rectangle eye = new Rectangle(eye2X, eye2Y, 15, 15);
g2.fill(eye);
eye.translate(50, 0);
g2.fill(eye);
g3.setColor(Color.GREEN);
Rectangle eye1 = new Rectangle(eye3X, eye3Y, 15, 15);
g3.fill(eye1);
eye1.translate(50, 0);
g3.fill(eye1);
Line2D.Double mouth = new Line2D.Double(mouth2X1, mouth2Y1, mouth2X2, mouth2Y2);
g2.setColor(Color.RED);
g2.draw(mouth);
Line2D.Double mouth1 = new Line2D.Double(mouth3X1, mouth3Y1, mouth3X2, mouth3Y2);
g3.setColor(Color.RED);
g3.draw(mouth1);
g2.setColor(Color.BLUE);
g2.drawString("Hello, World!", 5, 175);
}
public void MoveHorizontal()
{
head2X++;
head3X++;
eye2X++;
eye3X++;
mouth2X1++;
mouth3X1++;
mouth2X2++;
mouth3X2++;
}
public void MoveVertical()
{
head2Y++;
head3Y++;
eye2Y++;
eye3Y++;
mouth2Y1++;
mouth3Y1++;
mouth2Y2++;
mouth3Y2++;
}
public void MoveDiagonal()
{
head2X++;
head3X++;
eye2X++;
eye3X++;
mouth2X1++;
mouth3X1++;
mouth2X2++;
mouth3X2++;
head2Y++;
head3Y++;
eye2Y++;
eye3Y++;
mouth2Y1++;
mouth3Y1++;
mouth2Y2++;
mouth3Y2++;
}
}

Does the repaint() method in Java require a timer or action?

I've been working on a small "game," which I think is called Pachinko. I have uploaded an image of what the game screen looks like. I will be dropping balls, and having them look like they are rolling off pegs, ending up being caught in the bottom "gates."
My problem is that I cannot get the repaint() method to work. Does the repaint() method require a timer, or action to work? Please look at at these two classes. I have created a Ball class object inside the GameWindow class (near the bottom), and would like to update the ball's x/y values using the Ball's setPos() method, then repaint, so the ball appears to move.
What am I doing wrong? Do I need an update() method to use the repaint() method?
Game Window Image:
public class GameWindow extends JPanel{
private int numBalls = 0;
// GameWindow Constructor (Sets Ball amount from user)
public GameWindow(int balls){
JFrame myFrame = new JFrame("Game Window");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Globally set ball amount
setBallAmount(balls);
myFrame.add(this);
myFrame.setSize(325, 790);
myFrame.setLocationRelativeTo(this);
myFrame.setResizable(false);
myFrame.setVisible(true);
} // End GameWindow Constructor
// Function setPegAmount;
// Passes the amount of balls the user to class variable.
public void setBallAmount(int balls)
{
numBalls = balls * 2;
}
public void paintComponent(Graphics g){
super.paintComponent(g); // housekeeping, etc.
this.setBackground(Color.WHITE); // Background
int counter = 0; // count what number peg we are painting
int row = 1; // calculate what row we are creating
int rowSpacer = 55;
boolean evenRow = false;
int columnSpacer = 60;
// DRAW PEGS TO SCREEN (4 rows of 8, 4 rows of 7)
for (int x = 0; x < 60; x++)
{
// For odd rows
if (row % 2 == 1)
{
g.setColor(Color.BLACK);
g.fillOval(rowSpacer - 40, columnSpacer, 10, 10);
rowSpacer += 40;
counter++;
}
// For Even rows
else
{
g.setColor(Color.BLACK);
g.fillOval(rowSpacer - 20, columnSpacer, 10, 10);
rowSpacer += 40;
counter++;
}
// Check to see if we are finished with odd row
if (counter % 8 == 0 && evenRow == false)
{
row++;
rowSpacer = 55;
columnSpacer += 60;
evenRow = true;
counter = 0;
}
else if(counter % 7 == 0 && evenRow == true)
{
row++;
rowSpacer = 55;
columnSpacer += 60;
evenRow = false;
counter = 0;
}
} // END DRAWING PEGS TO SCREEN
// DRAW RECTANGULAR WALLS TO SCREEN
g.setColor(Color.BLACK); // Wall Color
g.fillRect(0, 0, 5, 760); // LEFT Wall
g.fillRect(315, 0, 5, 760); // RIGHT Wall
g.fillRect(0, 0, 315, 5); // TOP Wall
g.fillRect(0, 755, 320, 5); // BOTTOM Wall
// DRAW BOTTOM GATES
int gateSeperator = 35;
for (int x = 0; x < 7; x++)
{
g.setColor(Color.BLACK);
g.fillRect(gateSeperator, 500, 10, 255);
gateSeperator += 40;
}
// Create instance of ball object
Ball myBall = new Ball();
// Test draw ball
myBall.drawBall(g); // The ball is drawn to screen
myBall.setPos(50, 50); // Change the x and y coordinates of the Ball
repaint(); // Also tried "this.repaint();" but neither does anything
} // Ends paintComponent
} // End GameWindow Class
Ball.java:
public class Ball{
private int x = 5;
private int y = 30;
public void setPos(int xPos, int yPos)
{
x = xPos;
y = yPos;
}
public void drawBall(Graphics g)
{
g.setColor(Color.GREEN);
g.fillOval(x, y, 30, 30);
}
}
I don't think that's the way to do it. Swing's not my specialty but calling repaint in paintComponent, according to my experience, is incorrect.
For example, tell the component to repaint itself.
/**
* Tells the view to repaint itself.
*/
public void update() {
repaint();
}
As soon as possible, repaint ends up calling paintComponent via paint.
/**
* Paints the component.
* #param g The graphics object for the view.
*/
#Override
protected void paintComponent(Graphics g) {
// Draw some stuff...
}
So calling repaint inside of paintComponentis likely not what you're wanting to do. What you should be doing is using repaint to invode paintComponent.
I don't think you can rely on putting the repaint or update at the end of paintComponent because, I believe, multiple calls to repaint get lumped into a single update. So, yes, to properly animate object you should look into using a Swing Timer. For example,
Timer timer = Timer(delay, action);
timer.start();
The above timer will invoke the given action on the delay given in milliseconds. Please see this for more details.

Categories