JAVA Drawing Graphics Save as JPEG?

My problem is this, I am trying to save my g2 graphic image to a jpg. This is how I have things setup, I will show code and my thoughts. What I need is help to figure out how I could save seperate .java files graphics g to the jpg format from a JFileChooser in a different .java file.
HERE IS THE CODE FOR HOW GRAPH IS CREATED. graph.java
I have a graph I am drawing in a seperate .java file and it is created like this:
public class graph extends JPanel {
    public static Graphics2D g2;
    final int HPAD = 60, VPAD = 40;
    int[] data;
    Font font;
    public test() {
        data = new int[] {120, 190, 211, 75, 30, 290, 182, 65, 85, 120, 100, 101};
        font = new Font("lucida sans regular", Font.PLAIN, 8);       
        setBackground(Color.white);
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        int w = getWidth();
        int h = getHeight();
        // scales
        float xInc = (w - HPAD - HPAD) / 10f;
        float yInc = (h - 2*VPAD) / 10f;
        int[] dataVals = getDataVals();
        float yScale = dataVals[2] / 10f;
//        etc... (the rest is just drawing...blah...blah)
}HERE IS THE CODE FOR HOW MY GRAPH IS DISPLAYED AND TRYING TO BE SAVED. results.java
The graph I created is then displayed in a JPanel and there is a button in the results window to save the graph results. This is where I am having difficulty as I am trying to save the g2 from graph.java (declared public static...not sure if this a good idea) but anyway I want to save this as a jpg heres the code:
        resultPanel = new JPanel(new PercentLayout());
        graph drawing = new graph();
        resultPanel.add (
            drawing,
            new PercentLayout.Constraint(1,41,49,50));
        resultPanel.add (
            saveButton1,
            new PercentLayout.Constraint(1,94,25,5));
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == saveButton1) {
            doSaveGraph();
    public void doSaveGraph() {
        JFileChooser fileSaver;
        fileSaver = new JFileChooser(); // The file-opening dialog
        ExampleFileFilter filter = new ExampleFileFilter("jpg");
        filter.setDescription("JPEG Picture File");
        fileSaver.addChoosableFileFilter(filter);
        try {
            if(fileSaver.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                File f = fileSaver.getSelectedFile();
                BufferedImage img = new BufferedImage(672,600, BufferedImage.TYPE_INT_RGB);
      // SOMEWHERE IN HERE IS WHERE I NEED TO GRAB G2?  I AM NOT SURE WHAT TO DO HERE
                //Graphics g = img.getGraphics();
                //panel.paint(g);
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
                JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
                param.setQuality(1f, true);
                encoder.setJPEGEncodeParam(param);
                encoder.encode(img);
                System.out.println("It worked");
            else{}
        catch (Exception e) {
            e.printStackTrace();
...If you can help me I will be very happy, and give you 10 dukes! LOL and I appreciate the help!

import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SavingGraphics
    public static void main(String[] args)
        GraphicsCreationPanel graphicsPanel = new GraphicsCreationPanel();
        GraphicsSaver saver = new GraphicsSaver(graphicsPanel);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(saver.getUIPanel(), "North");
        f.getContentPane().add(graphicsPanel);
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class GraphicsCreationPanel extends JPanel
    String text;
    Font font;
    public GraphicsCreationPanel()
        text = "hello world";
        font = new Font("lucida bright regular", Font.PLAIN, 36);
        setBackground(Color.white);
    protected void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        int w = getWidth();
        int h = getHeight();
        g2.setPaint(Color.blue);
        g2.draw(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8));
        g2.setPaint(Color.orange);
        g2.fill(new Ellipse2D.Double(w/12, h/12, w*5/6, h*5/6));
        g2.setPaint(Color.red);
        g2.fill(new Ellipse2D.Double(w/6, h/6, w*2/3, h*2/3));
        g2.setPaint(Color.black);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics lm = font.getLineMetrics(text, frc);
        float textWidth = (float)font.getStringBounds(text, frc).getWidth();
        float x = (w - textWidth)/2;
        float y = (h + lm.getHeight())/2 - lm.getDescent();
        g2.drawString(text, x, y);
class GraphicsSaver
    GraphicsCreationPanel graphicsPanel;
    JFileChooser fileChooser;
    public GraphicsSaver(GraphicsCreationPanel gcp)
        graphicsPanel = gcp;
        fileChooser = new JFileChooser(".");
    private void save()
        if(fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
            File file = fileChooser.getSelectedFile();
            String ext = file.getPath().substring(file.getPath().indexOf(".") + 1);
            BufferedImage image = getImage();
            try
                ImageIO.write(image, ext, file);
            catch(IOException ioe)
                System.out.println("write: " + ioe.getMessage());
    private BufferedImage getImage()
        int w = graphicsPanel.getWidth();
        int h = graphicsPanel.getHeight();
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        graphicsPanel.paint(g2);
        g2.dispose();
        return bi;
    public JPanel getUIPanel()
        JButton save = new JButton("save");
        save.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
                save();
        JPanel panel = new JPanel();
        panel.add(save);
        return panel;
}

Similar Messages

  • How do I save user drawn graphics to a jpeg? (This code doesn't work).

    As the title says, I have the code that I think should work but cannot see what is wrong with it:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import javax.imageio.ImageIO;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class SavePaint extends JPanel {
        protected JButton saveButton;
        protected JFrame frame;
        protected int firstX, firstY, currentX, currentY, counter;
        protected JPanel mainPanel = this, panel2;
        protected JButton clearButton;
        protected Color background = Color.PINK;
        protected boolean dragged;
        public SavePaint() {
            JFrame frame = new JFrame("TheFrame");
            frame.add(mainPanel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(400, 400);
            frame.setVisible(true);
            MyMouseListener myMouseListener = new MyMouseListener();
            mainPanel.addMouseListener(myMouseListener);
            mainPanel.addMouseMotionListener(myMouseListener);
        private class MyMouseListener implements MouseListener, MouseMotionListener {
            public void mouseClicked(MouseEvent e) throws UnsupportedOperationException {
                // code
            public void mousePressed(MouseEvent e) throws UnsupportedOperationException {
                firstX = e.getX();
                firstY = e.getY();
                dragged = true;
            public void mouseReleased(MouseEvent e) throws UnsupportedOperationException {
                currentX = e.getX();
                currentY = e.getY();
                dragged = true;
                repaint();
            public void mouseEntered(MouseEvent e) throws UnsupportedOperationException {
                // code
            public void mouseExited(MouseEvent e) throws UnsupportedOperationException {
                try {
                    BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
                    Graphics2D graphics2D = image.createGraphics();
                    mainPanel.paint(graphics2D);
                    ImageIO.write(image, "jpeg", new File("/home/deniz/Desktop/jmemPractice.jpeg"));
                } catch (Exception exception) {
                    System.out.println("The exception is: " + exception);
            public void mouseDragged(MouseEvent e) throws UnsupportedOperationException {
                currentX = e.getX();
                currentY = e.getY();
                dragged = true;
                repaint();
            public void mouseMoved(MouseEvent e) throws UnsupportedOperationException {
                dragged = false;
        protected void paintComponent(Graphics g) {
            g.drawLine(firstX, firstY, currentX, currentY);
            firstX = currentX;
            firstY = currentY;
        public static void main(String[] args) {
            new SavePaint();
    }An observation that I made is that on top of the white background, there is a dot (is this technically one pixel?) which seems to be the endpoint of what the user (in this case - me) has drawn. The frame has a continous flow of dots display as the user makes them with the cursor. Why isn't the jpeg a continuous flow of dots as well?
    Any help would be greatly appreciated!
    Thanks in advance!

    there is a dot (is this technically one pixel?) This shows a problem with your painting logic.
    Whenever the panel is repainted, you only have a single line of code, so only a single pixel is ever drawn. The drawing looks like its working because Swing hasn't asked the panel to repaint itself so you see the cummulative effect of all your drawLine(...) method.
    However, try drawing a few lines, then minimize the window and then restore the window. You will only see a single pixel. This is exactly what you see when you try to create the jpeg.
    You should probably be using the "Draw on Image" approach suggested in [url http://www.camick.com/java/blog.html?name=custom-painting-approaches]Custom Painting Approaches.
    Just for interest sake you can also use the ScreenImage class I suggested to you earlier in your other posting (when you didn't bother to accept the answer I provided, so this will be the last time I help if you don't learn to use the forum properly).
    ScreenImage.writeImage(ScreenImage.createImage((Component)mainPanel), "mainPanel.jpg");This will force the class to use the Robot to capture the actual pixels on the screen. Using a Robot is slower then using the paint() method.

  • Draw graphics on Image and Save it

    hi!,
    Can anyone help me how to draw graphics(Line, rectangle.ect) on an Image and save it. I need to do the following steps.
    1. Get the Image from the local file system
    2. Based on the parameters i receive for graphics(Ex: rectangle).
    -I have to draw a rectangle on the Image.
    3. Save the Image again to the file system
    I would appreciate if any one has any ideas or sample code I can start with.
    Thanks!!!

    Here's an example using the javax.imageio package.
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    public class DrawOnImage {
        public static void main(String[] args) {
            try {
                BufferedImage buffer = ImageIO.read(new File(args[0]));
                Graphics2D g2d = buffer.createGraphics();
                Rectangle rect = new Rectangle(10, 10, 100, 100);
                g2d.setPaint(Color.RED);
                g2d.draw(rect);
                ImageIO.write(buffer, "JPG", new File(args[1]));
            } catch (IOException e) {
                e.printStackTrace();
    }

  • Adding java 2d graphices to a JScrollPane

    How can I use the graphics 2d in a Java Applet JScrollPane?
    here is me code. I have a a ImageOps.java file that does a bunch of Java 2d, but I need it to fit into my applet's JScrollPane. Can anyone help me?
    package louis.tutorial;
    import java.awt.BorderLayout;
    import javax.swing.JPanel;
    import javax.swing.JApplet;
    import java.awt.Dimension;
    import javax.swing.JInternalFrame;
    import javax.swing.JButton;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.Rectangle;
    import java.awt.Point;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JTextArea;
    import javax.imageio.ImageIO;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.ImageIcon;
    import javax.swing.KeyStroke;
    import java.awt.FileDialog;
    import java.awt.Toolkit;
    import java.awt.Color;
    import java.awt.image.BufferedImage;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.io.File;
    import java.io.IOException;
    import java.net.URL;
    import javax.swing.JScrollPane;
    * Place class description here
    * @version 1.0
    * @author llakser
    public class ImageApplet extends JApplet {
    private JPanel jContentPane = null;
    private JPanel jpLower = null;
    private JButton JBFirst = null;
    private JButton JBPrevious = null;
    private JButton JBNext = null;
    private JButton JBLast = null;
    private JButton JBZoonIn = null;
    private JButton JBZoomOut = null;
    private JButton JBAnimate = null;
    private JButton JBPause = null;
    private JButton JBAutoRepeat = null;
    private JComboBox jcbFrameDelay = null;
    private BufferedImage image; // the rasterized image
    private Image[] numbers = new Image[10];
    private Thread animate;
    private MediaTracker tracker;
    private int frame = 0;
    private ImageIcon[] icon = null;
    private JFrame f = new JFrame("ImageOps");
    * This is the xxx default constructor
    public ImageApplet() {
         super();
    * This method initializes this
    * @return void
    public void init() {
         this.setSize(600, 600);
         this.setContentPane(getJContentPane());
         this.setName("");
         this.setMinimumSize(new Dimension(600, 600));
         this.setPreferredSize(new Dimension(600, 600));
    // f.addWindowListener(new WindowAdapter() {
    // public void windowClosing(WindowEvent e) {System.exit(0);}
    ImageOps applet = new ImageOps();
    //getJContentPane().add("Center", f);
    getJContentPane().add("Center", applet);
    //applet.add(f);
    applet.init();
    f.pack();
    f.setSize(new Dimension(550,550));
    f.setVisible(true);
    public void load() {
         tracker = new MediaTracker(this);
         for (int i = 1; i < 10; i++) {
         numbers[i] = getImage (getCodeBase (), i+".jpeg");//getImage(getDocumentBase(), "Res/" + i + ".gif");
         //Image img;
         //ico[i] = new ImageIcon(getCodeBase (), i+".jpeg");
         /* if (fInBrowser)
         img = getImage (getCodeBase (), "1.jpeg");
         else
         img = Toolkit.getDefaultToolkit ().getImage (
         "1.jpeg");*/
         tracker.addImage(numbers, i);
         try {
         tracker.waitForAll();
         } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         int i = 1;
         // for (int i = 1; i < 10; i++)
              icon[0] = new ImageIcon ("C:/images2/1.jpeg");//getImage(getDocumentBase(), "Res/" + i + ".gif");
              //icon[0] = new ImageIcon("C:/images2/1.jpg");
              //System.out.println("Made it after icon " + ico.toString());
              //ImageIcon ii = new ImageIcon("1.jpg");
              //jLabel = new JLabel(icon);
              //jLabel.setText("JLabel");
              //jLabel.setIcon(icon[0]);
         Graphics g = null;
              //g.drawImage(numbers[1],0,0,1500,1400,jScrollPane);
         //ImageIcon ii = new ImageIcon(numbers[2]);
         //this.jScrollPane.add(new JLabel(ii));// = new JScrollPane(new JLabel(ii));
         // System.out.println("Gee I made it..");
              //scroll.paintComponents(g);
              //paintComponents(g);
    public void paintComponents(Graphics g) {
    super.paintComponents(g);
    // Retrieve the graphics context; this object is used to paint shapes
    Graphics2D g2d = (Graphics2D)g;
    // Draw an oval that fills the window
    int width = this.getBounds().width;
    int height = this.getBounds().height;
    Icon icon = new ImageIcon("C:/images2/1.jpg");
    //jLabel.setIcon(icon);
    //g2d.drawImage(0,0,1500,1400);
    g2d.drawOval(10,20, 300,400);
    // and Draw a diagonal line that fills MyPanel
    g2d.drawLine(0,0,width,height);
    * This method initializes jContentPane
    * @return javax.swing.JPanel
    private JPanel getJContentPane() {
         if (jContentPane == null) {
         jContentPane = new JPanel();
         jContentPane.setLayout(new BorderLayout());
         jContentPane.setPreferredSize(new Dimension(768, 576));
         jContentPane.setMinimumSize(new Dimension(768, 576));
         jContentPane.setName("");
         jContentPane.add(getJpLower(), BorderLayout.SOUTH);
         return jContentPane;
    * This method initializes jpLower     
    * @return javax.swing.JPanel     
    private JPanel getJpLower() {
    if (jpLower == null) {
         try {
         jpLower = new JPanel();
         jpLower.setLayout(null);
         jpLower.setPreferredSize(new Dimension(500, 100));
         jpLower.setMinimumSize(new Dimension(500, 160));
         jpLower.add(getJBFirst(), null);
         jpLower.add(getJBPrevious(), null);
         jpLower.add(getJBNext(), null);
         jpLower.add(getJBLast(), null);
         jpLower.add(getJBZoonIn(), null);
         jpLower.add(getJBZoomOut(), null);
         jpLower.add(getJBAnimate(), null);
         jpLower.add(getJBPause(), null);
         jpLower.add(getJBAutoRepeat(), null);
         jpLower.add(getJcbFrameDelay(), null);
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return jpLower;
    * This method initializes JBFirst     
    * @return javax.swing.JButton     
    private JButton getJBFirst() {
    if (JBFirst == null) {
         try {
         JBFirst = new JButton();
         JBFirst.setText("First");
         JBFirst.setLocation(new Point(7, 7));
         JBFirst.setSize(new Dimension(59, 26));
         JBFirst.addActionListener(new java.awt.event.ActionListener() {
         public void actionPerformed(java.awt.event.ActionEvent e) {
              System.out.println("First Button Clicked()");
         load();
              // TODO Auto-generated Event stub actionPerformed()
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBFirst;
    * This method initializes JBPrevious     
    * @return javax.swing.JButton     
    private JButton getJBPrevious() {
    if (JBPrevious == null) {
         try {
         JBPrevious = new JButton();
         JBPrevious.setText("Previous");
         JBPrevious.setLocation(new Point(69, 7));
         JBPrevious.setSize(new Dimension(94, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBPrevious;
    * This method initializes JBNext     
    * @return javax.swing.JButton     
    private JButton getJBNext() {
    if (JBNext == null) {
         try {
         JBNext = new JButton();
         JBNext.setText("Next");
         JBNext.setLocation(new Point(166, 7));
         JBNext.setSize(new Dimension(66, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBNext;
    * This method initializes JBLast     
    * @return javax.swing.JButton     
    private JButton getJBLast() {
    if (JBLast == null) {
         try {
         JBLast = new JButton();
         JBLast.setText("Last");
         JBLast.setLocation(new Point(235, 7));
         JBLast.setSize(new Dimension(59, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBLast;
    * This method initializes JBZoonIn     
    * @return javax.swing.JButton     
    private JButton getJBZoonIn() {
    if (JBZoonIn == null) {
         try {
         JBZoonIn = new JButton();
         JBZoonIn.setText("Zoom In");
         JBZoonIn.setLocation(new Point(408, 7));
         JBZoonIn.setPreferredSize(new Dimension(90, 26));
         JBZoonIn.setSize(new Dimension(90, 26));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBZoonIn;
    * This method initializes JBZoomOut     
    * @return javax.swing.JButton     
    private JButton getJBZoomOut() {
    if (JBZoomOut == null) {
         try {
         JBZoomOut = new JButton();
         JBZoomOut.setBounds(new Rectangle(503, 7, 90, 26));
         JBZoomOut.setPreferredSize(new Dimension(90, 26));
         JBZoomOut.setText("Zoom Out");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBZoomOut;
    * This method initializes JBAnimate     
    * @return javax.swing.JButton     
    private JButton getJBAnimate() {
    if (JBAnimate == null) {
         try {
         JBAnimate = new JButton();
         JBAnimate.setText("Animate");
         JBAnimate.setSize(new Dimension(90, 26));
         JBAnimate.setPreferredSize(new Dimension(90, 26));
         JBAnimate.setLocation(new Point(408, 36));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBAnimate;
    * This method initializes JBPause     
    * @return javax.swing.JButton     
    private JButton getJBPause() {
    if (JBPause == null) {
         try {
         JBPause = new JButton();
         JBPause.setPreferredSize(new Dimension(90, 26));
         JBPause.setLocation(new Point(503, 36));
         JBPause.setSize(new Dimension(90, 26));
         JBPause.setText("Pause");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBPause;
    * This method initializes JBAutoRepeat     
    * @return javax.swing.JButton     
    private JButton getJBAutoRepeat() {
    if (JBAutoRepeat == null) {
         try {
         JBAutoRepeat = new JButton();
         JBAutoRepeat.setBounds(new Rectangle(446, 65, 106, 26));
         JBAutoRepeat.setText("Auto Repeat");
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return JBAutoRepeat;
    * This method initializes jcbFrameDelay     
    * @return javax.swing.JComboBox     
    private JComboBox getJcbFrameDelay() {
    if (jcbFrameDelay == null) {
         try {
         jcbFrameDelay = new JComboBox();
         jcbFrameDelay.setSize(new Dimension(156, 25));
         jcbFrameDelay.setName("Frame Delay");
         jcbFrameDelay.setLocation(new Point(7, 35));
         } catch (java.lang.Throwable e) {
         // TODO: Something
    return jcbFrameDelay;
    } // @jve:decl-index=0:visual-constraint="10,10"

    I think you've got it:
    public class ImageComponent extends JPanel { //or JComponent
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            //do your rendering here
    }The fact that ImageComponent sits inside JScrollPane is accidental, right?
    It should be able to function on its own, without a JScrollPane present, just as JTextArea can.
    So I'm not sure what your question is. Can you post a small (<1 page)
    example program demonstrating your problem.
    For example, here are a very few lines demonstrating what I am trying to say:
    import java.awt.*;
    import javax.swing.*;
    class CustomExample extends JPanel {
        public CustomExample() {
            setPreferredSize(new Dimension(800,800));
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillOval(0, 0, getWidth(), getHeight());
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    JFrame f = new JFrame("CustomExample");
                    f.getContentPane().add(new JScrollPane(new CustomExample()));
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.setSize(400,400);
                    f.setLocationRelativeTo(null);
                    f.setVisible(true);
    }Now you post your problem in a program that is just as short.

  • Cannot resolve symbol java.awt.graphics

    // DrawRectangleDemo.java
    import java.awt.*;
    import java.lang.Object;
    import java.applet.Applet;
    public class DrawRectangleDemo extends Applet
         public void paint (Graphics g)
              // Get the height and width of the applet's drawing surface.
              int width = getSize ().width;
              int height = getSize ().height;
              int rectWidth = (width-50)/3;
              int rectHeight = (height-70)/2;
              int x = 5;
              int y = 5;
              g.drawRect (x, y, rectWidth, rectHeight);
              g.drawString ("drawRect", x, rectHeight + 30);
              x += rectWidth + 20;
              g.fillRect (x, y, rectWidth, rectHeight);
              // Calculate a border area with each side equal tp 25% of
              // the rectangle's width.
              int border = (int) (rectWidth * 0.25);
              // Clear 50% of the filled rectangle.
              g.clearRect (x + border, y + border,
                             rectWidth - 2 * border, rectHeight - 2 * border);
              g.drawString ("fillRect/clearRect", x, rectHeight + 30);
              x += rectWidth + 20;
              g.drawRoundRect (x, y, rectWidth, rectHeight, 15, 15);
              g.drawString ("drawRoundRect", x, rectHeight + 30);
              x=5;
              y += rectHeight + 40;
              g.setColor (Color.yellow);
              for (int i = 0; i < 4; i++)
                   g.draw3DRect (x + i * 2, y + i * 2,
                                       rectWidth - i * 4, rectHeight - i * 4, false);
              g.setColor (Color.black);
              g.drawString ("draw3DRect", x, y, + rectHeight + 25);
              x += rectWidth + 20;
              g.setColor (Color.yellow);
              g.fill3DRect (x, y, rectWidth, rectHeight, true);
              g.setColor (Color.black);
              g.drawString ("fill3DRect", x, y, + rectHeight + 25);
    Help me with this codes. I typed correctly but there still errors.
    --------------------Configuration: JDK version 1.3.1 <Default>--------------------
    D:\Program Files\Xinox Software\JCreator LE\MyProjects\DrawRectangleDemo.java:56: cannot resolve symbol
    symbol : method drawString (java.lang.String,int,int,int)
    location: class java.awt.Graphics
              g.drawString ("draw3DRect", x, y, + rectHeight + 25);
    ^
    D:\Program Files\Xinox Software\JCreator LE\MyProjects\DrawRectangleDemo.java:64: cannot resolve symbol
    symbol : method drawString (java.lang.String,int,int,int)
    location: class java.awt.Graphics
              g.drawString ("fill3DRect", x, y, + rectHeight + 25);
    ^
    2 errors
    Process completed.
    -------------------------------------------------------------------------------------------------------------------------------

    cannot resolve symbol
    symbol : method drawString (java.lang.String,int,int,int)
    This is telling you that you are trying to invoke the drawString() method with 4 parameters: String, int, int, int
    If you look at the API the drawString() method need 3 parameters: String, int, int - so you have an extra int
    location: class java.awt.Graphics
    g.drawString ("draw3DRect", x, y, + rectHeight + 25);
    Now is you look at your code you will find that you have 3 ',' in you method call. (I don't think you want the ',' after the y.

  • Save as JPEG changes CMYK colour

    Hi,
    I have a solid colour in Photshop that I set CMYK values for (I work in CMYK image mode). When I save as JPEG, the resulting JPEG file changes one of the CMYK values by 1 percentage point. When I save as TIFF, it works fine (CMKY values match original photshop file). What is going on?
    This is for CS4.
    Thanks.

    I'm confused. If your goal is to print the image, why not open the jpeg in Photoshop, do a save as using the native .PSD Photoshop file format, and just continue to work and save in that file format? Going back to jpeg makes no sense.
    In the first place, Jpeg does not support the CMYK color space, so every time you save it, it will save in the much smaller sRGB space. Also, between this and the fact that it compresses the image even at the highest settings, you are going to get changes in the image, including in the colors.
    Just avoid all this and work in .PSD file format.
    Another point: all of the photographers I know usually work in an RGB color space, Adobe rgb for example. As I understand it, CMYK is used in graphics and publication, often because you want to split the image into four channels to use in commercial four-color offset printing.
    If you're going to be doing inkjet printing, or via a service, I'd suggest staying in an Rgb workspace--you can still decide to use the CMYK menu to select your colors.
    Color management can be tricky, so I'd suggest you do a bit of research.

  • Help in drawing graphics.

    Hi friends,
    I'm newbie in drawing graphics with Java, and I need some help in a specific part of my program.
    What I want to do is to draw a waveform of a sound file. That waveform is built based on the amplitude of each sound sample. So I have a big vector full of those amplitudes. Now what I need to do is plot each point on the screen. The x coordinate of the point will be its time position in the time axis. The y coordinate of the point will be the amplitude value. Ok... Now I have a lot of doubts...
    1 - can someone give me a simple example on how to plot points in a java app? I know I have to extend a JPainel class, but I don't know much about those paint, and repaint methods. It's all weird to me. I already searched through the tutorial and the web, but I couldn't see a simple, good example. Can someone hand me this?
    2 - Once I know how to draw those graphics, I need to find a way to put a button, or anything like that, in my app, so the user can press that button to see to next part of the waveform, since the wave is BIG, and doesn't fit entirely on the screen. Is this button idea ok? Can I use some sort of SCROLL on it, would it be better?
    Well... I'm trying to learn it all. ANY help will be appreciated, ANY good link, little hint, first step, anything.
    Thanks for all, in advance.
    Leonardo
    (Brazil)

    This will lead you, in this sample you have a panel and a button,
    every click will fill a vector with random 700 points and draw them on the panel,
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Wave extends Frame implements ActionListener
         WPanel   pan    = new WPanel();
         Vector   points = new Vector();
         Button   go     = new Button("Go");
         Panel    cont   = new Panel();
    public Wave()
         super();
         setBounds(6,6,700,400);     
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   dispose();     
                   System.exit(0);
         add("Center",pan);
         go.addActionListener(this);
         cont.add(go);
         add("South",cont);
         setVisible(true);
    public void actionPerformed(ActionEvent a)
         points.removeAllElements();
         for (int j=0; j < 700; j++)
              int y = (int)(Math.random()*350);
              points.add(new Point(j,y+1));
         pan.draw(points);
    public class WPanel extends Panel
         Vector   points;
    public WPanel()
         setBackground(Color.pink);
    public void draw(Vector points)
         this.points = points;
         repaint();
    public void paint(Graphics g)
         super.paint(g);
         if (points == null) return;
         for (int j=1; j < points.size(); j++)
              Point p1 = (Point)points.get(j-1);
              Point p2 = (Point)points.get(j);
              g.drawLine(p1.x,p1.y,p2.x,p2.y);
    public static void main (String[] args)
         new Wave();  
    Noah

  • Save to jpeg

    hi all,
    i tried to save a jlayeredPane to a jpeg; all the compnents are saved but the background dirty, i mean wth different kind of fragments of images, and i don't know from where;
    how can i save a jpeg with the background clear ?
    Himerus
    thanks in advance

    Works for me:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ComponentSaver {
        public static void save(Component comp, File file) throws IOException {
            file.delete();
            int w = comp.getWidth();
            int h = comp.getHeight();
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bi.createGraphics();
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, w, h); //clear
            comp.paint(g);
            g.dispose();
            ImageIO.write(bi, "jpeg", file);
        public static void main(String[] args) {
            final JFrame f = new JFrame("ComponentSaver");
            JButton save = new JButton("save");
            save.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent evt) {
                    try {
                        save(f.getLayeredPane(), new File("junk.jpeg"));
                    } catch (IOException e) {
                        e.printStackTrace();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            Container cp = f.getContentPane();
            cp.add(new JLabel("sample label"), BorderLayout.CENTER);
            cp.add(save, BorderLayout.SOUTH);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • How to call - draw(Graphics g)

    This is a little method in my Applet:
    public void draw(Graphics g)
    g.drawImage(image, 0, 0, this);
    What I want is to call this method when I need it, not automatically like paint(Graphics g), but I couldn't figure out how to call, because Graphics is abstract class, can not be instantiated .
    Pleeeeeeeeeeeeease help me out , many thanks !!!

    This is a little method in my Applet:
    public void draw(Graphics g)
    g.drawImage(image, 0, 0, this);
    What I want is to call this method when I need it,Why?
    not automatically like paint(Graphics g), but I
    couldn't figure out how to call, because Graphics is
    abstract class, can not be instantiated .Right. You can't, nor should you ever need to do what you want to do. The Graphics object is passed to you in the paint() method.
    See:
    http://java.sun.com/products/jfc/tsc/articles/painting/index.html

  • Java 2D graphics help

    Hi, i need 2 files, Index class file(JFrame) and a Draw.class file
    Basically, i have a button in the index jframe form, and when i clicked on the button, there will be a JPanel/ Applet pop up, with a circle in it. can any1 write me some sample codes? a simple one will do. Thanks

    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.BasicStroke;
    import java.awt.GradientPaint;
    import java.awt.TexturePaint;
    import java.awt.Rectangle;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Rectangle2D;
    import java.awt.geom.RoundRectangle2D;
    import java.awt.geom.Arc2D;
    import java.awt.geom.Line2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JPanel;
    public class ShapesJPanel extends JPanel
       // draw shapes with Java 2D API
       public void paintComponent( Graphics g )
          super.paintComponent( g ); // call superclass's paintComponent
          Graphics2D g2d = ( Graphics2D ) g; // cast g to Graphics2D
          // draw 2D ellipse filled with a blue-yellow gradient
          g2d.setPaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100,
             Color.YELLOW, true ) ); 
          g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
          // draw 2D rectangle in red
          g2d.setPaint( Color.RED );                 
          g2d.setStroke( new BasicStroke( 10.0f ) );
          g2d.draw( new Rectangle2D.Double( 80, 30, 65, 100 ) );
          // draw 2D rounded rectangle with a buffered background
          BufferedImage buffImage = new BufferedImage( 10, 10,
             BufferedImage.TYPE_INT_RGB );
          // obtain Graphics2D from bufferImage and draw on it
          Graphics2D gg = buffImage.createGraphics();  
          gg.setColor( Color.YELLOW ); // draw in yellow
          gg.fillRect( 0, 0, 10, 10 ); // draw a filled rectangle
          gg.setColor( Color.BLACK );  // draw in black
          gg.drawRect( 1, 1, 6, 6 ); // draw a rectangle
          gg.setColor( Color.BLUE ); // draw in blue
          gg.fillRect( 1, 1, 3, 3 ); // draw a filled rectangle
          gg.setColor( Color.RED ); // draw in red
          gg.fillRect( 4, 4, 3, 3 ); // draw a filled rectangle
          // paint buffImage onto the JFrame
          g2d.setPaint( new TexturePaint( buffImage,
             new Rectangle( 10, 10 ) ) );
          g2d.fill(
             new RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );
          // draw 2D pie-shaped arc in white
          g2d.setPaint( Color.WHITE );
          g2d.setStroke( new BasicStroke( 6.0f ) );
          g2d.draw(
             new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );
          // draw 2D lines in green and yellow
          g2d.setPaint( Color.GREEN );
          g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) );
          // draw 2D line using stroke
          float dashes[] = { 10 }; // specify dash pattern
          g2d.setPaint( Color.YELLOW );   
          g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND,
             BasicStroke.JOIN_ROUND, 10, dashes, 0 ) );
          g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) );
       } // end method paintComponent
    } // end class ShapesJPanelbasically.. when i click on a button in the index class file, it will call this class file, i do not know to code to call this class file.
    Edited by: slaydragon on Nov 11, 2007 10:55 AM

  • What's wrong with this mini-code? (Trying to draw graphics).

    Could someone please help me fix what's wrong the following test-program?:
    package project;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class GraphicsTester extends JPanel
        JPanel thePanel = this;
        public void GraphicsTester()
            JFrame frame = new JFrame();
            frame.setSize(600,600);
            frame.add(thePanel);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            g.drawRect(50, 50, 50, 50);
            System.out.println("Sup fool");
        public static void main(String[] args)
            GraphicsTester gt = new GraphicsTester();
            System.out.println("works2");
    }Any help would be greatly appreciated!
    Thanks in advance!

    Also, all Swing code should be called from the Event Dispatch Thread. It probably isn't hurting much in your case. But, in the body of main, do this (instead of the comment, put what you currently have as the body of main):
    EventQueue.invokeLater(
    new Runnable()
          public void run()
              // Your current body of main.
      });

  • How to default save as JPEG?

    My current workflow has been placing rectangular photos onto white square backgrounds and then saving as JPEGs. Each time I have to save the resulting image, I have to manually opt for JPEGs. Is there any way of making this a default? Thanks if anyone knows.
    Richard

    When you have several layers, a jpeg format can't save your work, you have to create another file in psd or tiff format to keep the original unchanged and a new file with layers as a copy.
    The normal use of the 'save' command is to overwrite the original image. What you really want is not a single step, it's to:
    - flatten the layers
    - save (overwrite) the original image file.
    Allowing a default to automatically do that when you are editing a layered file would be a disaster in most cases. So you have two ways to tell the software to do that:
    - specify the jpeg format as output and if you want to overwrite the original or create a copy or version set
    - do a 'flatten image' before trying to do a 'save' or 'save as'.
    (If you use 'save for web', you are implicitly telling you want to flatten and save as jpeg).

  • My images won't save as jpeg unless I go to Save As... what is happening to my images?

    My images look great when edited in photoshop and when I got to close and save it won't give me the option to save as a jpeg so I have to go to File Save As and then save to jpeg. But when I go to order them in Roes they look drab and awful but the thumbnail looks great. Am I saving it wrong somehow?

    Go to Image --> Mode and set image to 8 or 16 bit. If the image has 32 bit, it won't export through the save for web dialog.
    Let me know if this fixes the issue.
    Reidar

  • I edit my photos in Photoshop, save as jpeg then import back into iPhoto.  But if I add text to an image in Photoshop can't save as jpeg but as psd. Is there any way I can change to jpeg in iPhoto?

    I edit my RAW photos in Photoschop CS3, save as jpeg then import back into iPhoto 11.  If I add text in Photoshop I can't save as jpeg but as psd.  Is there any way I can change to jpeg in iPhoto?

    Terence Devlin wrote:
    Yes you can. But you need to flatten it as jpeg doesn't support layers.
    While the final JPEG can't have layers, it is not necessary to flatten the original Photoshop file to create a JPEG. There are two ways to make a JPEG while not losing the flexibility of preserving layers, and they both flatten on the fly while saving.
    I just tried this in Photoshop CS3 myself. When I add a text layer, and choose Save, the Save As dialog box comes up and defaults to PSD as was described. But... that is just the default! Go ahead and choose JPEG from the Format pop-up menu down below the file list. JPEG is in there. So what happens to the layers? Notice when you choose JPEG, the Layers box grays out and the "As A Copy" box grays out and is checked (i.e. you cannot uncheck it). What is going on here is Photoshop will gladly make a JPEG of your layered file, but it will force the JPEG to be a copy, so as to not overwrite the original layered file. This is good, because your Photoshop file with its editable text layer is preserved, and you get a JPEG copy to put in iPhoto.
    The second way is, instead of doing Save or Save As, choose File/Save for Web and Devices. This will also give you a JPEG choice, and also create an exported copy. Because this way makes files for the Web, they will be smaller than JPEGs from Save As because they will lack built-in previews (which you don't really need these days) and other extra metadata that take up space.
    Either way you get a JPEG you can toss back into iPhoto.
    Terence Devlin wrote:
    Only by exporting.
    The Export menu in Photoshop CS3 does not have any direct choices for JPEG.

  • One-click 'Save as jpeg' shortcut script please! - saved in the same folder

    Hi, I've been re-directed here because I was told a script could solve my problems - but I have no scripting experience/knowledge/ability! Below is my original problem and post. I got as close as 2 button presses, but I'm after that sweet, sweet single-button, double-my-productivity shortcut! Thanks!
    http://forums.adobe.com/thread/1106992
    I use 'Save as .jpeg' ALL the time (Photoshop CS6, Mac ML), and it really feels like I should just be able to press one button (a shortcut) and the name/quality dialogs don't appear and it just saves a .jpeg into the folder that my original .PSD/file is in.
    So basically:
    - Press one button to save my open .PSD/file as a .jpeg
    - Automatically save it in the same folder as my .PSD
    - Save it as '10' quality in the jpeg settings
    - No dialog boxes, as soon as I press the button, it saves it - if there's already a .jpeg of the same name, it creates a '-1','-2' etc.
    I've tried using 'Actions', but it seems to save it wherever my original Action folder was - it doesn't change to whatever the current folder the .PSD is in...
    Thanks!
    Adam

    File -> Scripts -> Script Events Manager
    Click Enable Events at the top
    Select Save Document from Photoshop Event  drop down
    Select Save Extra JPEG from Script drop down
    Click Add
    Click Done
    EVERY document you save, except JPEG files, will save a jpg file. Saving will be slower.
    You will need to modify line 62 of the Save Extra JPEG.jsx file located here: <YOUR_PHOTOSHOP_INSTALL_LOCATION>\Presets\Scripts\Event Scripts Only
    In order to boost your quality to '10'. Here is the line in question
    jpegOptions.quality = 2; // really low
    Change it to
    jpegOptions.quality = 10; // really high
    You will need to modify the script to get this problem solved as well: it saves it - if there's already a .jpeg of the same name, it creates a '-1','-2' etc.
    You can steal code out of Image Processor that finds a file name that is unique for the folder so you don't get overwrites.
    Are you sure you want that? If you do lots of saves you are going to fill up your disk fast.

Maybe you are looking for

  • I updated Lightroom to version 6, but now it won't open.

    I updated Lightroom to version 6 from 5.6, and now it won't open.  I have tried un-installing it and re-installing it and nothing.  I then uninstalled 5.6 to see if that would help (shouldn't this have disappeared after the update??), and nothing.  P

  • IS Windows 7 already Mounted on BOot camp in OS x Mountain Lion

    Hi GUys i just wanted to ask that is the Windows 7 64 bit already mounted on BOOT CAMP in OS X mounation lion............... if it is do i need to buy a Disk for windows 7 Just in case

  • ITunes v9.1 Import MP3 Custom Settings VBR Quality?

    The pulldown options are: lowest, low, medium low, medium, medium high, high, highest What do the options of VBR Quality translate to? How do they relate to LAME Quality settings? Thanks in advance...

  • Not correct import of CS4 3D PhotoShop files into CS5.5

    On the default, when I open 3D PhotoShop file (created in CS4) The Environment texture of 3D object (created in CS4) has scale equal ZERO (instead 1, as it was in CS4). How it can be solved? Thanks.

  • Subquery in ODI

    Hello, i need an information ... situation: i need the NVL ( ..., ....) function. in the developer it is no problem to test the subquery, but in ODI i think, it's al little bit more complicated. NVL( <value from my table>, <subquery> ) at the moment