本文介紹了在這個游戲中使用哪個布局管理器?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在此游戲上使用哪個布局管理器?
推薦答案
IMHO,使用布局和組件不是解決問題的好方法,就我個人而言,我傾向于使用自定義繪畫解決方案。
從一件作品的基本概念開始,它需要知道它的位置,它的大小,它的顏色,能夠自己上色,并且可能是可重新定位的,類似于…
public interface Piece {
public Rectangle getBounds();
public Color getColor();
public void setLocation(Point point);
public void paint(Graphics2D g2d);
}
由此,您可以定義所需的形狀,例如…
public abstract class AbstractPiece implements Piece {
private Rectangle bounds;
private Color color;
@Override
public void setLocation(Point point) {
bounds.setLocation(point);
}
@Override
public Rectangle getBounds() {
return bounds;
}
@Override
public Color getColor() {
return color;
}
public void setBounds(Rectangle bounds) {
this.bounds = bounds;
}
public void setColor(Color color) {
this.color = color;
}
}
public class Square extends AbstractPiece {
public Square(Point location, int size, Color color) {
Rectangle bounds = new Rectangle();
bounds.setLocation(location);
bounds.setSize(size, size);
setBounds(bounds);
setColor(color);
}
@Override
public void paint(Graphics2D g2d) {
g2d.setColor(getColor());
g2d.fill(getBounds());
g2d.setColor(Color.GRAY);
Rectangle bounds = getBounds();
g2d.drawLine(bounds.x + (bounds.width / 2), bounds.y, bounds.x + (bounds.width / 2), bounds.y + bounds.height);
g2d.drawLine(bounds.x, bounds.y + (bounds.height / 2), bounds.x + bounds.width, bounds.y + (bounds.height / 2));
}
}
這只是一個基本的正方形,沒有什么花哨的東西,但是,它是獨立的,易于創建和管理。你可以用這個簡單的圖案創建你喜歡的任何形狀的組合,在一天結束的時候,你的板級不會在意,它只需要它占據的空間和如何繪制它,為此,你需要某種容器來管理所有這些形狀…
public class PuzzelPane extends JPanel {
private List<Piece> pieces;
public PuzzelPane() {
Dimension size = getPreferredSize();
pieces = new ArrayList<>(25);
Point location = new Point((size.width - 50) / 2, (size.width - 50) / 2);
pieces.add(new Square(location, 50, Color.BLUE));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Piece piece : pieces) {
Graphics2D g2d = (Graphics2D) g.create();
piece.paint(g2d);
g2d.dispose();
}
}
}
這是一個非常簡單的概念,它有一個List
來維護所有可用的形狀,并簡單地循環在這個paintComponent
方法中繪制它們
將其與this example和this example中的想法結合在一起,您現在就可以拖動形狀
這篇關于在這個游戲中使用哪個布局管理器?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,