У меня есть класс, который расширяет JComponent с именем Cell, который не отображается, и его paintComponent никогда не вызывается.Вот краткий контрольный список того, что я сделал, пытаясь заставить его работать:
- В конструкторе ячеек есть
this.setPreferredSize
, this.setMaximumSize
и this.setMinimumSize
- Объект (расширение
JPanel
), которое содержит ячейку, вызывает this.add(cell)
для каждой ячейки, а также this.validate()
JPanel's
, которая содержит JPanels
все вызовы .validate()
. - Основной
JPanel
добавляется к contentPane
из JFrame
и вызывается JFrame
.pack()
.
GUIFrontend.java
import java.awt.*;
public class GUIFrontend extends JFrame{
private static final long serialVersionUID = -7074700257172600349L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUIFrontend g = new GUIFrontend();
}
});
}
public GUIFrontend(){
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel primary = new JPanel();
//Map
JPanel mapContainer = new JPanel();
mapContainer.setMinimumSize(new Dimension(772, 600));
GTGrid gtg = new GTGrid();
gtg.validate();
mapContainer.add(gtg);
mapContainer.validate();
JPanel controls = new JPanel();
controls.setBackground(Color.green);
controls.setPreferredSize(new Dimension(160,600));
primary.add(mapContainer);
primary.add(controls);
primary.validate();
this.validate();
this.getContentPane().add(primary);
this.pack();
this.validate();
this.setVisible(true);
}
}
GTGrid.java
public class GTGrid extends Grid {
private static final long serialVersionUID = -2787182463097088611L;
public GTGrid() {
this.height = 150;
this.width = 193;
//Minimum of 4x4 per cell
this.setMinimumSize(new Dimension(width*4,height*4));
GridLayout gl;
this.setLayout(gl = new GridLayout(width,height));
gl.setVgap(0);
gl.setHgap(0);
this.vmax = 2;
//this.add(new JButton("Hello, World!"));
this.intersections = new ArrayList<IntersectionController>();
this.cells = new Cell[height][width];
for(int dt=0;dt<this.height;dt++){
for(int dl=0;dl<this.width;dl++){
this.cells[dt][dl] = new Cell(dt,dl,this);
this.cells[dt][dl].setDirection((dt%2==0)?Direction.East:Direction.West);
//Paint detail
this.add(cells[dt][dl]);
this.validate();
}
}
}
}
Cell.java (этот метод огромен, поэтому были добавлены только выборки)
public Cell(int dt, int dl, Grid parent){
//some deleted code unrelated to JComponent
//Methods for Paint
this.setPreferredSize(new Dimension(4,4));
this.setMaximumSize(new Dimension(10,10));
this.setMinimumSize(new Dimension(4,4));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println("I'm printing!");
Color oldColor = g.getColor();
//Draw black border around cell;
g.setColor(Color.black);
g.drawRect(0, 0, this.getWidth(), this.getHeight());
//Draw yellow line indicating direction of cell
this.drawYellowLine(g);
//Draw car if the cell has one
if (this.hasCar())
this.drawCar(g);
g.setColor(oldColor);
}