我试图做一个泡泡射击游戏,但我在扩展JPanel的MyPanel上绘制泡泡时遇到了问题。类气泡(扩展JButton)具有方法paintComponent:
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g;
RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHints(qualityHints);
g2d.setColor(c);
g2d.fillOval(this.x,this.y,this.r, this.r);
}在MyPanel类中,如果我想显示20列10行的气泡,我应该如何构造MyPanel和方法paint()?
发布于 2015-05-01 21:03:24
看起来你已经在这些泡沫中挣扎了一段时间了:Bubble shooter game on Graphics2D, only one bubble display [closed]和Painting balloons on Graphics2D似乎是关于类似的问题。当您提出新问题时,请包括您以前的代码和/或相关问题的链接。
气泡的自定义面板可能如下所示:
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
public class BubblePanel extends JPanel {
private final List<Bubble> bubbles;
public BubblePanel() {
bubbles = new ArrayList<>();
for (int rowIndex = 0; rowIndex < 10; rowIndex++)
for (int columnIndex = 0; columnIndex < 20; columnIndex++)
bubbles.add(new Bubble(100 + columnIndex * 60, 100 + rowIndex * 60,
28, Color.YELLOW));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (final Bubble bubble : bubbles)
bubble.paintComponent(g);
}
}注意:正如camickr已经用an answer回答了您前面的一个问题,使用Swing可以覆盖paintComponent方法来实现您自己的自定义绘制。你可以在关于Performing Custom Painting的官方Java课程中阅读更多关于这个主题的内容。步骤2中介绍了paintComponent方法。
发布于 2015-05-01 21:18:41
您可以尝试使用GridBagLayout()。您可以使用GridBagConstraints轻松地管理列和行。要了解有关GridBagLayout()的更多信息,请查看文档here。
https://stackoverflow.com/questions/29985437
复制相似问题