我正在尝试用Java编写棋盘游戏。 我有一个图像板和形状的棋子(例如一个矩形)。我希望董事会成为 JFrame 中的背景,并且棋子将成为董事会成员。我已经尝试了多次,但要么是电路板覆盖了形状,要么只显示了形状。我可以加入形状与图像..并创建一个新的图像,但这不是我想要的。有什么想法吗?
public class Board extends JPanel {
@Override
public void paintComponent(Graphics g) {
try {
BufferedImage img = ImageIO.read(new File("C:\\Users\\i\\Desktop\\j.png"));
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我的其他课程
public class GameGUI extends javax.swing.JFrame {
public GameGUI() {
Board b=new Board();
setContentPane(b);
setSize(600,600);
setTitle("gui");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
播放器的课程
public class Player extends JPanel{
int xPos = 100, yPos = 100, vwidth = 100, vheight = 100;
Rectangle r = new Rectangle(xPos, yPos, vwidth, vheight);
public Player(){ .....}
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g.setColor(Color.black);
if (fill) {
g.fillRect((int) r.getX(), (int) r.getY(), (int) r.getWidth(), (int) r.getHeight());
}
g2.draw(r);
}
}