paintComponent inside function - java

I'm a very beginner so I think I'm making stupid mistake, but I have:
public class Draw extends JPanel {
private static final long serialVersionUID = 1L;
public Draw(int rx, int ry)
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.BLUE);
try{
g.fillRect(rx, ry, 5, 5);
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i < 40; i++) {
Random r = new Random();
int rx = r.nextInt(40);
int ry = r.nextInt(40);
Draw d = new Draw(rx, ry);
f.add(d);
f.setSize(400, 400);
f.setVisible(true);
}
}
}
I want the code to generate rectangles in random positions with some delay in every loop.
Java is writing that "void is an invalid type for the variable paintComponent". I don't believe in this, because if I put paintComponent outside the Draw function it works (but not as I wont him to work).
Does paintComponent cannot be inside other function or there is other error?

Here is an example of what you want:
You should not define methods inside other methods, such as a constructor. Also don't use threads if just need to create intervals. Use javax.swing.Timer instead.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Draw extends JPanel {
private static final int FRAME_HEIGHT = 400;
private static final int FRAME_WIDTH = 400;
private static final int RECT_WIDTH = 40;
private static final int RECT_HEIGHT = 25;
private static final long serialVersionUID = 1L;
public Draw()
{
this.setBackground(Color.WHITE);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
//
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
Random r = new Random();
int rx = r.nextInt(FRAME_WIDTH-RECT_WIDTH);
int ry = r.nextInt(FRAME_HEIGHT-RECT_HEIGHT);
g.fillRect(rx, ry, RECT_WIDTH, RECT_HEIGHT);
}
public static void main(String[] args) {
JFrame f = new JFrame("Title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Draw d = new Draw();
f.add(d);
f.setSize(FRAME_WIDTH, FRAME_HEIGHT);
f.setVisible(true);
Timer t = new Timer(1000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
d.repaint();
}
});
t.start();
}
}
Good Luck.

Related

How to draw an array of Graphics

OK so i'm working on a school project (little animation) and I am currently trying to make rain. I'm not sure how I would go about drawing individual "drops" using JPanel. My Code so far:
Main Class:
public class RainPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
new RainPanel();
}
private final int WIDTH = 800, HEIGHT = 800;
Drop drop;
public RainPanel() {
init();
}
public void init() {
JFrame frame = new JFrame("Rain");
JPanel drop = new Drop();
frame.setVisible(true);
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.add(drop);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
drop.paint(g);
}
Drop class:
public class Drop extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
int x,y;
int yVel = 2;
Timer t = new Timer(5, this);
Random r = new Random();
ArrayList<Drop> DropArray;
public Drop() {
x = r.nextInt(800);
y = r.nextInt(800);
t.start();
}
public void paint(Graphics g) {
super.paintComponent(g);
DropArray = new ArrayList<>(100);
for (int i = 0; i < DropArray.size(); i++) {
DropArray.add(new Drop());
}
g.setColor(Color.BLUE);
g.fillRect(x, y, 3, 15);
}
public void update() {
y += yVel;
if (y > 800)
y = r.nextInt(800);
}
#Override
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
I understand if you might be cringing hard right now (I'm fairly new to graphics coding and mostly familiar with Java itself). All i'm getting drawn currently is a single rain drop. Any suggestions are appreciated.
Don't call super.paintComponent from within paint, you're breaking the paint chain which could cause no end of issues. Override paintComponent directly instead
You shouldn't be modifying the state of a component or anything the component relies on from within any paint method, paint can be called a number of times in quick succession and this can cause no end of issues
Component based animation is not a simple task and unless you really, really need it, you should try and avoid it. Instead, write a class which is "paintable", which you can call from your paintComponent method
For example..
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RainDropsKeepFalling {
public static void main(String[] args) {
new RainDropsKeepFalling();
}
public RainDropsKeepFalling() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new RainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class RainPane extends JPanel {
private List<Drop> drops = new ArrayList<>(100);
public RainPane() {
for (int index = 0; index < 100; index++) {
drops.add(new Drop(getPreferredSize()));
}
Timer timer = new Timer(5, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Drop drop : drops) {
drop.update(getSize());
repaint();
}
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Drop drop : drops) {
Graphics2D g2d = (Graphics2D) g.create();
drop.paint(g2d);
g2d.dispose();
}
}
}
protected static final Random random = new Random();
public static class Drop {
private double vDelta = random.nextDouble() + 0.5;
private int height = 15;
private int width = 3;
private double x;
private double y = -height;
private Rectangle2D shape;
public Drop(Dimension size) {
x = random.nextInt(size.width - width) + width;
y = random.nextInt(size.height - height) + height;
shape = new Rectangle2D.Double(x, y, width, height);
}
public void paint(Graphics2D g2d) {
g2d.setColor(Color.BLUE);
g2d.fill(shape);
}
public void update(Dimension size) {
y += vDelta;
if (y > size.height) {
y = -height;
x = random.nextInt(size.width - width) + width;
}
shape.setRect(x, y, width, height);
}
}
}

