This i believe is pretty simple maybe im just looking at it differently, i have a jpg of a normal battleships layout, i also have a actual grid i done with a Jpanel, in order to make my game more fancy i wish to have the jpanel with the grid overlaying the jpeg making it seem more realistic. When i imported the jpeg it placed the image within each grid . which is understandable, i create a new instance of a grid class. 6 by 6
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class Grid extends JPanel {
private int row;
private int column;
BufferedImage img;
private BattleShipsClient parent;
public Grid(int row , int column, BattleShipsClient gui)
{
this.row = row;
this.column = column;
this.parent = gui;
setBorder(new LineBorder(Color.black,1));
addMouseListener(new ClickListener());
/*
try {
img = ImageIO.read(new File("Battleships.jpg"));
} catch (IOException e) {
}*/
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
//g.drawImage(img, 0, 0, null);
}
private class ClickListener extends MouseAdapter
{
}
}
This is my grid class, the code to import the image has been commented out as it doesnt work in this place
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
public class BattleShipsClient implements Runnable, BattleShipConstants{
//6 rows and 6 collunms
private Grid [][] grid = new Grid[6][6];
private DataInputStream fromServer;
private DataOutputStream toServer;
BufferedImage img;
JFrame j = new JFrame();
public BattleShipsClient()
{
JPanel p = new JPanel();
p.setLayout(new GridLayout(6,6,0,0));
for (int i=0;i<6;i++)
for(int j=0;j<6;j++)
p.add(grid[i][j] = new Grid(i,j,this));
p.setBorder(new LineBorder(Color.black,1));
j.add(p,BorderLayout.CENTER);
j.setSize(320,320);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setVisible(true);
}
public void run(){
Thread thread = new Thread(this);
thread.start();
}
public static void main(String [] args){
BattleShipsClient bs = new BattleShipsClient();
}
}
I realise why its not working but cant seem to figure out how i will get it to work so its inline with the grid.
As you’re probably aware the reason its not working (image inlined) is that you’re adding 6 x 6 (36)
GridJPanelseach of which is drawing a separate Image of the battleship. What you need is to paint a single image and to overlay the individual cells on top.One way to do this is to create another custom
JPanelthat paints just the image and then add yourGridpanels to that instead:One last important note: Don’t forget to call
in each
Gridpanel to make each of the cells transparent. This will allow the image in the parent container to be displayed.