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.