Split string into List<String> if too long - java

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.

Related

Trying to Update Values of JThermometer and JSliders Dynamically in a for loop

I am new in java and trying to create a dashboard where I have N number of sensors and now i wants to show values of Humidity and temperature of each sensor in a separate panels . So firstly i have created N number of panels containing a JSlider and JThermometer for Humidity and temperature each. Now in a loop it reads the lines of outputs from arduino and i am trying to provide that values to that thermometers and sliders .
But i am not able to differentiate that output for which panel it is goin to set . even when i tried to set values to them it is not working at all.
Kindly give any idea how can i implement.
Thank you for help.
Java version - 18.0.1.1
IDE - Apache netbeans 14
static JTextField txtTemp, txtMois;
static JLabel lblTemp, lblMois;
static JSlider slider1, slider2;
static JThermometer th1, th2 ;
static JPanel JP1, JP ;
public void interfaces(){
///Here number of panels is 2
if(count1 > 0){
for(int i = 0 ; i<=count1 ; i++){
JP1 = myPanel(i,0,0);
add(JP1);
}
}
setVisible(true);
setTitle("Temperature and Humidity");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(1200,800);
getContentPane().setBackground(Color.lightGray);
setMinimumSize(new Dimension(350,450));
setLayout(null);
SerialPort[] AvailablePorts = SerialPort.getCommPorts();
SerialPort currPort = AvailablePorts[0];
for (SerialPort S : AvailablePorts) {
System.out.println("\n " + S.toString());
currPort = S;
}
int BaudRate = 9600;
int DataBits = 8;
int StopBits = SerialPort.ONE_STOP_BIT;
int Parity = SerialPort.NO_PARITY;
System.out.println("\n " + currPort.getSystemPortName());
currPort.setComPortParameters(BaudRate,
DataBits,
StopBits,
Parity);
currPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING,
1000,
0);
currPort.openPort();
if (currPort.isOpen())
{
System.out.println("is Open ");
} else {
System.out.println(" Port not open ");
}
try {
while (true) {
try{input = new BufferedReader(new InputStreamReader(currPort.getInputStream()));
String Line1 = input.readLine();
int count = 0;
String[] Data = Line1.split(" ");
for(int i = 0; i < Data.length; i++){
count +=1;
String[] Final_data = Data[i].split(",");
double temp, mois;
try{ temp = Double.parseDouble(Final_data[0]);
mois = Double.parseDouble(Final_data[1]);
System.out.println("Temparature : " + temp);
System.out.println("Humidity : " + mois);
th1.setValue(temp);
th2.setValue(mois);
slider1.setValue((int) temp);
slider2.setValue((int) mois);
txtTemp.setText(String.valueOf(temp));
txtMois.setText(String.valueOf(mois));
}
catch(NumberFormatException e){
System.out.println(e.toString());
}
}
}
catch(SerialPortTimeoutException ex){
System.out.println(ex);
}
}
} catch (Exception e) {
e.printStackTrace();
}
currPort.closePort();
}
//MyPannel funaction
public static JPanel myPanel(int count, double temp, double mois){
JP = new JPanel();
int width = (count-1)*420;
test = new JTextField(String.valueOf(count));
test.setBounds(0, 0, 200, 20);
JP.add(test);
th1 = new JThermometer();
th1.setBounds(10, 50, 150,300);
th1.setValue(0);
th1.setBackground(new Color(0,0,0,0));
th1.setForeground(Color.white);
String color = th1.getBackground().toString();
slider1 = new JSlider(JSlider.VERTICAL,0,100,0);
slider1.setBounds(110, 60, 50, 230);
slider1.setMinorTickSpacing(2);
slider1.setMajorTickSpacing(10);
slider1.setPaintTicks(true);
slider1.setPaintLabels(true);
slider1.setForeground(Color.white);
slider1.setBackground(new Color(0,0,0,0));
lblTemp = new JLabel("TEMPERATURE",SwingConstants.CENTER);
lblTemp.setBounds(15,30,140,30);
lblTemp.setForeground(Color.WHITE);
lblTemp.setFont(new Font("Arial", Font.BOLD, 20));
lblTemp.setBackground(Color.getColor(color));
txtTemp = new JTextField();
txtTemp.setFont(new Font("Arial", Font.BOLD, 16));
txtTemp.setBounds(115,300,50,30);
th2 = new JThermometer();
th2.setBounds(210, 50, 150, 300);
th2.setValue(0);
th2.setBackground(new Color(0,0,0,0));
th2.setForeground(Color.white);
slider2 = new JSlider(JSlider.VERTICAL,0,100,0);
slider2.setBounds(310, 60, 50, 230);
slider2.setMinorTickSpacing(2);
slider2.setMajorTickSpacing(10);
slider2.setPaintTicks(true);
slider2.setPaintLabels(true);
slider2.setBackground(new Color(0,0,0,0));
slider2.setForeground(Color.white);
lblMois = new JLabel("HUMIDITY",SwingConstants.CENTER);
lblMois.setBounds(215,30,140,30);
lblMois.setFont(new Font("Arial", Font.BOLD, 20));
lblMois.setForeground(Color.WHITE);
txtMois = new JTextField();
txtMois.setFont(new Font("Arial", Font.BOLD, 16));
txtMois.setBounds(315,300,50,30);
JP.add(lblTemp);
JP.add(txtTemp);
JP.add(lblMois);
JP.add(txtMois);
JP.add(th1,BorderLayout.CENTER);
JP.add(slider1);
JP.add(slider2);
JP.add(th2,BorderLayout.CENTER);
JP.setBounds(width, 20, 400, 400);
JP.setVisible(true);
JP.setLayout(new java.awt.BorderLayout());
JP.validate();
//JP.add(txt);
return JP;
}
//and arduino output will be like this..
29.5,56.9 25.5,40.3
29.5,54,8 25.5,40.0
so on...

