我的應用程序出現令人沮喪的問題。我想(在所提供的例子,這是)爲3個填充的矩形這樣的:Java - jpanel未顯示所有組件
##
#
唉,只有左上角繪製矩形。下面是我的代碼的SSCCE版本:
import static java.lang.System.out;
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class Main {
public static void main(String args[]) {
Map map = new Map();
Point[] poly1 = new Point[] { new Point(10, 10), new Point(40, 10), new Point(40, 40), new Point(10, 40) };
Point[] poly2 = new Point[] { new Point(50, 10), new Point(80, 10), new Point(80, 40), new Point(50, 40) };
Point[] poly3 = new Point[] { new Point(50, 50), new Point(80, 50), new Point(80, 80), new Point(50, 80) };
Point[][] polys = new Point[][] { poly1, poly2, poly3 };
ShowWindow(polys);
}
private static void ShowWindow(Point[][] polys) {
GameWindow frame = new GameWindow(polys);
frame.setVisible(true);
}
}
class GameWindow extends JFrame {
public GameWindow(Point[][] polys) {
setDefaultCloseOperation(EXIT_ON_CLOSE);
MapPanel panel = new MapPanel(polys);
Container c = getContentPane();
c.setPreferredSize(panel.getPreferredSize());
add(panel);
pack();
}
}
class MapPanel extends JPanel {
public MapPanel(Point[][] polys) {
setLayout(null);
for (Point[] poly : polys) {
CountryPolygon boundaries = new CountryPolygon(poly);
add(boundaries);
}
setBounds(0, 0, 800, 600);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(getBounds().width, getBounds().height);
}
}
class CountryPolygon extends JComponent {
private Path2D.Double CountryBounds;
public CountryPolygon(Point[] points) {
CountryBounds = GetBoundaries(points);
setBounds(CountryBounds.getBounds());
}
private Path2D.Double GetBoundaries(Point[] points) {
Path2D.Double bounds = new Path2D.Double();
bounds.moveTo(points[0].x, points[0].y);
for(Point p : points) {
if(p == points[0]) continue;
bounds.lineTo(p.x, p.y);
}
bounds.closePath();
return bounds;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g.create();
g2.setColor(new Color(175, 100, 175));
g2.fill(CountryBounds);
g2.dispose();
}
}
我真正的代碼不是很喜歡這一點,但問題是大同小異。您可能想知道爲什麼我不使用佈局管理器。那麼,我正在嘗試創建一個類似RISK的遊戲,所以我有很多不規則的形狀,都必須放在正確的位置。
我對Java很陌生,也找不到一個類似的搜索問題。
感謝您的幫助!
這是不正確的:我在我的CountryPolygon類中調用了setBounds(),它設置了組件的大小和組件的位置。爲了驗證這一點,我從類內部調用了System.out.println(getSize()),並在MapPanel類的for循環中調用了System.out.println(boundaries.getSize())。對於所有創建的組件都返回width = 30 height = 30,這是正確的。 –
@OlaviMustanoja,對不起,錯過了。請參閱編輯。 – camickr
將所有對象調整爲800x600,使所有組件都可以按預期顯示。但是,我不明白這一點。如果我的jpanel的大小是800x600,並且我的代碼使得poly1的大小爲30x30,並且位置x = 10 y = 10,那麼爲什麼組件是在邊界外? –