I have Problem with Making adding RandomText(with random size, font,x,y) to JFrame every seconds this is my Code
first one is JComponent which expects Randomly Made String to appear
public class RandomTextGenerator extends JComponent{
private String str;
private Random r;
private Color c;
private Font f;
private int x;
private int y;
Graphics g;
public RandomTextGenerator(String s)
{
r = new Random();
c = new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255));
f = new Font("random",Font.BOLD,r.nextInt(100));
x = r.nextInt(100);
y = r.nextInt(100)+100;
//setPreferredSize(new Dimension(500,500));
str = s;
}
public void paintComponent(Graphics g)
{
g.setColor(c);
g.setFont(f);
System.out.println(str);
g.drawString(str, x, y);
}
}
Another one is JFrame
public class TextFrame extends JFrame{
public TextFrame() {
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Random Text Generator");
this.getContentPane().setBackground(Color.BLACK);
this.setLayout(new GridLayout(1,1));
this.add(new RandomTextGenerator("AAAAAAAA"));
this.add(new RandomTextGenerator("BBBBBBBBBB"));
this.setVisible(true);
}
public void addRandomText(RandomTextGenerator r)
{
this.add(r);
this.add(new RandomTextGenerator("CCC"));
System.out.println("Method called");
this.repaint();
}
}
above Code,
this.add(new RandomTextGenerator("AAAAAAAA"));
this.add(new RandomTextGenerator("BBBBBBBBBB"));
those ones Works well and display on Screen but problem is method addRandomText
this.add(r);
this.add(new RandomTextGenerator("CCC"));
those ones do not works at all.
my main method is here
public class tfmain {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Your Message");
String str = s.nextLine();
TextFrame tf = new TextFrame();
Timer t = new Timer(1000,new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
tf.addRandomText(new RandomTextGenerator(str));
}
});
t.start();
}
}
with this code Method Called is appear which means that Timer Actually works.
but why adding Jcomponent isn't working?? adding Jcomponent in AddRandomtext never works(paintComponent is not called too)
Please Give me some advice. Sorry for my bad english
Related
My programmer was to make a program that translate each word you enter into another languages and shows the image of each word enter.
The translator of English words into french Words by using Jfield and StringArray works. But i got a big problem for setting each images. I don't know how to call them in JApplet Class.
The goal is to use ImageArray class for setup each image corresponding to each world enter in Jfield.
THis is my ImageArray class:
Heading1
public class ImageArray extends JPanel implements ActionListener {
Image[] pics;
String[] names;
int NUM_PICS;
JPanel controls, imagePanel;
JButton randomize;
Image currentImage;
ImageIcon icon;
JLabel imageLabel;
public ImageArray() {
setImages();
setLayout(new BorderLayout());
loadImages();
currentImage=pics[0];
setUpControls();
setUpImagePanel();
}
public void setUpControls(){
controls=new JPanel(new FlowLayout());
randomize=new JButton("randomize");
randomize.addActionListener(this);
controls.add(randomize);
add(controls, BorderLayout.SOUTH);
}
public void setUpImagePanel(){
imagePanel=new JPanel(new FlowLayout());
imageLabel=new JLabel();
imageLabel.setHorizontalAlignment(JLabel.CENTER);
icon=new ImageIcon();
icon.setImage(currentImage);
imageLabel.setIcon(icon);
imagePanel.add(imageLabel);
add(imagePanel, BorderLayout.CENTER);
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(currentImage,0,0,250,250,this);
}
public void setImages(){
pics = new Image[NUM_PICS];
NUM_PICS=names.length;
names[0]= "apple.jpg";
names[1]= "bags.jpg";
names[2] = "bathroom.jpg";
names[3] = "battled.jpg";
names[4]= "car.png";
names[5]= "chairs.jpg";
names[6] = "Computer.jpg";
names[7] = "family.jpg";
names[8] = "flowers.jpg";
names[9] = "god.jpg";
names[10] = "house.png";
names[11] = "map.jpg";
names[12] = "men.jpg";
names[13] = "pencil.jpg";
names[14] = "sisters.jpg";
names[15] = "tomato.jpg";
names[16] = "watch.jpg";
names[17] = "women.jpg";
names[18] ="book.gif";
}
public void loadImages(){
for(int i=0; i<names.length; i++){
currentImage=pics[NUM_PICS];
icon.setImage(currentImage);
repaint();
}
}
public int indexOfImages(ImageIcon userInput)
{
for(int i=0;i<names.length;i++)
{
if(userInput.equals(names[i])){return i;}
}
return -1;
}
#Override
public void actionPerformed(ActionEvent e) {
Object button=e.getSource();
if(button==randomize){
int random=(int)(Math.random()*pics.length);
currentImage=pics[random];
icon.setImage(currentImage);
repaint();
}
}
}
I am having problem getting my horse position to update within my swing application. I have tried multiple methods to update the xPosition of the horses as they refresh across the swing panel that represents the racetrack.
public class HorseModel{
/*Horse dimensions*/
private int x;
private int y;
private final int horsePerimeter = 20;
public HorseModel(int xT, int yT){
/*Constructor*/
x = xT;
y = yT;
}
public void setDimensions(int dimX, int dimY){
/*Sets program dimensions*/
x = dimX;
y = dimY;
}
public void createHorse(Graphics2D h){
/*Paints HorseModel on screen as 2 dimensional object*/
Ellipse2D.Double horseModel = new Ellipse2D.Double(x, y, horsePerimeter, horsePerimeter);
h.setColor(Color.RED);
h.fill(horseModel);
h.setColor(Color.YELLOW);
h.draw(horseModel);
}
}
public class HorseMovement implements Runnable{
public final int xStartPos = 10; //change
public final int yStartPos = 20;
private RaceTrack hRaceTrack;
private HorseModel Horse2D;
private int xPos, yPos;
public HorseMovement(RaceTrack r, int yPos_Spacing){
/*Constructor*/
xPos = xStartPos;
yPos = yStartPos * yPos_Spacing;
Horse2D = new HorseModel(xPos, yPos);
hRaceTrack = r;
}
public HorseModel moveHorse(HorseModel horseObject){
/*Updates horse positon*/
horseObject = new HorseModel(xPos++, yPos);
return horseObject;
}
public void paintComponent(Graphics h){
/*paints the new horse after movement*/
this.Horse2D = moveHorse(Horse2D);
Graphics2D hMod = (Graphics2D) h;
Horse2D.createHorse(hMod);
}
public void run(){
/*Repaints the horse models as they increment movement across the screen*/
hRaceTrack.repaint();
hRaceTrack.revalidate();
}
}
public class RacePanel extends JFrame{
/*Frame Buttons*/
private JPanel mPanel;
private JButton startRace = new JButton("Start Race");
private JButton stopRace = new JButton("Stop Race");
private JButton startOver = new JButton("Start Over");
/*Panel to fill with HorseModels for race*/
private RaceTrack rTrack;
/*Window dimensions*/
public int Window_Height = 1024;
public int Window_Width = 768;
public RacePanel(){
/*Constructor*/
initGui();
initRace();
initQuit();
setSize(Window_Width, Window_Height);
}
public void initGui(){
/*Initializes the main race panel and sets button positions and layouts*/
mPanel = new JPanel(new BorderLayout());
rTrack = new RaceTrack();
JPanel horsePanel = new JPanel(); //panel to house horse objects before running across screen
horsePanel.setLayout(new GridLayout(1, 3));
positionJPanels(horsePanel, mPanel);
}
public void initRace(){
/*implements action listener for start race button*/
class StartRace implements ActionListener{
public void actionPerformed(ActionEvent e){
startRace.setEnabled(true);
rTrack.initTrack();
}
}
ActionListener event = new StartRace();
stopRace.addActionListener(event);
}
public void initQuit(){
/*Implements the action listener for stop race button*/
class StopRace implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);//exits program if race is stopped
}
}
ActionListener event = new StopRace();
stopRace.addActionListener(event);
}
public void positionJPanels(JPanel h, JPanel p){
/*Handles adding buttons to a JPanel*/
h.add(startRace);
h.add(startOver);
h.add(stopRace);
p.add(h, BorderLayout.NORTH); //sets the horse panel buttons to the top of the layout
p.add(rTrack, BorderLayout.CENTER); //sets
add(p);
}
}
public class RaceController {
public static void main(String[] args){
new RaceController();
}
public RaceController(){
/*Constructor*/
JFrame mFrame = new RacePanel();
mFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mFrame.setVisible(true);
}
}
public class RaceTrack extends JPanel{
/*Sets horses within race track*/
private int numOfHorseObjects = 5;// change this to a dynamic
private int numOfThreads = 25;
/*Holds horse thread from HorseObject class*/
private ArrayList<HorseMovement> horses = new ArrayList<>();
private ArrayList<Thread> threads = new ArrayList(numOfThreads);
public RaceTrack(){
/*Constructor*/
setBackground(Color.black);
reset();
}
public void initTrack(){
/*Starts the RaceTrack simulation*/
threads.clear(); //clears the thread arraylist still residing
for(int i = 0; i < horses.size(); i++){
Thread T = new Thread(horses.get(i));
T.start();
threads.add(T);
}
}
public void reset(){
/*resets horse position within screen*/
horses.clear();
for(int i = 0; i < numOfHorseObjects; i++){
horses.add(new HorseMovement(this, i + 1));
}
}
public void paintComponent(Graphics g){
/*overrides graphics paint method in order to paint the horse movements
* through the arraylist of HorseMovements*/
super.paintComponent(g);
for(HorseMovement h : horses){
h.paintComponent(g);
}
}
}
Issues with your code:
You never give the startRace JButton an ActionListener, so how is button going to have any affect, and how is the race ever going to start? Note that you're adding the StartRace ActionListener object to the stopRace JButton, and I'm guessing that this was done in error.
Even if you added that Listener to the startRace button, the action listener will only advance all the horses one "step" and no more -- there are no loops in within your background threads to perform actions repetitively.
You seem to be creating new Horse2D objects needlessly. Why not simply advance the location of the existing Horse2D object?
Myself, I'd use a single Swing Timer rather than a bunch of Threads in order to simplify the code.
I am looking to adjust the thickness of the line drawn at line 75 under the "MyPanel" Class you will find in the comments. My overall intent of this program is to draw letters on the screen when buttons are clicked. Thanks
public class Painttest extends JFrame {
private Timer timer;
private JPanel panel1, panel2;
private MyPanel center;
private MyButton stop, A, B;
public Painttest() {
this.setSize(650, 700);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
panel1 = new JPanel();
panel2 = new JPanel();
center = new MyPanel();
center.setBackground(Color.cyan);
stop = new MyButton("Stop");
stop.setName("stop button");
A = new MyButton("A");
A.setName("A Button");
B = new MyButton("B");
B.setName("B Button");
panel1.add(A);
panel1.add(B);
panel2.add(stop);
this.add(panel1, BorderLayout.WEST);
this.add(center, BorderLayout.CENTER);
this.add(panel2, BorderLayout.EAST);
timer = new Timer(50, center);
this.setVisible(true);
System.out.println(center.getSize()); // size of center panel
}
public static void main(String[] args) {
new Painttest();
}
///////////////////////////////////////////////////////////////////////
// MyPanel class : This panel will be used to draw on
////////////////////////////////////////////////////////////////////////
private class MyPanel extends JPanel implements ActionListener {
private int startingx, startingy;
private int endingx, endingy;
MyPanel() {
startingx = 110;
startingy = 330;
endingx = startingx ;
endingy = startingy ;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// g.fillOval(startingx, startingy, 30, 30);
g.drawLine(startingx, startingy, endingx,endingy); // draws a single line
}
#Override
public void actionPerformed(ActionEvent e) {
startingx = startingx + 1;
startingy = startingy - 3;
repaint();
}
}
///////////////////////////////////////////////////////////////////////
// MyButton class : When Clicked, I want it to draw something on the MyPanel (center)
////////////////////////////////////////////////////////////////////////
private class MyButton extends JButton implements ActionListener {
String name;
MyButton(String title) {
super(title);
addActionListener(this);
name = "NOT SET";
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Pressed a button " + name);
////////////////////////////////////
// if Statements to control the timer
////////////////////////////////////
// STOP TIMER
if (e.getSource() == stop) {
timer.stop();
}
if(e.getSource() == A){
timer.start();
}
if(e.getSource() == B){
timer.start();
}
}
public void setName(String newname) {
name = newname;
}
public String getName() {
return name;
}
}
}
Modify your paintComponent method something like this:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke(new BasicStroke(6.0F));
// g.fillOval(startingx, startingy, 30, 30);
g2d.drawLine(startingx, startingy, endingx, endingy);
}
You can set various kinds of strokes. A basic stroke is a solid thick line.
I am making a simple program to paint a graph and some points in it. The points should be made with methods while changing coordinates of the g.fillOval but actually its painting only the last point.
Here is the code:
import javax.swing.*;
import java.awt.*;
public class PointGraphWriter extends JPanel
{
JFrame korniza = new JFrame();
private int x;
private int y;
private int length;
private String OX;
private String OY;
private String emri;
private int y_height;
private int x_num;
public PointGraphWriter()
{
int width= 500;
korniza.setSize(width,width);
korniza.setVisible(true);
korniza.setTitle(emri);
korniza.getContentPane().add(this);
}
public void paintComponent(Graphics g)
{
g.drawLine(x,y,x+length,y);
g.drawLine(x,y,x,y-length);
g.drawString(OX,x+length, y+15);
g.drawString(OY,x-15,y-length);
g.drawString("0", x -15,y);
g.drawString("0", x,y+15);
g.fillOval(x_num,y-y_height-2, 4 ,4);
}
public void setTitle(String name)
{
emri= name;
this.repaint();
}
public void setAxes(int x_pos, int y_pos, int axis_length, String x_label, String y_label)
{
x= x_pos;
y=y_pos;
length= axis_length;
OX = x_label;
OY = y_label;
}
public void setPoint1(int height)
{
y_height=height;
x_num = x-2;
this.repaint();
}
public void setPoint2(int height)
{
y_height=height;
x_num = x + length/5-2;
this.repaint();
}
}
and here is the main method:
public class TestPlot
{
public static void main(String[] a)
{
PointGraphWriter e = new PointGraphWriter();
e.setTitle("Graph of y = x*x");
e.setAxes(50, 110, 90, "5", "30");
int scale_factor = 3;
e.setPoint1(0 * scale_factor);
e.setPoint2(1 * scale_factor);
}
}
Please have a look at this example. Something in lines of this, you might have to incorporate in your example, to make it work. Simply use a Collection to store what you have previously painted, and when the new thingy comes along, simply add that thingy to the list, and repaint the whole Collection again. As shown below :
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class RectangleExample {
private DrawingBoard customPanel;
private JButton button;
private Random random;
private java.util.List<Rectangle2D.Double> rectangles;
private ActionListener buttonActions =
new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
Rectangle2D.Double rectangle = new Rectangle2D.Double(
(double) random.nextInt(100), (double) random.nextInt(100),
(double) random.nextInt(100), (double) random.nextInt(100));
rectangles.add(rectangle);
customPanel.setValues(rectangles);
}
};
public RectangleExample() {
rectangles = new ArrayList<Rectangle2D.Double>();
random = new Random();
}
private void displayGUI() {
JFrame frame = new JFrame("Rectangle Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
customPanel = new DrawingBoard();
contentPane.add(customPanel, BorderLayout.CENTER);
button = new JButton("Create Rectangle");
button.addActionListener(buttonActions);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new RectangleExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class DrawingBoard extends JPanel {
private java.util.List<Rectangle2D.Double> rectangles =
new ArrayList<Rectangle2D.Double>();
public DrawingBoard() {
setOpaque(true);
setBackground(Color.WHITE);
}
public void setValues(java.util.List<Rectangle2D.Double> rectangles) {
this.rectangles = rectangles;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(300, 300));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Rectangle2D.Double rectangle : rectangles) {
g.drawRect((int)rectangle.getX(), (int)rectangle.getY(),
(int)rectangle.getWidth(), (int)rectangle.getHeight());
}
System.out.println("WORKING");
}
}
See Custom Painting Approaches for examples of the two common ways to do painting:
Keep a List of the objects to be painted
Paint onto a BufferedImage
The approach you choose will depend on your exact requirement.
NOTE: The problem with my code was simply that I created the method to clear the rects and everything but the only thing I was doing wrong was instantiating DrawPanel class's myDraw object inside of the go() method. And so I had to instantiate DrawPanel again with Stop and that created a whole new object. So I ended up calling the clearRects method on a different DrawPanel object than the one rects were being added to. Anyway, I decided to go with code suggestions by MadProgrammer because his code was exactly how Java: A Beginner's Guide teaches it and was much cleaner.
Well, I have been running around StackOverflow since this morning and have been able to fix a lot of problems with my code but I am still stuck with this problem with ArrayLists.
I have the following piece of code that does not seem to do what I intend for it to do. Now I am aware that I am the one making a mistake somewhere but not really sure how to correct it.
The way it is set up is that when I hit the stop button, the ArrayList should clear so I have a blank JPanel so to speak, here's the code snippets. I can post the whole program if you want me to though but I am only pasting the snippet here because I'm assuming I'm making a pretty simple and dumb mistake on my part:
class DrawPanel extends JPanel {
ArrayList<MyRectangle> rects = new ArrayList<>();
Random rand = new Random();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
addRect();
for(MyRectangle r : rects) {
g.setColor(r.getColor());
g.fillRect(r.x, r.y, r.width, r.height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public ArrayList<MyRectangle> addRect() {
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth() - wd);
int y = rand.nextInt(getHeight() - ht);
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
System.out.println(rects.size());
return rects;
}
public void clearEvent(ActionEvent e) {
System.out.println(rects.size());
rects.clear();
frame.repaint();
System.out.println("I was called");
}
}
And here's the part where the button calls it in its actionPerformed method:
class StopListener implements ActionListener {
DrawPanel draw = new DrawPanel();
public void actionPerformed(ActionEvent e) {
timer.stop();
draw.clearEvent(e);
}
}
EDIT: I understand that the arraylist object that my clearEvent method refers to is not the same one that addRect()'s adding stuff to. What I am asking, I guess, is how to make it "connect" so I can wipe things clean using the JButton.
EDIT: Here's the full program:
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.*;
public class TwoButtonsRandomRec {
JFrame frame;
Timer timer;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TwoButtonsRandomRec test = new TwoButtonsRandomRec();
test.go();
}
});
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton startButton = new JButton("Start");
startButton.addActionListener(new StartListener());
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(new StopListener());
final DrawPanel myDraw = new DrawPanel();
timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
myDraw.repaint();
}
});
frame.add(startButton, BorderLayout.NORTH);
frame.add(stopButton, BorderLayout.SOUTH);
frame.add(myDraw, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
class StartListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
timer.start();
}
}
class StopListener implements ActionListener {
DrawPanel draw = new DrawPanel();
public void actionPerformed(ActionEvent e) {
timer.stop();
draw.clearEvent(e);
}
}
class DrawPanel extends JPanel {
ArrayList<MyRectangle> rects = new ArrayList<>();
Random rand = new Random();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
addRect();
for(MyRectangle r : rects) {
g.setColor(r.getColor());
g.fillRect(r.x, r.y, r.width, r.height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
}
public ArrayList<MyRectangle> addRect() {
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth() - wd);
int y = rand.nextInt(getHeight() - ht);
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
System.out.println(rects.size());
return rects;
}
public void clearEvent(ActionEvent e) {
System.out.println(rects.size());
rects.clear();
repaint();
System.out.println("I was called");
}
}
}
class MyRectangle extends Rectangle {
Color color;
public MyRectangle(int x, int y, int w, int h, Color c) {
super(x, y, w, h);
this.color = c;
}
public Color getColor() {
return color;
}
}
Here's the previous relevant question I asked here in case anyone's interested.
Strange JFrame Behavior
I see two immediate issues.
The first is, you're calling addRect within the paintComponent method, which means, even after you clear the List, on the next repaint, a new rectangle will be added to it.
Secondly, I would call repaint in the DrawPanel instead of using frame.repaint(), as you really only want to update the draw panel, not the entire frame
public class BadPaint05 {
public static void main(String[] args) {
new BadPaint05();
}
public BadPaint05() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MasterPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MasterPane extends JPanel {
private DrawPanel drawPane;
private Timer timer;
public MasterPane() {
setLayout(new BorderLayout());
drawPane = new DrawPanel();
add(drawPane);
JButton stop = new JButton("Stop");
stop.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
drawPane.clearEvent(e);
timer.stop();
}
});
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
drawPane.addRect();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
add(stop, BorderLayout.SOUTH);
}
}
class DrawPanel extends JPanel {
ArrayList<MyRectangle> rects = new ArrayList<>();
Random rand = new Random();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// addRect();
for (MyRectangle r : rects) {
g.setColor(r.getColor());
g.fillRect(r.x, r.y, r.width, r.height);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
public ArrayList<MyRectangle> addRect() {
int ht = rand.nextInt(getHeight());
int wd = rand.nextInt(getWidth());
int x = rand.nextInt(getWidth() - wd);
int y = rand.nextInt(getHeight() - ht);
int r = rand.nextInt(256);
int g = rand.nextInt(256);
int b = rand.nextInt(256);
rects.add(new MyRectangle(x, y, wd, ht, new Color(r, b, g)));
System.out.println(rects.size());
repaint();
return rects;
}
public void clearEvent(ActionEvent e) {
System.out.println(rects.size());
rects.clear();
// frame.repaint();
repaint();
System.out.println("I was called");
}
}
public class MyRectangle {
private int x, y, width, height;
private Color color;
private MyRectangle(int x, int y, int wd, int ht, Color color) {
this.x = x;
this.y = y;
this.width = wd;
this.height = ht;
this.color = color;
}
public Color getColor() {
return color;
}
}
}