Display DICOM file on screen

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.

Passing Parameters to the print method (JAVA)

I need some help with my code. What i need it to do is everytime a page is added to the Java Book different data needs to be on the page every time. I've tried it a number of different ways and i just can't work it out!
Here's my code:
dataBase data = new dataBase();
int userCountAmount = data.getAmountOfUsers();
Book bk = new Book();
PrinterJob PJ = PrinterJob.getPrinterJob();
String[] pupilName = new String[userCountAmount];
String[] parentsName = new String[userCountAmount];
int parCount = 0;
int pupCount = 0;
public void print2() {
System.out.println(pupilName.length);
System.out.println(parentsName.length);
System.out.println(userCountAmount);
String[] custData = processData(data.getAllCustomers());
PageFormat portrait = PJ.defaultPage();
int pupNameCount = 0;
int parNameCount = 0;
portrait.setOrientation(PageFormat.PORTRAIT);
for (int i = 0; i < userCountAmount; i++) {
pupilName[i] = custData[pupNameCount];
parentsName[i] = custData[parNameCount];
System.out.println(custData[pupNameCount] + " " + custData[parNameCount]);
pupNameCount = pupNameCount + 13;
parNameCount = parNameCount + 13;
bk.append(new IntroPage(), PJ.defaultPage());
parCount++;
pupCount++;
System.out.println(parCount+" " + pupCount);
}
// setWindow();
//PageFormat PF = PJ.pageDialog(PJ.defaultPage());
PJ.setPageable(bk);
// PJ.setPrintable((Printable) this);
boolean doPrint = PJ.printDialog();
//JOptionPane.showMessageDialog(null, doPrint);
if (doPrint) {
try {
PJ.print();
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
}
private class IntroPage implements Printable {
/**
* Method: print
* <p>
*
* #param g
* a value of type Graphics
* #param pageFormat
* a value of type PageFormat
* #param page
* a value of type int
* #return a value of type int
*/
public int print(Graphics g, PageFormat pageFormat, int page) {
//--- Create the Graphics2D object
Graphics2D g2d = (Graphics2D) g;
//--- Translate the origin to 0,0 for the top left corner
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
//--- Set the default drawing color to black and get date
g2d.setPaint(Color.black);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
//draw tables
g2d.setPaint(Color.darkGray);
Rectangle2D.Double invoiceOut = new Rectangle2D.Double(10, 200, 400, 280);
Rectangle2D.Double invoiceDesc = new Rectangle2D.Double(10, 200, 200, 280);
Rectangle2D.Double invoiceSess = new Rectangle2D.Double(10, 200, 260, 280);
Rectangle2D.Double invoiceRate = new Rectangle2D.Double(10, 200, 330, 280);
Rectangle2D.Double invoiceTitle = new Rectangle2D.Double(10, 200, 400, 20);
Rectangle2D.Double totalAmount = new Rectangle2D.Double(340, 480, 70, 20);
g2d.draw(invoiceOut);
g2d.draw(invoiceDesc);
g2d.draw(invoiceSess);
g2d.draw(invoiceRate);
g2d.draw(invoiceTitle);
g2d.draw(totalAmount);
//table title strings
String descrp = "Description:";
String sesh = "Sessions:";
String rate = "Rate:";
String amount = "Amount:";
String titleText = "INVOICE";
String totalAmountString = "Total Amount:";
//Address Strings
String printDate = "Print Date: " + String.valueOf(dateFormat.format(date));
String line1Text = "16 here now";
String line2Text = "There";
String line3Text = "Thisshire";
String line4Text = "GU66 74S";
String phoneText = "Phone: 010101 0101010";
String mobileText = "Mobile: 010101 010101";
String emailText = "Email: here#there.com";
//to/for strings
String toString = "To: " + pupilName[pupCount-1];
String forString = "For: " + parentsName[parCount-1];
//footer strings
String footerLine1 = "Please pay by cash or cheque made payable to " + " " + " or by Internet Banking.";
String footerBold1 = "Mrs Bob Bobbins";
String iBankingDet = "company Sort code: " + " " + " Account Number: " + " " + "put your name as";
String bSortCode = "00-00-00";
String bAccountNumber = "0000000";
String iBankingDet2 = "reference!";
String noticeAlert = "Please Pay by latest on the first lesson of Term/Series.";
String customNotice = "** Thank you for your custom **";
//Set fonts
Font textFont = new Font("Tahoma", Font.PLAIN, 10);
Font toForFont = new Font("Tahoma", Font.BOLD, 10);
Font addressFont = new Font("Tahoma", Font.PLAIN, 8);
Font titleFont = new Font("Tahoma", Font.BOLD, 24);
Font textFontBold = new Font("Tahoma", Font.BOLD, 10);
//set table titles
g2d.setPaint(Color.GRAY);
g2d.setFont(addressFont);
g2d.drawString(descrp, 15, 215);
g2d.drawString(sesh, 215, 215);
g2d.drawString(rate, 275, 215);
g2d.drawString(amount, 345, 215);
g2d.drawString(totalAmountString, 285, 495);
//set title
g2d.setFont(titleFont);
g2d.drawString(titleText, 250, 20);
//set address
g2d.setFont(addressFont);
g2d.drawString(line1Text, 350, 40);
g2d.drawString(line2Text, 350, 50);
g2d.drawString(line3Text, 350, 60);
g2d.drawString(line4Text, 350, 70);
g2d.drawString(phoneText, 350, 80);
g2d.drawString(mobileText, 350, 90);
g2d.drawString(emailText, 350, 100);
g2d.drawString(printDate, 350, 120);
//draw to and for strings
g2d.setPaint(Color.darkGray);
g2d.setFont(toForFont);
g2d.drawString(toString, 10, 160);
g2d.drawString(forString, 180, 160);
//draw footer onto page
g2d.setPaint(Color.black);
g2d.setFont(textFont);
g2d.drawString(footerLine1, 10, 520);
g2d.setFont(textFontBold);
g2d.drawString(footerBold1, 220, 520);
g2d.setFont(textFont);
g2d.drawString(iBankingDet, 10, 545);
g2d.setFont(textFontBold);
g2d.drawString(bSortCode, 165, 545);
g2d.drawString(bAccountNumber, 295, 545);
g2d.setFont(textFont);
g2d.drawString(iBankingDet2, 10, 555);
g2d.setFont(textFontBold);
g2d.drawString(noticeAlert, 95, 575);
g2d.drawString(customNotice, 145, 595);
//add image to invoice
Image img;
img = new ImageIcon(this.getClass().getResource("logo.png")).getImage();
g2d.drawImage(img, -10, -10, 180, 84, null);
return (PAGE_EXISTS);
}
}
So basically, all i need to do is pass additional parameters to the print method, but this is impossible! It wouldn't implement the print class other wise!
I've tried substituting arrays and a lot more, i can't think of anything else!
You can't add arguments to the print() as it must implement the interface.
However you can add any number of arguments to the constructor, and these can be used in your method.
bk.append(new IntroPage(arg1, arg2, arg3), PJ.defaultPage());
You could add fields to the class IntroPage. Then when you create IntroPage pass appropriate arguments to initialize your fileds. And later, in print(), you can use the data from your fileds.

Saving a Java 2d graphics image as .png file

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.

Graphics disappear for unknown reason

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.

Categories

Resources