我有擴展JComponent的叫,它無法顯示單元,其的paintComponent永遠不會被調用的類。 這裏的事情,我都在試圖做一個簡短的清單得到它的工作:未顯示JComponent的,沒有的paintComponent被稱爲
- 細胞構造函數
this.setPreferredSize
,this.setMaximumSize
和this.setMinimumSize
- 保存單元格的對象(的
JPanel
擴展)調用this.add(cell)
爲每個單元以及this.validate()
- 該保持其他
JPanels
所有呼籲.validate()
。 - 將主要
JPanel
添加到JFrame
的contentPane
,並調用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);
}
簡要回顧一下在你的代碼沒有做任何事情脫穎而出。建立一個SSCCE很可能會消除你的問題。 – jzd 2011-02-15 02:59:32
廣告什麼是「網格」?它是一個JComponent,所以`add`方法添加組件? – 2011-02-15 03:25:12