Capturing JPanel graphics

I am trying to capture the graphics of a JPanel and write it to JPEG. I have had success when I add the JPanel to a JFrame, create a BufferedImage, get a Graphics object from the BufferedImage, and then call the JPanel's paint/print. However, when the resolution of the screen is smaller than the size of the JPanel, I get nothing in the extra space when I use paint, and I get the strange effect of some of the leftmost components redrawn in the extra area on the right. If the resolution becomes larger than the panel, it works just fine.
Changing the resolution is not a resonable solution for this application. How can I get around the size limitations of the JFrame to capture the whole contents of the JPanel?

The approach suggested by Deudeu should work -- all you have to do is change the button used int he example to your panel. The important line in the posted code is:
BufferedImage im = new BufferedImage(button.getWidth(), button.getHeight(), BufferedImage.TYPE_INT_RGB );
Notice how the buffered image is created with the size of the button (which should be the size of your panel regardless of whether it is larger than the physical screen).
If you haven't already given it a try, try it!
;o)
V.V.

Similar Messages

  • Dynamic JPanel graphics within a JFame

    Dear Forum,
    I have a class which extends JFrame. It calls two classes that each extend JPanel with paintComponent() overriden so that I can draw 2D graphics in each. The first JPanel class is a static arrangement of shapes. This class and the class that extends JFrame also implement a MouseListener so that when a MouseEvent occurs within the first JPanel class, it causes the second JPanel class to redraw in graphics. That's the hope.
    I am able to do everything but get the second JPanel class to change (i.e. I can get a print statement to verify that my MouseEvent is creating the proper data structure in the JFrame class). However, I cannot figure a way around having the either JPanel class called statically.
    Can this be done? It sounds simple enough. Rather than ask you all for code. Does anyone know the general approach to this problem?
    Thanks,
    Dan

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Relay
        GeneralPanel generalPanel;
        DetailPanel detailPanel;
        int[][] data =
            { 60,  60, 60, 4 }, { 180, 120, 50, 3 },
            { 60, 300, 45, 7 }, { 165, 240, 60, 5 }
        private JPanel getContent()
            generalPanel = new GeneralPanel(this);
            generalPanel.setData(data);
            PolygonSelector selector = new PolygonSelector(this);
            generalPanel.addMouseListener(selector);
            detailPanel = new DetailPanel();
            JPanel panel = new JPanel(new GridLayout(1,0));
            panel.setOpaque(true);
            panel.add(generalPanel);
            panel.add(detailPanel);
            return panel;
        public void showDetails(Polygon p)
            detailPanel.showDetails(p);
        public static void main(String[] args)
            Relay relay = new Relay();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(relay.getContent());
            f.setSize(500,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class GeneralPanel extends JPanel
        Relay relay;
        Polygon[] polygons;
        boolean haveSelection;
        public GeneralPanel(Relay relay)
            this.relay = relay;
            polygons = new Polygon[0];
            haveSelection = false;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.blue);
            for(int j = 0; j < polygons.length; j++)
                g2.draw(polygons[j]);
        public void setData(int[][] data)
            polygons = new Polygon[data.length];
            for(int j = 0; j < data.length; j++)
                int[][] xy = generateShapeArrays(data[j]);
                polygons[j] = new Polygon(xy[0], xy[1], data[j][3]);
            repaint();
        private int[][] generateShapeArrays(int[] data)
            int cx = data[0];
            int cy = data[1];
            int R = data[2];
            int sides = data[3];
            int radInc = 0;
            if(sides % 2 == 0)
                radInc = 1;
            int[] x = new int[sides];
            int[] y = new int[sides];
            for(int i = 0; i < sides; i++)
                x[i] = cx + (int)(R * Math.sin(radInc*Math.PI/sides));
                y[i] = cy - (int)(R * Math.cos(radInc*Math.PI/sides));
                radInc += 2;
            // keep base of triangle level
            if(sides == 3)
                y[2] = y[1];
            return new int[][] { x, y };
    class DetailPanel extends JPanel
        String x;
        String y;
        Dimension size;
        String sides;
        boolean haveSelection;
        final int HPAD = 20;
        final int VPAD = 10;
        public DetailPanel()
            setBorder(BorderFactory.createLoweredBevelBorder());
            haveSelection = false;
        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();
            Font font = g2.getFont().deriveFont(16f);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            String header = "Polygon Details";
            float width = (float)font.getStringBounds(header, frc).getWidth();
            LineMetrics lm = font.getLineMetrics(header, frc);
            float sx = (w - width)/2;
            float sy = VPAD + lm.getAscent();
            g2.drawString(header, sx, sy);
            if(haveSelection)
                String dim = String.valueOf(size.width) + ", " + size.height;
                String[] s =
                    "x = " + x, "y = " + y, "size = " + dim, "sides = " + sides
                sx = HPAD;
                for(int j = 0; j < s.length; j++)
                    sy += font.getLineMetrics(s[j], frc).getHeight();
                    g2.drawString(s[j], sx, sy);
        public void showDetails(Polygon p)
            if(p == null)
                haveSelection = false;
            else
                Rectangle r = p.getBounds();
                size = r.getSize();
                Point loc = r.getLocation();
                x = String.valueOf(loc.x);
                y = String.valueOf(loc.y);
                sides = String.valueOf(p.npoints);
                haveSelection = true;
            repaint();
    class PolygonSelector extends MouseAdapter
        Relay relay;
        public PolygonSelector(Relay relay)
            this.relay = relay;
        public void mouseClicked(MouseEvent e)
            GeneralPanel generalPanel = (GeneralPanel)e.getSource();
            Point p = e.getPoint();
            Polygon[] polygons = generalPanel.polygons;
            Polygon polygon = null;
            for(int j = 0; j < polygons.length; j++)
                if(polygons[j].contains(p))
                    polygon = polygons[j];
                    break;
            relay.showDetails(polygon);
    }

  • Help with Capturing Business Graphics data point

    Hi,
    I created a BusinessGraphics UI element with SimpleSeries and assigned eventId for the categories and data points. I am able to get the series that is clicked through the event but I would like to know which point (value) is clicked as well.
    The steps I followed are
    1. Created BG UI element, category and SimpleSeries
    2. Assigned eventIDs
    3. Created an action class and mapped it to the UI element
    4. Code in wdDoModifyView is
         if (firstTime)
           IWDBusinessGraphics chart = (IWDBusinessGraphics) view.getElement("bgCSB");
           chart.mappingOfOnAction().addSourceMapping("id", "pointID");
    5. Implemented action class with one parameter (pointID) and able to get the value.
    Can someone help me to get the data point values from the user click.
    Appreciate your help.
    Thanks,
    Kalyan

    You have done everything right, except I don't think you can do this with simple series.
    Create something like this:
    in the context:
    series-> (this node can be with 1..1 cardinality and 1..1 selection)
       points->
           label (string)
           value (int)
           pointId (string)
    in the business graphics:
    create one series (not simple one) and add to it one point of numeric type.
    in the properties of business graphics bind seriesSource to series context.
    Series: bined poitSource to series.points
    Series_points: bind eventId to series.points.pointId
                            bind label to series.points.label
                            bind valueSource to series.points
    Values (these are the numeric values): bind value to series.points.value
    in wdDoModify method do the same thing as you have done already.
    Now, when you click on a point you will receive in your event in pointId variable the pointId context attribute value.
    Best regards,
    Anton

  • Problem with Graphics and JPanel...

    I would like to draw a rectangle on a JPanel. Here is my code:
    JPanel panel = new JPanel();
    Graphics g = panel.getGraphics();
    g.drawRect(20,20,20,20);
    When I run my program, I have a NullPointerException...
    Do you any suggestions to fix the problem??
    thanks
    Pete

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class pete extends JFrame {
      public pete() {
        JPanel panel = new JPanel() {
          public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int midx = getSize().width / 2;
            int midy = getSize().height / 2;
            g2.draw(new Rectangle2D.Double(midx/2, midy/2, midx, midy));
        getContentPane().add(panel, "Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,300);
        setLocation(300,100);
        setVisible(true);
      public static void main(String[] args) {
        new pete();
    }

  • How to capture graphical outputs from other programs

    Does anyone know how we capture the graphical outputs from the other programs and show them
    on the swing?
    I'd like to use a java program to run gnuplot, capture the outputs, and show them using swing.

    Depends on what you mean by "graphic outputs".
    Taking a quick glance at the gnuplot homepage, it looks as if you can output to PNG files, so just run the app, and load the png file.

  • How capture entire JTextPane graphics ?

    Hello i have JTextPane ,     
    I would want to capture the entire graphics and to transform to image.
    the problem that I would want to capture all the portion that scrollable .
    i have this metod but capture visible graphics.
    Component comp = myTextPane;
    int w = comp.getWidth();
    int h = comp.getHeight();
    BufferedImage image = comp.getGraphicsConfiguration().createCompatibleImage(w, h);
    Graphics2D g = image.createGraphics();
    comp.paint(g);
    g.dispose();
    i need method for capture all entire graphics.
    Thanks

    I have resolved my problem, works good .
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ScreenImage
    public void ScreenImage()
    * Create a BufferedImage for Swing components.
    * The entire component will be captured to an image.
    * @param     component Swing component to create image from
    * @param     fileName name of file to be created or null
    * @return     image the image for the given region
    * @exception IOException if an error occurs during writing
    public static BufferedImage createImage(JComponent component, String fileName)
    throws IOException
    Dimension d = component.getSize();
    if (d.width == 0)
    d = component.getPreferredSize();
    component.setSize( d );
    Rectangle region = new Rectangle(0, 0, d.width, d.height);
    return ScreenImage.createImage(component, region, fileName);
    * Create a BufferedImage for Swing components.
    * All or part of the component can be captured to an image.
    * @param     component Swing component to create image from
    * @param     region The region of the component to be captured to an image
    * @param     fileName name of file to be created or null
    * @return     image the image for the given region
    * @exception IOException if an error occurs during writing
    public static BufferedImage createImage(JComponent component, Rectangle region, String fileName)
    throws IOException
    boolean opaqueValue = component.isOpaque();
    component.setOpaque( true );
    BufferedImage image = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = image.createGraphics();
    g2d.setClip( region );
    component.paint( g2d );
    g2d.dispose();
    component.setOpaque( opaqueValue );
    ScreenImage.writeImage(image, fileName);
    return image;
    * Create a BufferedImage for AWT components.
    * @param     component AWT component to create image from
    * @param     fileName name of file to be created or null
    * @return     image the image for the given region
    * @exception AWTException see Robot class constructors
    * @exception IOException if an error occurs during writing
    public static BufferedImage createImage(Component component, String fileName)
    throws AWTException, IOException
    Point p = new Point(0, 0);
    SwingUtilities.convertPointToScreen(p, component);
    Rectangle region = component.getBounds();
    region.x = p.x;
    region.y = p.y;
    return ScreenImage.createImage(region, fileName);
    * Convenience method to create a BufferedImage of the desktop
    * @param     fileName name of file to be created or null
    * @return     image the image for the given region
    * @exception AWTException see Robot class constructors
    * @exception IOException if an error occurs during writing
    public static BufferedImage createDesktopImage(String fileName)
    throws AWTException, IOException
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle region = new Rectangle(0, 0, d.width, d.height);
    return ScreenImage.createImage(region, fileName);
    * Create a BufferedImage from a rectangular region on the screen.
    * @param     region region on the screen to create image from
    * @param     fileName name of file to be created or null
    * @return     image the image for the given region
    * @exception AWTException see Robot class constructors
    * @exception IOException if an error occurs during writing
    public static BufferedImage createImage(Rectangle region, String fileName)
    throws AWTException, IOException
    BufferedImage image = new Robot().createScreenCapture( region );
    ScreenImage.writeImage(image, fileName);
    return image;
    * Write a BufferedImage to a File.
    * @param     image image to be written
    * @param     fileName name of file to be created
    * @exception IOException if an error occurs during writing
    public static void writeImage(BufferedImage image, String fileName)
    throws IOException
    if (fileName == null) return;
    int offset = fileName.lastIndexOf( "." );
    String type = offset == -1 ? "jpg" : fileName.substring(offset + 1);
    ImageIO.write(image, type, new File( fileName ));
    public static void main(String args[])
    throws Exception
    final JFrame frame = new JFrame();
    // final JTextArea textArea = new JTextArea(30, 60);
    final JTextPane textArea = new JTextPane();
    final JScrollPane scrollPane = new JScrollPane( textArea );
    frame.getContentPane().add( scrollPane );
    textArea.setPage ("FILE:C:\\Java_(linguaggio).htm");
    JMenuBar menuBar = new JMenuBar();
    frame.setJMenuBar( menuBar );
    JMenu menu = new JMenu( "File" );
    ScreenImage.createImage(menu, "menu.jpg");
    menuBar.add( menu );
    JMenuItem menuItem = new JMenuItem( "Frame Image" );
    menu.add( menuItem );
    menuItem.addActionListener( new ActionListener()
    public void actionPerformed(ActionEvent e)
    // Let the menu close and repaint itself before taking the image
    new Thread()
    public void run()
    try
    Thread.sleep(50);
    System.out.println("Creating frame.jpg");
    frame.repaint();
    ScreenImage.createImage(frame, "frame.jpg");
    catch(Exception exc) { System.out.println(exc); }
    }.start();
    final JButton button = new JButton("Create Images");
    button.addActionListener( new ActionListener()
    public void actionPerformed(ActionEvent e)
    try
    System.out.println("Creating desktop.jpg");
    ScreenImage.createDesktopImage( "desktop.jpg" );
    System.out.println("Creating frame.jpg");
    ScreenImage.createImage(frame, "frame.jpg");
    System.out.println("Creating scrollpane.jpg");
    ScreenImage.createImage(scrollPane, "scrollpane.jpg");
    System.out.println("Creating textarea.jpg");
    ScreenImage.createImage(textArea, "textarea.jpg");
    System.out.println("Creating button.jpg");
    ScreenImage.createImage(button, "button.jpg");
    button.setText("button refreshed");
    button.paintImmediately(button.getBounds());
    System.out.println("Creating refresh.jpg");
    ScreenImage.createImage(button, "refresh.jpg");
    System.out.println("Creating region.jpg");
    Rectangle r = new Rectangle(0, 0, 100, 16);
    ScreenImage.createImage(textArea, r, "region.png");
    catch(Exception exc) { System.out.println(exc); }
    frame.getContentPane().add(button, BorderLayout.SOUTH);
    try
    FileReader fr = new FileReader( "ScreenImage.java" );
    BufferedReader br = new BufferedReader(fr);
    textArea.read( br, null );
    br.close();
    catch(Exception e) {}
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo( null );
    frame.setVisible(true);
    }

  • Need help making ball move and bounce off of sides of JPanel

    I'm currently working on a program that creates a ball of random color. I'm trying to make the ball move around the JPanel it is contained in and if it hits a wall it should bounce off of it. I have been able to draw the ball and make it fill with a random color. However, I cannot get it to move around and bounce off the walls. Below is the code for the class that creates the ball. Should I possible be using multithreads? As part of the project requirements I will need to utilizes threads and include a runnable. However, I wanted to get it working with one first and than add to it as the final product needs to include new balls being added with each mouse click. Any help would be appreciated.
    Thanks
    import java.awt.Color;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    public class Ball extends JPanel{
        Graphics g;
        int rval; // red color value
        int gval; // green color value
        int bval; // blue color value
        private int x = 1;
        private int y = 1;
        private int dx = 2;
        private int dy = 2;
        public void paintComponent(Graphics g){
            for(int counter = 0; counter < 100; counter++){
                // randomly chooses red, green and blue values changing color of ball each time
                rval = (int)Math.floor(Math.random() * 256);
                gval = (int)Math.floor(Math.random() * 256);
                bval = (int)Math.floor(Math.random() * 256);
                super.paintComponent(g);
                g.drawOval(0,0,30,30);   // draws circle
                g.setColor(new Color(rval,gval,bval)); // takes random numbers from above and creates RGB color value to be displayed
                g.fillOval(x,y,30,30); // adds color to circle
                move(g);
        } // end paintComponent
        public void move(Graphics g){
            g.fillOval(x, y, 30, 30);
            x += dx;
            y += dy;
            if(x < 0){
                x = 0;
                dx = -dx;
            if (x + 30 >= 400) {
                x = 400 - 30;
                dx = -dx;
            if (y < 0) {
                y = 0;
                dy = -dy;
            if (y + 30 >= 400) {
                y = 400 - 30;
                dy = -dy;
            g.fillOval(x, y, 30, 30);
            g.dispose();
    } // end Ball class

    Create a bounding box using the size of the panel. Each time you move the ball, check that it's still inside the box. If it isn't, then change it's direction. You know where the ball is, (x, y), so just compare those values to the boundary values.

  • Width Wrong for Imported Graphics in Frame 9

    Has anyone else had issues with Framemaker detecting the wrong width when importing graphics?  As an example, when I import a JPG of a button that should be 21 x 21 pixels, Framemaker displays the width as 24px and the height as 21px.  This results in a smashed graphic.  If I adjust the dimensions of the graphic in FrameMaker to the correct dimensions, then print the PDF, the right border of the image is off.
    I have tried capturing the graphic a variety of different ways, and I always experience the same results.  I can import the graphic into Captivate or Word and the sizing is correct.  Any ideas?  Thanks!
    I am using FrameMaker version 9.0p237 as part of the Technical Communication Suite 2.

    I just tested this with a sample file at the 21x21 dimensions, and you are absolutely correct. FM9 screws up the dimensions (and default dpi resolution) for PNG and GIF files. I also tried BMP and TIF equivalents and these were ok. FM8 does not have this problem, so it looks like Adobe played with the PNG and GIF filters a bit (perhaps to get rid of all of the extra colours coming in).
    For a JPG or PNG import of a 21x21 at 96dpi, FM9 seems to think that it is 24x21 at 110dpi. FM8 gets it right.
    For a GIF import of the same, FM9 thinks it is 22x21 at 75dpi. FM8 got it right.
    What's also strange is that if the dimensions are both even, e.g. 20x20 at 96dpi, then FM9 gets it right for the JPG, PNG and GIF. However, if the *first* dimension is odd, e.g. 21x20 it gets it wrong again as before, but if the second dimesion is odd, e.g. 20x21, the it gets it right. VERY WIERD!
    It's definitely a BUG.
    I would suggest that you either use BMP or TIF for now OR try to increase your icons by 1 pixel to make them an even size, e.g. 22x22.
    I'd also recommend that you not use JPG for these, but rather GIF or PNG, because you may generate some unwanted artifacts in the JPG due to the lossy compression used.

  • Dynamic image loading in a JPanel

    Hi,
    I've created a JFrame which includes a JPanel and would like to dynamically add images to the JPanel (for a space invaders game). I've been getting the JPanel graphics object casting to Graphics2D and then passing it to the Actor class constructor where the sprite is loaded as a BufferedImage and then called drawImage on the Graphics object but the sprite does not display. It's been suggested that I need to use a new JPanel for every sprite that gets loaded, but this would seem to be less efficient.
    public class NewJFrame extends javax.swing.JFrame {
        public static NewJFrame root;
        public NewJFrame() {
            initComponents();
            root = this;
           Graphics2D g = (Graphics2D) jPanel1.getGraphics(); 
           new Actor(g);
    public class Actor {
        public Actor(Graphics g){
            try {
            BufferedImage sprite = ImageIO.read(new File("/Users/administrator/Desktop/image.jpg"));
            g.drawImage(sprite, 0, 0, null);
            } catch (IOException e) { System.out.println(e);}
        }Thanks

    The problem with doing it this way if I understand correctly is that if I overload the paintComponent method of the panel I'm trying to draw on this will be static i.e. you can't pass parameters (such as a the url of the graphic to load or number of graphics to load) to the paintComponent method (it only accept Graphics g as a parameter). In other words the panel can only be drawn on once.

  • Cant do setColor(Color.BLACK); to a graphic object inside a class

    i have a graphic object inside a class:
    JPanel panel = new JPanel();
    Graphic lienzo = areadibujo.getGraphic();
    and then i cant do this:
    lienzo.setColor(Color.BLACK);
    netbeans error:
    <identifier> expected
    i just can do that inside a method from the class...

    HI i found the problem.
    The problem is that when i create the graphic object i do this:
    Graphics lienzo = areadibujo.getGraphics();
    areadibujo.getGraphics(); returns null so when i try to do something like lienzo.drawline(1,1,200,200); it just says nullpointer error, i guess at the time i create graphic object the panel "areadibujo" is not still created because the frame doesnt still shows, i can correct this by copying Graphics lienzo = areadibujo.getGraphics(); inside a actionperfmoded or other event method , but i dont wanna do that, where does the panel object already is created in constructor?.... i dont know if i explain my self well or how can i force areadibujo.getGraphics() to return something...

  • How can I capture then convert to BMP a screendump from a device in Epson ESC/P printer format?

    I am using a Tektronix VM700 which can only output a screendump by "printing" to the serial port. I want to capture this data (of variable length) then convert it to BMP. Has anyone done this before or has an Epson-format-to-BMP routine?

    Hi Simon,
    Try this and see if it works. I don't know if there are different Epson formats. This VI handles monochrome pics only.
    I had the same problem when a thermal printer died, and I decided to capture the "graphics" per PC instead of on paper. I've been using it for my purposes for years. Dunno if it'll work for you, but you can try it and see. I think my printer worked with ESC/K, but maybe it'll give you a start at least.
    Shane.
    Using LV 6.1 and 8.2.1 on W2k (SP4) and WXP (SP2)
    Attachments:
    EPS_string_to_graphm_faster.llb ‏61 KB

  • How to save a graphic composition

    I have a JPanel where several swing components are added. I'd like to apply some transformations to the resulting composition.So I'd like to save it before applying transformations in order to recover the original composed image every time I want to transform it.
    How should this be achieved ?
    Could I get an image from the jPanel Graphics context ?
    Any hint ?
    Thanks in advance. Jose Gonz�lez.

    do you mean affine transformations?
    AffineTransformation af = aGraphics2D.getTransform()
    //do here your transforms
    //reset to the original
    aGraphics2D.setTransform(af)

  • Read .txt file of numbers and draw

    Hello.
    I am trying to utlize BufferedReader and g.drawline to read numbers from a text file and output to the screen as a "line".
    I know I still need a while loop and some error checking, but, am having trouble finishing the more 'basic' portion of the code.
    The GUI class is already taken care of. I am just trying to open the file, read, turn to int, produce lines, then close file.
    I have commented out some of the code that was provided with the assignment.
    Any help would be appreciated.
    Thank you.
    import javax.swing.*;
    import java.awt.*;
    * DrawingPanel creates a panel used for drawing
    * a map
    * Numbers stored in text file, usa.txt.
    * one number per line.  Read each number
    * create a map on screen. GUI provided in a
    * 2nd class.
    public class DrawingPanel extends JPanel {
         /** Graphics object used for drawing on the panel */                           
         private Graphics g;                  
         /** Tells if it is time to draw */
         private boolean timeToDrawPath;
         /** The filename of the hurricane path */
                                  //private String pathFile; 
         private String usa.txt;
         * Creates a new, white DrawingPanel for drawing the maps
         public DrawingPanel() {
              setBackground(Color.white);
              this.timeToDrawPath = false;
                                  //this.pathFile = null;
              this.usa.txt = null;
         * This method is called automatically by Java.  There will NEVER
         * be a direct call to paint() anywhere in the code.  Anytime that we
         * need to update what is drawn on the screen, we call repaint().
         * @param grph The graphics window to paint
         public void paint(Graphics grph) {
              g = grph;
              super.paint(g);
              processUSA();
              if (timeToDrawPath){
                   drawPath();
         * Reads the USA coastline coordinates from a file and draws the path
         * to the panel
         public void processUSA( ) {
                        //just an example of how to draw a single
                        //line segment from (50,50) to (200,200)
                        //g.drawLine( 300, 50, 200, 200);
         //Insert the while loop here??
         //Include the parse.Int statement
         //Open the file
         String inFile = ("usa.txt");
         FileReader fileReader = new FileReader (inFile);
                   //BufferedReader bufReader = newBufferedReader (fileReader);
         BufferedReader bufReader=newBufferedReader (new fileReader ("usa.txt"));
                        //Insert beginning of while loop here????
         //read data from the file
         String str=bufReader.readLine();
         g.drawLine(x1,y1,x2,y2);
         }

    Yep, you are right in deciding the positioning of the while loop.
    But the folly you are committing is while creating object of BufferedReader ... It is to be created by passing to the constructor, the reference of the FileReader object you have created.
    so the line of code shud look like ...
    BufferedReader bufReader = new BufferedReader(FileReaderObject);
    And then you can go ahead with readLine() as per your requirement in the while loop.

  • Having a problem with image IO and drawing image

    My question did not come out on the other posting. I am getting them image from a JPanel. I then convert the image into a renderedimage. Use the ImageIO.write method to convert to png format. I don't want to save the image on the local disk so it is writted to a ByteArrayOutputStream. I get the bytes from this and insert this into a blob field type.
    Then to paint the image onto the JPanel I try two methods to paint it on to the JPanel. I set the JPanel to be the width and size of the image. But I am getting a null pointer exception and I can't figure out why. If anyone could give me any suggestions I would really appreciate it.
    rImage = convertToRenderedImage(draw.drawPanel.offScreen, width11, drawPanelHeight, type);
    try{
    bo = new ByteArrayOutputStream();
    ImageIO.write(rImage, "png", bo);
    imageBytes = bo.toByteArray();
    }catch(IOException iox3)
    System.err.println(iox3);
    PreparedStatement statement12 = connection.prepareStatement(
    "INSERT INTO feed VALUES(?,?,?,?,?,?);");
    statement12.setBytes(2, imageBytes);
    icon = new ImageIcon(rs.getBytes("file"));
    image = icon.getImage();
    //base is the JPanel
    Graphics g2d = base.getGraphics();
    bytes = rs.getBytes("file");
    bInput = new ByteArrayInputStream(bytes);
    try
    bImage = ImageIO.read(bInput);
    catch(IOException e21)
    System.out.println("Error in imageIO transformation");
    //image is Image and bimage is bufferedimage
    image = bImage;
    Graphics g2d = base.getGraphics();
    g2d.drawImage(image, 0, 0, base);
    g2d.drawImage(image, 0, 0, base);

    Would it be possible for you to send out a small runnable testcase that I could try out with?
    Thanks,
    Kannan

  • JLabel in Rules class won't display

    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import Graphics.DrawFrame;
    public class Caller { //driver class
         public static void main(String[] args) { //main method
              int width = 350; //sets width to 350 pixels
              int height = 150; //sets height to 150 pixels
              Toolkit toolkit = Toolkit.getDefaultToolkit(); //creates a Toolkit object
              Dimension dim = toolkit.getScreenSize(); //creates a Dimension object and stores the screen size
              do {
                   //DrawFrame.setDefaultLookAndFeelDecorated(true); //decorates the look and feel
                   DrawFrame frame = new DrawFrame((dim.width-width)/2, (dim.height-height)/2, width, height, "How to Play"); //creates an instance of DrawFrame and sets it in the center of the screen with a height of 300 and a width of 300
                   JButton rules = new JButton("Play"); //creates a newJButton with the text "play"
                   JLabel label = new JLabel("<html>Press ENTER to call a new number.<br>Press R to reset game.<br> The game resets if all 75 numbers have been called.<br> Press H to see this screen again.<br> Click the button or press ENTER to start.", SwingConstants.CENTER); //creates a JLabel that explains the game and centers it in the frame
                   frame.panel.add(label); //adds the label to the frame
                   label.setOpaque(true); //sets the label as opaque
                   label.setVisible(true); //makes the label visible
                   frame.panel.add(rules); //adds the button to the frame
                   rules.setOpaque(true); //sets the button to opaque
                   rules.setVisible(true); //makes the button visible
                   ButtonListener button = new ButtonListener(); //creates instance of ButtonListener class
                   rules.addActionListener(button); //adds an Action Listener to the button
                   frame.getRootPane().setDefaultButton(rules); //sets button as default button (clicks button when user hits ENTER
                   frame.setVisible(true);
                   while (button.source != rules) {//loops if the source of the ActionEvent wasn't the button
                        label.repaint(); //repaints the label
                        rules.repaint(); //repaints the button
                   frame.dispose(); //deletes the frame when the button is clicked
                   Bingo.bingoCaller(); //calls the method in the bingo class
              } while(true); //loops indefinitely
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class ButtonListener implements ActionListener { //class implements ActionListener interface
              public Object source; //creates an object of type Object
              public void actionPerformed(ActionEvent e) { //actionPerformed method that has an ActionEvent ofject as an argument
                   source = e.getSource(); //sets the source of the ActionEvent to source
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import Graphics.*;
    public class Bingo {
         static Ball balls[][] = new Ball[5][15]; //creates a 2D 5 by 15 array
         public static void bingoCaller() {
              //DrawFrame.setDefaultLookAndFeelDecorated(true); //decorates the look and feel
              int width = 1250; //sets width to 1250 pixels
              int height = 500; //sets height to 500 pixels
              Toolkit toolkit = Toolkit.getDefaultToolkit(); //creates a Toolkit object
              Dimension dim = toolkit.getScreenSize(); //creates a Dimension object and sets the it as the screen size
              DrawFrame frame = new DrawFrame((dim.width-width)/2, (dim.height-height)/2, width, height, "Automated BINGO Caller"); //creates instance of DrawFrame that is 1250 pixel wide and 500 pixels high at the center of the screen
              Graphics g = frame.getGraphicsEnvironment(); //calls the getGraphicsEnvironment method in the DrawFrame class
              Keys key = new Keys(); //creates instance of the Keys class
              frame.addKeyListener(key); //adds a KeyListener called Key
              for (int x = 0; x < 5; x++) { //fills rows
                   for (int y = 0; y < 15; y++) { //fills columns
                        balls[x][y] = new Ball(x, y+1); //fills array
              frame.pack(); //adjusts the size of the frame so everything fits
              g.setColor(Color.black); //sets the font color of the letters to black
              g.setFont(new Font("MonoSpace", Font.BOLD, 50)); //creates new font
              for(int y=0;y<balls.length;y++){ //draws all possible balls
                   g.drawString(balls[y][0].s, 0, y*100+50); //draws numbers
                   for(int x=0;x<balls[y].length;x++){ //draws all possible balls
                        g.drawString(Integer.toString(balls[y][x].i), (x+1)*75, y*100+50); //draws letters
              frame.repaint(); //repaints numbers
              do {
                   int x, y; //sets variables x and y as integers
                   int count = 0; //sets a count for the number of balls called
                   boolean exit; //sets a boolean to the exit variable
                   do {
                        exit = false; //exit is set to false
                        x = (int)(Math.random() * 5); //picks a random number between 0 and 4 and stores it as x
                        y = (int)(Math.random() * 15); //picks a random number between 0 and 14 stores it as y
                        if (!balls[x][y].called) { //checks to see if a value is called
                             exit = true; //changes exit to true if it wasn't called
                             balls[x][y].called = true; //sets called in the Ball class to true if it wasn't called
                   } while (!exit&&count<5*15); //if exit is false, and count is less than 75returns to top of loop
                   for(int z=0;z<balls.length;z++){ //looks at balls
                        g.setColor(Color.black); //displays in black
                        g.drawString(balls[z][0].s, 0, z*100+50); //draws balls as a string
                        for(int a=0;a<balls[z].length;a++){ //looks at all balls
                             if (balls[z][a].called){ //if a ball is called
                                  g.setColor(Color.red); //change color to red
                                  count++; //increments count
                             } else {
                                  g.setColor(Color.white); //if it isn't called stay white
                             g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //draws balls as string
                   boolean next=false; //initiates boolean value next and sets it to false
                   frame.repaint(); //repaints the balls when one is called
                   while(!next) {
                        try {
                             Thread.sleep(100); //pauses the thread for 0.1 seconds so it can register the key pressed
                        } catch (InterruptedException e) {
                             e.printStackTrace(); //if it is interrupted it throws an exception and it is caught and the stack trace is printed
                        if(key.keyPressed==KeyEvent.VK_ENTER){ //if Enter is pressed
                             next=true; //next is set to true
                             key.keyPressed=0; //keypressed value is reset to 0
                        }else if (key.keyPressed == KeyEvent.VK_H) {
                             new Rules();
                             key.keyPressed = 0;
                        } else if (key.keyPressed == KeyEvent.VK_R) { //if R is pressed
                             key.keyPressed=0; //keypressed is reset to 0
                             next=true; //next is set to true
                             count=5*15; //changes count to 5*15
                             for(int z=0;z<balls.length;z++){ //recreates rows
                                  g.setColor(Color.white); //sets color to white
                                  g.drawString(balls[z][0].s, 0, z*100+50); //redraws rows
                                  for(int a=0;a<balls[z].length;a++){ //recreates columns
                                       balls[z][a] = new Ball(z, a+1); //fills array
                                       g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //redraws columns
                   if (count==5*15) { //if count = 5*15
                        for(int z=0;z<balls.length;z++){ //recreates rows
                             g.setColor(Color.white); //sets color to white
                             g.drawString(balls[z][0].s, 0, z*100+50); //redraws rows
                             for(int a=0;a<balls[z].length;a++){ //recreates columns
                                  balls[z][a] = new Ball(z, a+1); //fills array
                                  g.drawString(Integer.toString(balls[z][a].i), (a+1)*75, z*100+50); //redraws columns
              } while (true); //infinite loop only terminates program when the close button is clicked
    package Graphics;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    public class DrawFrame extends JFrame{
         public Panel panel; //creates a variable called panel of type Panel
         public DrawFrame(int width, int height, String s) { //constructor for size and title
              super(s); //gets s from class that calls it
              this.setBounds(0, 0, width, height); //sets size of component
              initial(); //calls method initial
         public DrawFrame(int x, int y, int width, int height, String s) { //second constructor for size, title, and where on the screen it appears
              super(s); //gets title from the class that calls it
              this.setBounds(x, y, width, height);     //sets size of component     
              initial(); //calls method initial
         void initial() {
              this.setResizable(false); //disables resizing of window
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //terminates program if close button is pressed
              this.setPreferredSize(getSize()); //gets the size and set the preferred size
              panel = this.getPanel(); //gets the an instance of the Panel class and store the reference in panel
              this.getContentPane().add(panel); //adds panel to the frame
              this.setVisible(true); //makes the frame visible
              panel.init(); //calls the init method form the Panel class
         public Graphics getGraphicsEnvironment(){ //return type of Panel for method getGraphicsEnvironment
              return panel.getGraphicsEnvironment(); //returns the GraphicsEnvironment from class Panel
         Panel getPanel(){ //method getPanel with return type of Panel
              return new Panel(); //returns a new instance of the Panel class
    package Graphics;
    import java.awt.Graphics;
    import javax.swing.JFrame;
    public class DrawFrame2 extends JFrame{
         public Panel panel; //creates a variable called panel of type Panel
         public DrawFrame2(int width, int height, String s) { //constructor for size and title
              super(s); //gets s from class that calls it
              this.setBounds(0, 0, width, height); //sets size of component
              initial(); //calls method initial
         public DrawFrame2(int x, int y, int width, int height, String s) { //second constructor for size, title, and where on the screen it appears
              super(s); //gets title from the class that calls it
              this.setBounds(x, y, width, height);     //sets size of component     
              initial(); //calls method initial
         void initial() {
              this.setResizable(false); //disables resizing of window
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //terminates program if close button is pressed
              this.setPreferredSize(getSize()); //gets the size and set the preferred size
              panel = this.getPanel(); //gets the an instance of the Panel class and store the reference in panel
              this.getContentPane().add(panel); //adds panel to the frame
              this.setVisible(true); //makes the frame visible
              panel.init(); //calls the init method form the Panel class
         public Graphics getGraphicsEnvironment(){ //return type of Panel for method getGraphicsEnvironment
              return panel.getGraphicsEnvironment(); //returns the GraphicsEnvironment from class Panel
         Panel getPanel(){ //method getPanel with return type of Panel
              return new Panel(); //returns a new instance of the Panel class
    package Graphics;
    import javax.swing.JPanel;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Image;
    public class Panel extends JPanel{
         Graphics g; //initiates variable g as type Graphics
         Image image; //initiates variable image as type Image
         public void init() {
              image = this.createImage(this.getWidth(), this.getHeight()); //creates the image with the specified height and stores it as image
              g = image.getGraphics(); //uses the getGraphics method from the Image class and stores it as g
              g.setColor(Color.white); //sets the color of g to white
              g.fillRect(0, 0, this.getWidth(), this.getHeight()); //fills the rectangle
         Graphics getGraphicsEnvironment() { //method getGraphicsEnvironment with return type Graphics
              return g; //returns g
         public void paint(Graphics graph) { //overrides the paint method and passes the argument graph of type Graphics
              if (graph == null) //if there is nothing in graph
                   return; //return
              if (image == null) { //if there is nothing in image
                   return; //return
              graph.drawImage(image, 0, 0, this); //draws the image
    package Graphics;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    public class Keys extends KeyAdapter{
    public int keyPressed; //creates a variable keyPressed that stores an integer
    public void keyPressed(KeyEvent e) { //creates a KeyEvent from a KeyListner
              keyPressed = e.getKeyCode(); //gets the key from the keyboard
    public class Ball {
         String s; //initiates s that can store data type String
         int i; //initiates i that can store data as type integer
         boolean called = false; //initiates called as a boolean value and sets it to false
         public Ball(int x, int y) {
              i = (x * 15) + y; //stores number as i to be passed to be printed
              switch (x) { //based on x value chooses letter
              case 0: //if x is 0
                   s = "B"; //sets s to B
                   break; //breaks out of switch case
              case 1: //if x is 1
                   s = "I"; //sets s to I
                   break; //breaks out of switch case
              case 2: //if x is 2
                   s = "N"; //sets s to N
                   break; //breaks out of switch case
              case 3: //if x is 3
                   s = "G"; //sets s to G
                   break; //breaks out of switch case
              case 4: //if x is 4
                   s = "O"; //sets s to O
         public String toString() { //overrides toString method, converts answer to String
              return s + " " + i; //returns to class bingo s and i
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JLabel;
    import javax.swing.SwingConstants;
    import Graphics.DrawFrame2;
    public class Rules {
         public Rules() {
         int width = 350;
         int height = 150;
         Toolkit toolkit = Toolkit.getDefaultToolkit();
         Dimension dim = toolkit.getScreenSize();
         DrawFrame2 frame = new DrawFrame2((dim.width-width)/2, (dim.height-height)/2, width, height, "How to Play");
         JLabel label = new JLabel("<html>Press ENTER to call a new number.<br> Press R to reset game.<br> The game resets if all 75 numbers have been called.<br> Press H to see this scrern again.", SwingConstants.CENTER);
         frame.panel.add(label);
         label.setOpaque(true);
         label.setVisible(true);
         frame.setVisible(true);
    I created this program to call bingo numbers. When you start the program a small frame appears that tells you how to use the program. When you click the button that frame is disposed and a new one appears that call the numbers. Both of these frames have code in them that will find the dimensions of your screen and put the frames in the center. When you press enter a new number is called by changing the number from white (same color as background) to red. Once all 75 numbers have been called it resets the game. If you press R at anytime during the game the game resets. I had wanted to create a new frame that would display how to play in the middle of the game. It had to be different than the one at the beginning where it doesn't have the button and it isn't in the driver class (class Caller). If you press H at anytime after it starts calling numbers the new frame will be displayed. I have a class (DrawFrame) that extends JFrame but that had the default close operation set to EXIT_ON_CLOSE and I didn't want the program to terminate when the user clicked the x in the how to play frame. I created DrawFrame2 to solve this problem where the only line of code that is different is that the default close operation is DISPOSE_ON_CLOSE. The name of the class I used for the new how to play frame is Rules. The code in this class should work but for some reason the JLabel isn't displaying. Can someone please help me out?

    I just copied the code from class Caller into Rules and reworked it a bit and it worked.

Maybe you are looking for

  • Since I installed Mcafee Cox internet securityI cannot get firefox to open. When I try to remove it and redownload it windows says I need to close firefox

    i have restarted computer and then I can uninstall firefox. when I reinstall it I can open it a few times but then it will not open. I have tried to turn off firewall and reinstall firefox and that did not help. I turn fiewall off and firefox will st

  • I shut my MacBook down and now it won't start (yes it's charged)

    I was typing on my MacBook this morning and hit the esc key a couple of times by accident.  My keyboard stopped working and was only typing . and/. I went to settings to adjust; turned my computer on and off a few times, then shut it down and now it

  • Updated itunes and now NO itunes store!!!

    Hello,Newbie to this forum. Where do I start, I first upgraded itunes software about 1 month ago and after that, unable to burn cd's.keep getting error (4280).So I learned to live with it for the meanwhile.Now I upgraded the software to see if that w

  • ESS Fields Description:

    Hi Experts, I have customized the homepage framework. It is working fine till two days back. Now, whenever I am trying to access a service on portal, the description of each field, each button, and error messages are in non-English. It is happening w

  • SELECT COUNT(*)  bug

    I have a table named comments, with a column labeled book_id. In this column I have non-unique integer values (we'll say 2 rows contain the number 9) import flash.events.*; import flash.data.* import fl.controls.ComboBox; import flash.filesystem.File