Thread Animation Example not working

I was trying to follow these tutorials http://zetcode.com/tutorials/javagamestutorial/animation/ and none of the three examples on that page seem to be working for me. One of them uses a swing timer, one uses the utility timer, and the last and supposedly most effective and accurate according to the page uses a thread to animate.
I will show you the one using the thread, since it is the way that I think I will be doing thing's when using animation for making games.
ThreadAnimationExample.java (in the tutorial it is called star.java but obviously that wont work)
import java.awt.EventQueue;
import javax.swing.JFrame;
public class ThreadAnimationExample extends JFrame {
public ThreadAnimationExample() {
add(new Board());
setTitle("Star");
pack();
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame ex = new ThreadAnimationExample();
ex.setVisible(true);
}
});
}
}
Board.java (the main class)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Board extends JPanel
implements Runnable {
private final int B_WIDTH = 350;
private final int B_HEIGHT = 350;
private final int INITIAL_X = -40;
private final int INITIAL_Y = -40;
private final int DELAY = 25;
private Image star;
private Thread animator;
private int x, y;
public Board() {
loadImage();
initBoard();
}
private void loadImage() {
ImageIcon ii = new ImageIcon("star.png");
star = ii.getImage();
}
private void initBoard() {
setBackground(Color.BLACK);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
setDoubleBuffered(true);
x = INITIAL_X;
y = INITIAL_Y;
}
#Override
public void addNotify() {
super.addNotify();
animator = new Thread(this);
animator.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawStar(g);
}
private void drawStar(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(star, x, y, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
private void cycle() {
x += 1;
y += 1;
if (y > B_HEIGHT) {
y = INITIAL_Y;
x = INITIAL_X;
}
}
#Override
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true) {
cycle();
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep < 0) {
sleep = 2;
}
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e.getMessage());
}
beforeTime = System.currentTimeMillis();
}
}
}
If you are using Eclipse you should create a source folder and add that image to the source folder. Then you could use this:
ImageIcon ii = new ImageIcon( getClass().getResource("/imageName.png") );

Painting to a panel using threads in Java

