我是 Java 和用戶界面的新手,我對 Java 圖形有疑問。我想要實作的是在 JPanel 上繪制網格,然后將自定義組件繪制到網格中。
這是我想在其上繪制網格的類(它的基礎擴展了 JPanel)。
public class RectGridPanel extends GridPanel
{
List<Rectangle> rects;
public RectGridPanel(Simulator sim)
{
super(sim);
this.rects = new ArrayList<Rectangle>();
this.setLayout(new GridLayout(20,20));
for(int x = 1; x < 801; x = 40)
{
for(int y = 2; y < 801; y = 40)
{
Cell newCell = new RectCell(x, y, sim);
this.add(newCell);
}
}
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
for(int x = 1; x < 801; x = 40)
{
for(int y = 2; y < 801; y = 40)
{
Rectangle rect = new Rectangle(x, y, 40, 40);
g2.draw(rect);
rects.add(rect);
}
}
}
}
這是我想在網格內繪制的單元格:
public class RectCell extends Cell
{
Rectangle shape;
public RectCell(int x, int y, Simulator sim)
{
super(x, y, sim);
shape = new Rectangle(x, y, CELL_SIZE, CELL_SIZE);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
g2.fill(shape);
}
}
所以網格本身繪制得很好,但是一旦我嘗試在其中創建單元格,它就會像這樣被破壞: 
uj5u.com熱心網友回復:
public class RectCell extends Cell
{
Rectangle shape;
public RectCell(int x, int y, Simulator sim)
{
super(x, y, sim);
shape = new Rectangle(x, y, CELL_SIZE, CELL_SIZE);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
g2.fill(shape);
}
}
Graphics傳遞給這個paintComponent()函式的物件定義了當前RectCell可以繪制的螢屏空間。坐標系相對于 的左上角RectCell,因此繪制背景應始終從x = 0和y = 0或其他一些有意義的值開始。這里的坐標與您似乎假設的父組件無關。
更好的是,設定背景顏色并讓 Swing 負責繪制它,而不是自己繪制矩形。
uj5u.com熱心網友回復:
目前尚不清楚您嘗試實作的目標。RectCell的原因是什么?為什么不直接在 RectGridPanel 中繪制形狀?在paintComponent 中嵌套回圈不是一個好主意。請注意,每次使用新物件增加 rects 串列時,paintComponent 都會被頻繁呼叫。以前繪制的矩形丟失(qraphicaly)并且具有相同引數的新矩形正在串列中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/372478.html
下一篇:組合框的網格選擇彈出視窗
