I am drawing a graphical representation of information my simulation is generating. I have the graph displaying but the problem i am running into is to be able to save it as a .png. When it saves the png, the file is all black, so it's not saving my graph but creating some blank png file. The problem is I am having difficulty figuring out how to cast to a BufferedImage or a RenderedImage all of my attempts in eclipse throw errors and when I get it to compile, it works as how I described above. Any thoughts or suggestions? I have been stuck on this for a couple of weeks and either it is an obvious fix or I am not able to save it as png. But from the research i have conducted, it is possible to save a java 2d graphics img as a png file, I don't know what I am missing? A fresh pair of eyes would be greatly and immensely appreciated! Thank you in advance, I appreciate any and all advice or comments regarding this.
public class GraphDisplay extends JPanel implements RenderedImage {
final int PAD = 20;
Primate p;
public GraphDisplay(){
}
public GraphDisplay(Primate p){
this.p = p;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// now we can get x1,y1,x2,y2
double tlx= p.getMap().getX1();
double tly= p.getMap().getY1();
double brx= p.getMap().getX2();
double bry= p.getMap().getY2();
int w = getWidth();
int h= getHeight();
ArrayList <Tree> t= p.getMap().getTrees();
ArrayList<Double> xHist = p.getXHist();
ArrayList<Double> yHist = p.getYHist();
ArrayList<Double> testxHist = new ArrayList();
ArrayList<Double> testyHist = new ArrayList();
for(double i=34;i<1000;i+=5)
{
testxHist.add(i);
}
for(double i=34;i<1000;i+=5)
{
testyHist.add(i);
}
// Draw lines.
double scale=.45;
g2.setBackground(Color.WHITE);
g2.setPaint(Color.green.darker());
for(int i = 0; i < xHist.size()-1; i++) {
double x1 = PAD + (xHist.get(i)-tlx)*scale;
double y1 = (tly-yHist.get(i))*scale-PAD;
double x2 = PAD + (xHist.get(i+1)-tlx)*scale;
double y2 = (tly-yHist.get(i+1))*scale-PAD;
g2.draw(new Line2D.Double(x1, y1, x2, y2));
}
// Mark path points
if(p.getRoute()!=null)
{
ArrayList<Double> routeX= p.getRoute().getX();
ArrayList<Double> routeY= p.getRoute().getY();
g2.setPaint(Color.pink);
for(int i = 0; i < routeX.size()-1; i++) {
double x1 = PAD + (routeX.get(i)-tlx)*scale;
double y1 = (tly-routeY.get(i))*scale-PAD;
double x2 = PAD + (routeX.get(i+1)-tlx)*scale;
double y2 = (tly-routeY.get(i+1))*scale-PAD;
g2.draw(new Line2D.Double(x1, y1, x2, y2));
}
}
g2.setPaint(Color.red);
for(int i = 0; i < xHist.size(); i++) {
double x = PAD + (xHist.get(i)-tlx)*scale;
double y = (tly-yHist.get(i))*scale-PAD;
g2.fill(new Ellipse2D.Double(x-.75, y-.75, 1.5, 1.5));
}
//testing purposes
g2.setPaint(Color.BLACK);
for(int i=0;i<t.size();i++)
{
double x= PAD+(t.get(i).getX()-tlx)*scale;
double y= (tly-t.get(i).getY())*scale-PAD;
g2.fill(new Ellipse2D.Double(x-1,y-1,2,2));
}
}
public class GraphListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
saveGraph(p);
}
}
public void saveGraph(Primate p)
{
ImageIcon saveIcon = new ImageIcon("save.png");
GraphDisplay graphImg = new GraphDisplay(p);
Object graph = new GraphDisplay(p);
BufferedImage buffGraph = new BufferedImage(500,500, BufferedImage.TYPE_INT_RGB);
graph = buffGraph.createGraphics();
RenderedImage rendGraph = (RenderedImage) graphImg;
String graphFileName = JOptionPane.showInputDialog("Please enter a name for the S1Mian graphical output file: ");
File f;
f = new File(graphFileName + ".png");
//every run is unique so do not allow the user to overwrite previously saved files...
if(!f.exists())
{
try{
ImageIO.write(buffGraph, "png", f);
JOptionPane.showMessageDialog(null, graphFileName + ".png has been created and saved to your directory...", "File Saved", JOptionPane.INFORMATION_MESSAGE, saveIcon);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(null, graphFileName +".png already exists please use a different file name...", "File Exists", JOptionPane.INFORMATION_MESSAGE, saveIcon);
}
}
public void createGraph(Primate p)
{
JFrame frame = new JFrame("S1Mian Graphical Output");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //disabled now that graphical output is integrated into GUI as when clicked shut down entire program...
JPanel savePanel = new JPanel();
ImageIcon saveIcon = new ImageIcon("saveIcon.png");
JButton save = new JButton("Save");
save.setToolTipText("Saves the S1Mian graphical output to a .png file");
save.setIcon(saveIcon);
GraphListener gl = new GraphListener();
save.addActionListener(gl);
GraphDisplay graph = new GraphDisplay(p);
graph.setPreferredSize(new Dimension(950, 900));
JScrollPane graphScrollPane = new JScrollPane();
graphScrollPane.setViewportView(graph);
graphScrollPane.setViewportBorder(BorderFactory.createLineBorder(Color.black));
frame.getContentPane().add(graphScrollPane, BorderLayout.CENTER);
savePanel.add(save);
frame.getContentPane().add(savePanel, BorderLayout.NORTH);
frame.setSize(900,850);
frame.setLocation(200,200);
frame.setVisible(true);
}
JPanel dPanel;
...
public void save()
{
BufferedImage bImg = new BufferedImage(dPanel.getWidth(), dPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D cg = bImg.createGraphics();
dPanel.paintAll(cg);
try {
if (ImageIO.write(bImg, "png", new File("./output_image.png")))
{
System.out.println("-- saved");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
See this example: Draw an Image and save to png.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class WriteImageType {
static public void main(String args[]) throws Exception {
try {
int width = 200, height = 200;
// TYPE_INT_ARGB specifies the image format: 8-bit RGBA packed
// into integer pixels
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();
Font font = new Font("TimesRoman", Font.BOLD, 20);
ig2.setFont(font);
String message = "www.java2s.com!";
FontMetrics fontMetrics = ig2.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringHeight = fontMetrics.getAscent();
ig2.setPaint(Color.black);
ig2.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4);
ImageIO.write(bi, "PNG", new File("c:\\yourImageName.PNG"));
ImageIO.write(bi, "JPEG", new File("c:\\yourImageName.JPG"));
ImageIO.write(bi, "gif", new File("c:\\yourImageName.GIF"));
ImageIO.write(bi, "BMP", new File("c:\\yourImageName.BMP"));
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
Screen Image will create a buffered image of the panel and write the image to a file.
It appears that you never actually paint to the BufferedImage in your saveGraph(..) routine.
After you create your BufferedImage and retrieve the Graphics object for that image, call the paintComponent method of your main class passing that graphics context. You also are create two GraphDisplay objects but never use either one.
GraphDisplay graphImg = new GraphDisplay(p);
//You don't need this one, you created one above named graphImg
// Object graph = new GraphDisplay(p);
BufferedImage buffGraph = new BufferedImage(500,500, BufferedImage.TYPE_INT_RGB);
//get the graphics context for the BufferedImage
Graphics2D graph = buffGraph.createGraphics();
//now tell your main class to draw the image onto the BufferedImage
graphImg.paintComponent(graph);
At this point your BufferedImage should now have the same drawing that your panel had and you should be able to save the contents.
Related
I am trying to create yolov4 detection code, using java with (.weights and .cfg) file from python. here I am tring to open python file in java using these two files, so I faced problem when I run the code run time error.
note: I used opencv 4.5.5, yolov4.
package YOLOv4;
import org.opencv.core.*;
import org.opencv.dnn.*;
import org.opencv.utils.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.objdetect.CascadeClassifier;
import org.opencv.videoio.VideoCapture;
import java.util.ArrayList;
import java.util.List;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class yolo {
private static List<String> getOutputNames(Net net) {
List<String> names = new ArrayList<>();
List<Integer> outLayers = net.getUnconnectedOutLayers().toList();
List<String> layersNames = net.getLayerNames();
outLayers.forEach((item) -> names.add(layersNames.get(item - 1)));//unfold and create R-CNN layers from the loaded YOLO model//
return names;
}
public static void main(String[] args) throws InterruptedException {
System.load("C:/Users/mayal/OneDrive/Desktop/opencv/build/java/x64/opencv_java455.dll"); // Load the openCV 4.0 dll //
String modelWeights = "C:/Users/mayal/OneDrive/Desktop/yolov4-opencv-python/yolov4-tiny.weights"; //Download and load only wights for YOLO , this is obtained from official YOLO site//
String modelConfiguration = "C:/Users/mayal/OneDrive/Desktop/yolov4-opencv-python/yolov4-tiny";//Download and load cfg file for YOLO , can be obtained from official site//
String filePath = "C:/Users/mayal/OneDrive/Desktop/yolov4-opencv-python/cars.mp4"; //My video file to be analysed//
VideoCapture cap = new VideoCapture(filePath);// Load video using the videocapture method//
Mat frame = new Mat(); // define a matrix to extract and store pixel info from video//
Mat dst = new Mat ();
//cap.read(frame);
JFrame jframe = new JFrame("Video"); // the lines below create a frame to display the resultant video with object detection and localization//
JLabel vidpanel = new JLabel();
jframe.setContentPane(vidpanel);
jframe.setSize(620, 620);
jframe.setVisible(true);// we instantiate the frame here//
Net net = Dnn.readNetFromDarknet(modelWeights, modelConfiguration); //OpenCV DNN supports models trained from various frameworks like Caffe and TensorFlow. It also supports various networks architectures based on YOLO//
//Thread.sleep(5000);
//Mat image = Imgcodecs.imread("D:\\yolo-object-detection\\yolo-object-detection\\images\\soccer.jpg");
Size sz = new Size(620,620);
List<Mat> result = new ArrayList<>();
List<String> outBlobNames = getOutputNames(net);
while (true) {
if (cap.read(frame)) {
Mat blob = Dnn.blobFromImage(frame, 0.00392, sz, new Scalar(0), true, false); // We feed one frame of video into the network at a time, we have to convert the image to a blob. A blob is a pre-processed image that serves as the input.//
net.setInput(blob);
net.forward(result, outBlobNames); //Feed forward the model to get output //
// outBlobNames.forEach(System.out::println);
// result.forEach(System.out::println);
float confThreshold = 0.6f; //Insert thresholding beyond which the model will detect objects//
List<Integer> clsIds = new ArrayList<>();
List<Float> confs = new ArrayList<>();
List<Rect2d> Rect2ds = new ArrayList<>();
for (int i = 0; i < result.size(); ++i)
{
// each row is a candidate detection, the 1st 4 numbers are
// [center_x, center_y, width, height], followed by (N-4) class probabilities
Mat level = result.get(i);
for (int j = 0; j < level.rows(); ++j)
{
Mat row = level.row(j);
Mat scores = row.colRange(5, level.cols());
Core.MinMaxLocResult mm = Core.minMaxLoc(scores);
float confidence = (float)mm.maxVal;
Point classIdPoint = mm.maxLoc;
if (confidence > confThreshold)
{
int centerX = (int)(row.get(0,0)[0] * frame.cols()); //scaling for drawing the bounding boxes//
int centerY = (int)(row.get(0,1)[0] * frame.rows());
int width = (int)(row.get(0,2)[0] * frame.cols());
int height = (int)(row.get(0,3)[0] * frame.rows());
int left = centerX - width / 2;
int top = centerY - height / 2;
clsIds.add((int)classIdPoint.x);
confs.add((float)confidence);
Rect2ds.add(new Rect2d(left, top, width, height));
}
}
}
float nmsThresh = 0.5f;
MatOfFloat confidences = new MatOfFloat(Converters.vector_float_to_Mat(confs));
Rect2d[] boxesArray = Rect2ds.toArray(new Rect2d[0]);
MatOfRect2d boxes = new MatOfRect2d(boxesArray);
MatOfInt indices = new MatOfInt();
Dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThresh, indices); //We draw the bounding boxes for objects here//
int [] ind = indices.toArray();
int j=0;
for (int i = 0; i < ind.length; ++i)
{
int idx = ind[i];
Rect2d box = boxesArray[idx];
Imgproc.rectangle(frame, box.tl(), box.br(), new Scalar(0,0,255), 2);
//i=j;
System.out.println(idx);
}
// Imgcodecs.imwrite("D://out.png", image);
//System.out.println("Image Loaded");
ImageIcon image = new ImageIcon(Mat2bufferedImage(frame)); //setting the results into a frame and initializing it //
vidpanel.setIcon(image);
vidpanel.repaint();
// System.out.println(j);
// System.out.println("Done");
}
}
}
// }
private static BufferedImage Mat2bufferedImage(Mat image) { // The class described here takes in matrix and renders the video to the frame //
MatOfByte bytemat = new MatOfByte();
Imgcodecs.imencode(".jpg", image, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = null;
try {
img = ImageIO.read(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}
}
I want only images at their respective positions as in the pdf with its exact layout but I don't want text to render in it Is there any way to do it currently I am working in this way but text also coming in this way so is there any way to meet that requirement
File sourceFile=new File(pdfFile);
String fileName = sourceFile.getName().replace(".pdf", "");
int pageNumber = 1;
for (PDPage page : li)
{
BufferedImage image = page.convertToImage();
File outputfile = new File(imgDes + fileName +"_"+ pageNumber +".png");
System.out.println("Image Created -> "+ outputfile.getName());
ImageIO.write(image, "png", outputfile);
pageNumber++;
}
Derive a class from PageDrawer and override all methods that don't deal with images with empty, and then call drawPage(). I just overrode processTextPosition(), and didn't bother about lines, shapes etc but I think it is clear what I mean.
public class MyPageDrawer extends PageDrawer
{
public MyPageDrawer() throws IOException
{
}
#Override
protected void processTextPosition(TextPosition text)
{
}
// taken from PDPage.convertToImage, with extra parameter and one modification
static BufferedImage convertToImage(PDPage page, int imageType, int resolution) throws IOException
{
final Color TRANSPARENT_WHITE = new Color(255, 255, 255, 0);
final int DEFAULT_USER_SPACE_UNIT_DPI = 72;
PDRectangle cropBox = page.findCropBox();
float widthPt = cropBox.getWidth();
float heightPt = cropBox.getHeight();
float scaling = resolution / (float) DEFAULT_USER_SPACE_UNIT_DPI;
int widthPx = Math.round(widthPt * scaling);
int heightPx = Math.round(heightPt * scaling);
Dimension pageDimension = new Dimension((int) widthPt, (int) heightPt);
int rotationAngle = page.findRotation();
// normalize the rotation angle
if (rotationAngle < 0)
{
rotationAngle += 360;
}
else if (rotationAngle >= 360)
{
rotationAngle -= 360;
}
// swap width and height
BufferedImage retval;
if (rotationAngle == 90 || rotationAngle == 270)
{
retval = new BufferedImage(heightPx, widthPx, imageType);
}
else
{
retval = new BufferedImage(widthPx, heightPx, imageType);
}
Graphics2D graphics = (Graphics2D) retval.getGraphics();
graphics.setBackground(TRANSPARENT_WHITE);
graphics.clearRect(0, 0, retval.getWidth(), retval.getHeight());
if (rotationAngle != 0)
{
int translateX = 0;
int translateY = 0;
switch (rotationAngle)
{
case 90:
translateX = retval.getWidth();
break;
case 270:
translateY = retval.getHeight();
break;
case 180:
translateX = retval.getWidth();
translateY = retval.getHeight();
break;
default:
break;
}
graphics.translate(translateX, translateY);
graphics.rotate((float) Math.toRadians(rotationAngle));
}
graphics.scale(scaling, scaling);
PageDrawer drawer = new MyPageDrawer(); // MyPageDrawer instead of PageDrawer
drawer.drawPage(graphics, page, pageDimension);
drawer.dispose();
graphics.dispose();
return retval;
}
public static void main(String[] args) throws IOException
{
String filename = "......./blah.pdf";
// open the document
PDDocument doc = PDDocument.loadNonSeq(new File(filename), null);
List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
for (int p = 0; p < pages.size(); ++p)
{
PDPage page = pages.get(p);
BufferedImage bim = convertToImage(page, BufferedImage.TYPE_INT_RGB, 300);
boolean b = ImageIOUtil.writeImage(bim, "page-" + (p + 1) + ".png", 300);
if (!b)
{
// error handling
}
}
doc.close();
}
}
I am having some trouble displaying a dicom file. I have tried many things to display the picture onto the frame but all it does is make an error which is "image is empty". Any suggestions would be appreciated. (I know that the image is not empty and that it is able to access the image from the laptop).
Thank you.
Here is my code (which is coded in java):
class Open{
public static void main(String s) throws IOException{
String [] array = s.split("/");
String k = array[0];
k+= "/";
k += array[1];
k+= "/";
k += array[2];
k+= "/";
k+= array[3];
k+= "/";
k+= array[4];
k+= "/";
System.out.println(k);
System.out.println(s.length());
if(s.length() == 0){
System.out.println("The path and filename are empty!");
System.exit(0);
}
File source = new File(k, array[5]);
final Image image = ImageIO.read(source);
//final BufferedImage image = ImageIO.read(new File(k, array[5]));
if(image == null){
System.out.println("The image is empty or can't be read!");
System.exit(0);
}
JFrame frame = new JFrame();
final Rectangle bounds = new Rectangle(0,0,240, 240);
JPanel panel = new JPanel();
//{
// public void paintComponent(Graphics g){
//// Rectangle box = g.getClipBounds();
//// ((Graphics2D)g).fill(box);
////
//// if(bounds.intersects(box)){
// g.drawImage(image,0,0,null);
//// }
// }
// };
JLabel b = new JLabel(new ImageIcon(image));
panel.add(b);
frame.getContentPane().add(panel);
panel.setPreferredSize(new Dimension(300, 300));
frame.pack();
frame.setVisible(true);
}
}
You can do it with PixelMed. The documentation is pretty much non-existent, but there are javadocs.
If you primarily intend to display the image, you should be able to use SourceImage and SingleImagePanel from the com.pixelmed.display package to load and display the image. If you want to parse DICOM attributes, you could start with one of the read methods in com.pixelmed.dicom.AttributeList.
I have this string: "This is my very long String that wont fit on one line"
And I need to split it into multiple lines so it'll fit where I need it.
Lets say theres only room for about 15 letters per line, then it should look like this:
"This is my very"
"long String"
"that wont fit"
"on one line"
I would like to split it into a List<String> so I can do
for(String s : lines) draw(s,x,y);
Any help on how to do this would be appriciated!
The way I'm rendering the text is with Graphics.drawString()
This is what I've tried so far (horrible, I know)
String diaText = "This is my very long String that wont fit on one line";
String[] txt = diaText.trim().split(" ");
int max = 23;
List<String> lines = new ArrayList<String>();
String s1 = "";
if (!(diaText.length() > max)) {
lines.add(diaText);
} else {
for (int i = 0; i < txt.length; i++) {
String ns = s1 += txt[i] + " ";
if (ns.length() < 23) {
lines.add(s1);
s1 = "";
} else {
s1 += txt[i] + "";
}
}
}
int yo = 0;
for (String s : lines) {
Font.draw(s, screen, 70, 15 + yo, Color.get(-1, 555, 555,555));
yo += 10;
}
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class LabelRenderTest {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
String title = "<html><body style='width: 200px; padding: 5px;'>"
+ "<h1>Do U C Me?</h1>"
+ "Here is a long string that will wrap. "
+ "The effect we want is a multi-line label.";
JFrame f = new JFrame("Label Render Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BufferedImage image = new BufferedImage(
400,
300,
BufferedImage.TYPE_INT_RGB);
Graphics2D imageGraphics = image.createGraphics();
GradientPaint gp = new GradientPaint(
20f,
20f,
Color.red,
380f,
280f,
Color.orange);
imageGraphics.setPaint(gp);
imageGraphics.fillRect(0, 0, 400, 300);
JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());
Dimension d = textLabel.getPreferredSize();
BufferedImage bi = new BufferedImage(
d.width,
d.height,
BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 128));
g.fillRoundRect(
0,
0,
bi.getWidth(f),
bi.getHeight(f),
15,
10);
g.setColor(Color.black);
textLabel.paint(g);
Graphics g2 = image.getGraphics();
g2.drawImage(bi, 20, 20, f);
ImageIcon ii = new ImageIcon(image);
JLabel imageLabel = new JLabel(ii);
f.getContentPane().add(imageLabel);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
You could consider using LineBreakMeasurer which is intended for this sort of thing in a graphics environment. Please check out the JavaDocs here, which contain a couple of detailed examples on how to use it.
I am creating a battleship type game using swing. i draw images in one panel and it shows up fine, but when i draw more images in a different panel it either deletes most if not all of the images in the first panel and keeps the images in the second panel intact. How would I go about keeping the images from disappearing after drawn in the panel.
I have been searching for an answer online for about a week or so and have come up with nothing...
public class GameBoard extends JPanel{
Graphics g0;
public void paintComponent(Graphics g1) {
g0 = this.getGraphics();
// fill with the color you want
int wide = 275;
int tall = 275;
// go into Graphics2D for all the fine art, more options
// optional, here I just get variable Stroke sizes
Graphics2D g2 = (Graphics2D) g1;
g2.setColor(Color.black);
g2.setStroke(new BasicStroke(1));
Graphics2D g3 = (Graphics2D) g0;
g3.setColor(Color.black);
g3.setStroke(new BasicStroke(1));
// the verticals
for (int i = 0; i < 12*25; i+=25) {
g2.drawLine(i, 0, i, tall);
g3.drawLine(i, 0, i, tall);
}
// the horizontal
for (int i = 0; i < 12*25; i+=25) {
g2.drawLine(0, i, wide, i);
g3.drawLine(0, i, wide, i);
}
g0 = this.getGraphics();
}
public void paintComponent(Image i, int x, int y) {
g0.drawImage(i, x, y, null);
}
}
the above are my panels that are created the first function draws the grid and the second is to draw and image at the inserted cooridnates (x,y)
public class Game {
static JFrame main = new JFrame();
static GameBoard panel = new GameBoard(), panel1 = new GameBoard();
static Container c = main.getContentPane();
static JLabel title = new JLabel("BattleShip!");
static int count = 0, x, y, j;
static String b;
static BufferedImage pB = null, aC = null, bS = null, deS = null, suB = null;
static BattleShips[] player = new BattleShips[5];
static BattleShips[] computer = new BattleShips[5];
static Graphics g;
public static void setup(){
player[0] = new BattleShips();
player[1] = new BattleShips();
player[2] = new BattleShips();
player[3] = new BattleShips();
player[4] = new BattleShips();
computer[0] = new BattleShips();
computer[1] = new BattleShips();
computer[2] = new BattleShips();
computer[3] = new BattleShips();
computer[4] = new BattleShips();
c.add(title);
c.add(panel);
c.add(panel1);
panel.setAlignmentY(Component.CENTER_ALIGNMENT);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setSize(276, 276);
panel1.setAlignmentY(Component.CENTER_ALIGNMENT);
panel1.setAlignmentX(Component.CENTER_ALIGNMENT);
panel1.setSize(276, 276);
title.setAlignmentY(Component.CENTER_ALIGNMENT);
title.setAlignmentX(Component.CENTER_ALIGNMENT);
main.setVisible(true);
main.setSize(new Dimension(291,630));
main.setResizable(true);
main.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
main.setLocation(400, 15);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics g = panel.getGraphics(), g1 = panel1.getGraphics();
panel.paintComponent(g);
panel1.paintComponent(g1);
panel.setBorder(new EmptyBorder(0,0,25,0));
panel1.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
String d = "H";
switch(count){
case 0:
player[0].Name = "patrolBoat";
player[0].x[0] = e.getX()-(e.getX()%25);
player[0].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[0].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities,
"ham");
try {pB = ImageIO.read(new File("src/resources/"+player[0].Name+d+".png"));} catch (IOException e1) {}
panel1.paintComponent(pB,player[0].x[0],player[0].y[0]);
count++;
break;
case 1:
player[1].Name = "battleship";
player[1].x[0] = e.getX()-(e.getX()%25);
player[1].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities1 = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[1].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities1,
"ham");
try {bS = ImageIO.read(new File("src/resources/"+player[1].Name+d+".png"));} catch (IOException e1) {}
panel1.paintComponent(bS,player[1].x[0],player[1].y[0]);
count++;
break;
case 2:
player[2].Name = "aircraftCarrier";
player[2].x[0] = e.getX()-(e.getX()%25);
player[2].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities11 = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[2].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities11,
"ham");
try {aC = ImageIO.read(new File("src/resources/"+player[2].Name+d+".png"));} catch (IOException e3) {}
panel1.paintComponent(aC,player[2].x[0],player[2].y[0]);
count++;
break;
case 3:
player[3].Name = "destroyer";
player[3].x[0] = e.getX()-(e.getX()%25);
player[3].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities111 = {"H", "V"};
d = (String)JOptionPane.showInputDialog(
main,
"Place " + player[3].Name + " vertically or horizontally?",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
null,
possibilities111,
"ham");
try {deS = ImageIO.read(new File("src/resources/"+player[3].Name+d+".png"));} catch (IOException e2) {}
panel1.paintComponent(deS,player[3].x[0],player[3].y[0]);
count++;
break;
case 4:
player[4].Name = "submarine";
player[4].x[0] = e.getX()-(e.getX()%25);
player[4].y[0] = (e.getY()-(e.getY()%25));
Object[] possibilities1111 = {"H", "V"};
d = (String)JOptionPane.showInputDialog( main, "Place " + player[4].Name + " vertically or horizontally?", "Customized Dialog",JOptionPane.PLAIN_MESSAGE,null, possibilities1111, "ham");
try {suB = ImageIO.read(new File("src/resources/"+player[4].Name+d+".png"));} catch (IOException e1) {}
panel1.paintComponent(suB,player[4].x[0],player[4].y[0]);
count = 5;
break;
case 5:
try {setupComp();
count++;} catch (IOException e1) {}
}
}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
});
}
static void setupComp() throws IOException{
b = "H";
g = panel.getGraphics();
////////DESTROYER
j = (int) (Math.random()*1);
computer[1].Name = "destroyer";
if(j == 0){
b = "H";
deS = ImageIO.read(new File("src/resources/"+computer[1].Name+b+".png"));}
else if(j == 1){
b = "V";
deS = ImageIO.read(new File("src/resources/"+computer[1].Name+b+".png"));}
computer[1].x[0] = ((int)(Math.random()*150));
computer[1].x[0] = computer[1].x[0]-computer[1].x[0]%25;
computer[1].y[0] = ((int)(Math.random()*150));
computer[1].y[0] = computer[1].y[0]-computer[1].y[0]%25;
///////END DESTROYER
//////PATROL BOAT
j = (int) (Math.random()*1);
computer[2].Name = "patrolBoat";
switch(j){
case 0:
b = "H";
pB = ImageIO.read(new File("src/resources/"+computer[2].Name+b+".png"));
case 1:
b = "V";
pB = ImageIO.read(new File("src/resources/"+computer[2].Name+b+".png"));
}
computer[2].x[0] = ((int)(Math.random()*225));
computer[2].x[0] = computer[2].x[0]-computer[2].x[0]%25;
computer[2].y[0] = ((int)(Math.random()*225));
computer[2].y[0] = computer[2].y[0]-computer[2].y[0]%25;
///////END PATROL BOAT
///////AIRCRAFT CARRIER
j = (int) (Math.random()*1);
computer[3].Name = "aircraftCarrier";
switch(j){
case 1:b = "H";
aC = ImageIO.read(new File("src/resources/"+computer[3].Name+b+".png"));
case 0:
b = "V";
aC = ImageIO.read(new File("src/resources/"+computer[3].Name+b+".png"));
}
computer[3].x[0] = ((int)(Math.random()*125));
computer[3].x[0] =computer[3].x[0]-computer[3].x[0]%25;
computer[3].y[0] = ((int)(Math.random()*125));
computer[3].y[0] = computer[3].y[0]-computer[3].y[0]%25;
///////END AIRCRAFT CARRIER
///////SUBMARINE
j = (int) (Math.random()*1);
computer[4].Name = "submarine";
switch(j){
case 0:b = "H";
suB = ImageIO.read(new File("src/resources/"+computer[4].Name+b+".png"));
case 1:
b = "V";
suB = ImageIO.read(new File("src/resources/"+computer[4].Name+b+".png"));
}
computer[4].x[0] = ((int)(Math.random()*200));
computer[4].x[0] = computer[4].x[0]-computer[4].x[0]%25;
computer[4].y[0] = ((int)(Math.random()*200));
computer[4].y[0] = computer[4].y[0]-computer[4].y[0]%25;
//END SUBMARINE
///////BATTLESHIP
j = (int) (Math.random()*1);
computer[0].Name = "battleship";
switch(j){
case 1:b = "H";
bS = ImageIO.read(new File("src/resources/"+computer[0].Name+b+".png"));
case 0:
b = "V";
bS = ImageIO.read(new File("src/resources/"+computer[0].Name+b+".png"));
}
computer[0].x[0] = ((int)(Math.random()*200));
computer[0].x[0] = computer[0].x[0]-computer[0].x[0]%25;
computer[0].x[0] = ((int)(Math.random()*200));
computer[0].x[0] = computer[0].y[0]-computer[0].y[0]%25;
///////END BATTLESHIP
System.out.println(computer[0].x[0]+","+computer[0].y[0]);
System.out.println(computer[1].x[0]+","+computer[1].y[0]);
System.out.println(computer[2].x[0]+","+computer[2].y[0]);
System.out.println(computer[3].x[0]+","+computer[3].y[0]);
System.out.println(computer[4].x[0]+","+computer[4].y[0]);
g.drawImage(bS, computer[0].x[0], computer[0].x[0], null);
g.drawImage(aC, computer[1].x[0], computer[1].x[0], null);
g.drawImage(pB, computer[2].x[0], computer[2].x[0], null);
g.drawImage(suB, computer[3].x[0], computer[3].x[0], null);
g.drawImage(deS, computer[4].x[0], computer[4].x[0], null); }}
Don't use getGraphics() to obtain the Graphics object of a Component, and never call paintComponent(...) directly yourself. The Graphics object obtained via getGraphics() is only temporary and will not persist whenever a repainting occurs.
Do all your painting either directly in the paintComponent method (or method called by it), or indirectly in a BufferedImage that is then displayed in paintComponent. Then call repaint() on the component that needs to display a changed image. This will tell the JVM that it should call paintComponent(...) and pass in a valid Graphics object.
Above all, read the graphics tutorials to see how to do it right. It's all there for you to see and learn from -- your "1 week or so" of searching should have found these as they'll be at the top of any Google search on the subject.
Edit
Having said all this, something tells me that you will do better by not messing with any of this drawing business at all, but instead create ImageIcons from your images and then displaying them in JLabels. This is the easiest way to show images using Java Swing.