Why is only one rectangle being painted here even though I call the repaint()
method multiple times in my for()
loop? Additionally I want to display 8 rectangles per row and 8 rectangles per column with 2 pixels space in between. Any ideas or help?
package PROG2;
import java.awt.*;
import java.util.*;
import javax.swing.*;
class Model {
int m_width;
int m_height;
int m_x1 = 50;
int m_y1 = 50; //Information about the model
int m_x2 = 100;
int m_y2 = 30;
int counter = 0; //Assisting variable
Model(int width,int height) {
m_width = width;
m_height = height;
}
void math() {
counter = counter 2;
counter = counter m_x2;
m_x1 = counter;
}
}
class View extends JComponent {
private Model m_Mod;
View(Model mod) {
m_Mod = mod;
}
@Override
protected void paintComponent(Graphics g) {
//super.paintComponent(g);
g.setColor(Color.green);
g.drawRect(m_Mod.m_x1,m_Mod.m_y1,
m_Mod.m_x2,m_Mod.m_y2);
g.fillRect(m_Mod.m_x1,m_Mod.m_y1,
m_Mod.m_x2,m_Mod.m_y2);
}
}
class Controller {
private Model m_Mod;
private View m_View;
Controller(){
m_Mod = new Model(500,500);
m_View = new View(m_Mod);
JFrame frame = new JFrame();
frame.add(m_View);
frame.setSize(m_Mod.m_width,m_Mod.m_height);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Graphics g = frame.getGraphics();
}
void simulate(int right, int down){
for( int i = 0; i < right; i ) {
m_Mod.math();
m_View.repaint();
}
}
}
class Übung2{
public static void main(String[] args) throws Exception {
Controller c = new Controller();
c.simulate(8, 8);
}
}
CodePudding user response:
Even when you call repaint()
multiple times, the actual drawing will take place only once at a later time (until swing will trigger a repaint again). At that time, the content of the paintComponent()
method is executed. The code you have in your method only draws one rectangle (drawRect()
) and one filled rectangle (fillRect()
) and that's it, nothing more. So you don't get more than what you wrote in your method.
You can use arrays (or lists) to store the multiple XY coordinates of your rectangles and then iterate over the array/list to draw multiple rectangles while inside the single call of paintComponent()
. The code can look like this:
@Override
protected void paintComponent(Graphics g) {
//super.paintComponent(g);
g.setColor(Color.green);
foreach (RectModel rect: m_Mod.getRectangles()) {
g.drawRect(rect.x1, rect.y1, rect.x2, rect.y2);
}
}
This assumes you have such a class RectModel
which holds the data of one rectangle (x1
, y1
, x2
, y2
) and that you have a method m_Mod.getRectangles()
which returns an array/list of RectModel
instances. When you execute the simulate()
method in your controller, you will calculate all the rectangles you want to draw and save them in the this.rectangles
array/list of the Model
class. After that the paintComponent()
method fill use that array/list and draws the rectangles.