do not know why there is not printing going on here in my run method. I call repaint and override it in the horsethread class. here is my code. When I run the program and hit Run Race it doesnt draw anything to the panel, any ideas?
import javax.swing.JFrame;
public class HorseTester {
public static void main(String[] args)
{
JFrame frame = new HorsePanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.util.ArrayList;
public class HorsePanel extends JFrame
{
private JPanel panel;
private JButton reset;
private JButton quit;
private JButton run;
private ActionListener listener;
private static final int NUM_OF_HORSES = 5;
public static final int FRAME_WIDTH = 400;
public static final int FRAME_HEIGHT = 400;
private ArrayList<Thread> allThreads = new ArrayList<Thread>();
private ArrayList<HorseThread> horses = new ArrayList<HorseThread>();
public HorsePanel()
{
//Allocating the memory for horses
for(int i=0;i<NUM_OF_HORSES;i++)
horses.add(new HorseThread(i+1));
//Adding them to thread pool
for(int i=0;i<NUM_OF_HORSES;i++)
allThreads.add( new Thread(horses.get(i)));
createPanel();
createRunRace();
createQuit();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createRunRace()
{
class RunRace implements ActionListener
{
public void actionPerformed(ActionEvent rightEvent)
{
run.setEnabled(false);
for(int i=0;i<NUM_OF_HORSES;i++)
allThreads.get(i).start();
}
}
ActionListener a = new RunRace();
this.run.addActionListener(a);
}
public void createQuit()
{
class QuitRace implements ActionListener
{
public void actionPerformed(ActionEvent rightEvent)
{
System.exit(0);
}
}
ActionListener b = new QuitRace();
this.quit.addActionListener(b);
}
public void createPanel()
{
panel = new JPanel(new BorderLayout());
JPanel drawingPanel = new JPanel();
this.run = new JButton("Run Race");
this.quit = new JButton("Quit");
this.reset = new JButton("Reset");
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 3));
topPanel.add(run);
topPanel.add(reset);
topPanel.add(quit);
panel.add(topPanel, BorderLayout.NORTH);
panel.add(drawingPanel, BorderLayout.SOUTH);
add(panel);
}
}
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JComponent;
public class HorseThread extends JComponent implements Runnable
{
public static final int X_START = 10;
public static final int Y_START = 20;
private Horse horse;
private int xpos, ypos;
public HorseThread(int offset)
{
xpos = X_START;
ypos = Y_START * offset;
horse = new Horse(xpos, ypos);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
horse.draw(g2);
}
/**
* Run method that thread executes and makes horses go across
* the screen racing.
*/
public void run()
{
repaint();
}
}
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
public class Horse
{
private int xTop;
private int yTop;
public static final int RING_WIDTH = 20;
public Horse(int x, int y)
{
xTop = x;
yTop = y;
}
public void setXY(int dx, int dy)
{
xTop = dx;
yTop = dy;
}
public void draw(Graphics2D g2)
{
Ellipse2D.Double horse = new Ellipse2D.Double(xTop, yTop, RING_WIDTH, RING_WIDTH);
g2.setColor(Color.BLUE);
g2.fill(horse);
g2.setColor(Color.WHITE);
g2.fill(horse);
}
}
The main problem is, HorseThread extends from JComponent, but you never actually add it to anything, therefore it never gets painted.
If, instead, you created a TrackPane and painted each of the horses within the paintComponent method (there's no need for HorseThread to extend from JComponent), you might have better luck.
Also note, that once a Thread has completed, it can not be restarted...
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class HorseTester {
public static void main(String[] args) {
new HorseTester();
}
public HorseTester() {
JFrame frame = new HorsePanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public class HorsePanel extends JFrame {
private JPanel panel;
private JButton reset;
private JButton quit;
private JButton run;
private ActionListener listener;
public static final int FRAME_WIDTH = 400;
public static final int FRAME_HEIGHT = 400;
private TrackPane trackPane;
public HorsePanel() {
createPanel();
createRunRace();
createQuit();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createRunRace() {
class RunRace implements ActionListener {
public void actionPerformed(ActionEvent rightEvent) {
run.setEnabled(false);
trackPane.start();
}
}
ActionListener a = new RunRace();
this.run.addActionListener(a);
}
public void createQuit() {
class QuitRace implements ActionListener {
public void actionPerformed(ActionEvent rightEvent) {
System.exit(0);
}
}
ActionListener b = new QuitRace();
this.quit.addActionListener(b);
}
public void createPanel() {
panel = new JPanel(new BorderLayout());
trackPane = new TrackPane();
this.run = new JButton("Run Race");
this.quit = new JButton("Quit");
this.reset = new JButton("Reset");
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 3));
topPanel.add(run);
topPanel.add(reset);
topPanel.add(quit);
panel.add(topPanel, BorderLayout.NORTH);
panel.add(trackPane, BorderLayout.CENTER);
add(panel);
}
}
public class TrackPane extends JPanel {
private static final int NUM_OF_HORSES = 5;
private ArrayList<HorseThread> horses = new ArrayList<HorseThread>();
private ArrayList<Thread> threads = new ArrayList<Thread>(25);
public TrackPane() {
setBackground(Color.GREEN);
reset();
}
public void reset() {
// Should dispose of any running threads...
horses.clear();
//Allocating the memory for horses
for (int i = 0; i < NUM_OF_HORSES; i++) {
horses.add(new HorseThread(this, i + 1));
}
}
public void start() {
// Should dispose of any running threads...
threads.clear();
for (int i = 0; i < horses.size(); i++) {
Thread thread = new Thread(horses.get(i));
thread.start();
threads.add(thread);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (HorseThread horse : horses) {
horse.paint(g);
}
}
}
public class HorseThread implements Runnable {
public static final int X_START = 10;
public static final int Y_START = 20;
private Horse horse;
private int xpos, ypos;
private TrackPane track;
public HorseThread(TrackPane track, int offset) {
xpos = X_START;
ypos = Y_START * offset;
horse = new Horse(xpos, ypos);
this.track = track;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
horse.draw(g2);
}
/**
* Run method that thread executes and makes horses go across the screen
* racing.
*/
public void run() {
track.repaint();
}
}
public class Horse {
private int xTop;
private int yTop;
public static final int RING_WIDTH = 20;
public Horse(int x, int y) {
xTop = x;
yTop = y;
}
public void setXY(int dx, int dy) {
xTop = dx;
yTop = dy;
}
public void draw(Graphics2D g2) {
Ellipse2D.Double horse = new Ellipse2D.Double(xTop, yTop, RING_WIDTH, RING_WIDTH);
g2.setColor(Color.BLUE);
g2.fill(horse);
g2.setColor(Color.WHITE);
g2.draw(horse);
}
}
}
Also note that Swing is not thread safe, be careful using Threads in this environment ;)

Java Graphics Checkout Simulation;

I am working on a project which is a Checkout Simulation. I have the code to make it work run but i am struggling to understand and implement how to add graphics(in my case a square) once a certain condition is true. For example i have made my code so that it goes through random numbers and if 2,4,6 or 8 has been randomly generated, someone will be added to the queue and the same goes for if they are even numbers 1 or 3, someone is removed from the queue. I basically just want to know how to add a square to the screen once i have met my condition (for example, generating a 4 should add a square to the screen but it doesn't)
ANY help would really be appreciated!
public class MainPanel extends JPanel {
private Queue<String> tillQueue;
private int rndNumber;
private int currentLength;
private ArrayList<Integer> lengthList;
private double mean;
private Random rand;
private int MAXLENGTH;
private static Random r = new Random();
private static Random r2 = new Random();
Color colour;
private static final int IMAGE_SIZE = 600;
private Timer timer;
private int delay;
private JButton startButton;
private JButton stopButton;
private BufferedImage buffer;
JToolBar toolbar;
public MainPanel() {
startButton = new JButton("START");
stopButton = new JButton("STOP");
toolbar = new JToolBar();
toolbar.add(startButton);
toolbar.add(stopButton);
this.buffer = new BufferedImage(IMAGE_SIZE, IMAGE_SIZE, BufferedImage.TYPE_INT_ARGB);
setDoubleBuffered(false);
StartActionHandler start = new StartActionHandler();
StopActionHandler stop = new StopActionHandler();
TimerEvent timerEvt = new TimerEvent();
startButton.addActionListener(start);
stopButton.addActionListener(stop);
delay = 50;
timer = new Timer(delay, timerEvt);
}
public class TimerEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
//drawNext(buffer.getGraphics());
for (int time = 1; time < 9; time++) {
rndNumber = rand.nextInt(6) + 1; //generates random number
if (rndNumber == 2 || rndNumber == 4 || rndNumber == 6 || rndNumber == 8) {
//time is added to queue
tillQueue.add(String.valueOf(time));
drawNext(buffer.getGraphics());
repaint();
}
}
}
}
public class StartActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
timer.start();
}
}
private void drawNext(Graphics g) {
int x = r.nextInt(IMAGE_SIZE);
int y = r.nextInt(IMAGE_SIZE);
int red = r2.nextInt(255);
int green = r2.nextInt(255);
int blue = r2.nextInt(255);
Color randomColour = new Color(red, green, blue);
g.setColor(randomColour);
g.fillRect(x, y, 10, 10);
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(buffer, 0, 0, this);
}
}
Note several changes to get rendering working:
For convenience, use the buffer's createGraphics() method and dispose() it when done.
Initialize the offscreen buffer to a known state.
One instance of Random is usually sufficient.
Limit variable scope to the extent possible, e.g. private class TimerEvent.
Override getPreferredSize() to establish the rendering area size.
As tested:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.Timer;
/**
* #see https://stackoverflow.com/a/21238669/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MainPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
private static class MainPanel extends JPanel {
private static final int SIZE = 500;
private static final int DELAY = 100;
private static final Random r = new Random();
private final Queue<String> tillQueue = new LinkedList<>();
private Timer timer;
private JButton startButton;
private JButton stopButton;
private BufferedImage buffer;
private JToolBar toolbar;
public MainPanel() {
super(new BorderLayout());
startButton = new JButton("START");
stopButton = new JButton("STOP");
toolbar = new JToolBar();
toolbar.add(startButton);
toolbar.add(stopButton);
buffer = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = buffer.createGraphics();
g.clearRect(0, 0, SIZE, SIZE);
g.dispose();
StartActionHandler start = new StartActionHandler();
TimerEvent timerEvt = new TimerEvent();
timer = new Timer(DELAY, timerEvt);
startButton.addActionListener(start);
add(new JLabel(new ImageIcon(buffer)));
add(toolbar, BorderLayout.SOUTH);
}
private class TimerEvent implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (int time = 1; time < 9; time++) {
if (r.nextInt(6) % 2 == 0) {
tillQueue.add(String.valueOf(time));
drawNext();
}
}
}
}
private class StartActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
}
private void drawNext() {
Graphics2D g = buffer.createGraphics();
int x = r.nextInt(SIZE);
int y = r.nextInt(SIZE);
g.setColor(new Color(r.nextInt()));
g.fillRect(x, y, 10, 10);
g.dispose();
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(buffer, 0, 0, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(SIZE, SIZE);
}
}
}
How is suposed to work? when you met the condition an item is added to tillQueue, but tillQueue is never readed...
I you want to draw something you can draw it in the method paintComponent.
To draw a rectangle simply use:
http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#drawRect(int, int, int, int)
You can iterate the tillQueue in the paintComponent method and draw the corresponding rectangles.

Repaint method compiling improperly

I am trying to use repaint in a timer task, but eclipse is telling me the method is undefined, and I don't know why. I believe I have all the proper imports. Below is just a small segment of my code.
import java.awt.Color;
import java.awt.Graphics;
import java.util.TimerTask;
import java.util.Timer;
import javax.swing.JPanel;
class task extends TimerTask
{
public void run()
{
repaint();
}
}
You're calling a method that has not been declared in the class it is held in, and so Java, not "Eclipse" is complaining, and rightfully so.
If you are trying to redraw a Swing GUI component intermittently using a timer then,
Use a Swing Timer, not a java.util.Timer, since the latter does not handle Swing threading properly.
Call repaint() on a Swing component, not on nothing as you're doing.
Most important, go through the Java and Java Swing tutorials, as it will explain all of this and more.
For example, try running this straight, and then try running it stoned. It's almost psychedelic:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyRepaint extends JPanel {
private static final Color COLOR_1 = Color.RED;
private static final Color COLOR_2 = Color.BLUE;
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private static final int DELAY = 25;
private int x1 = 0;
private int y1 = 0;
private int x2 = 20;
private int y2 = 20;
Paint myPaint = new GradientPaint(x1, y1, COLOR_1, x2, y2, COLOR_2, true);
public MyRepaint() {
new Timer(DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
x1++;
y1++;
x2++;
y2++;
x1 %= PREF_W;
y1 %= PREF_H;
x2 %= PREF_W;
y2 %= PREF_H;
myPaint = new GradientPaint(x1, y1, COLOR_1, x2, y2, COLOR_2, true);
// the repaint method call below works because it is calling it on
// the current object of this class, which extends JPanel
// and thus has a repaint() method.
repaint();
}
}).start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(myPaint);
g2.fillRect(0, 0, PREF_W, PREF_H);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
MyRepaint mainPanel = new MyRepaint();
JFrame frame = new JFrame("MyRepaint");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories