BufferedImages and Swing's ScrollablePicture in a JPanel

I'm referring to http://java.sun.com/developer/technicalArticles/Media/imagestrategies/index.html paper.
As I read this excellent paper, I decided to go for the BufferedImage strategy.
But I can't put my BufferedImage into my ScrollablePicture as below:
JPanel picPanel = new JPanel(new GridBagLayout());
//Set up the scroll pane.
picture = new ScrollablePicture(imageIcon_, columnView.getIncrement()); // OK
//picture = new ScrollablePicture(bImg, columnView.getIncrement()); // NOT OK = don't work
...How to bypass the message "java:542: cannot resolve symbol symbol : constructor ScrollablePicture (java.awt.image.BufferedImage,int)"
It is very important as all my code is based on BufferedImage to apply many operations on the image.
? I believe the API does not allow to perform RGB to B&W operation on ImageIcon. ?
Thanks to all.
dimitryous r.

Hi camickr,
Hi all,
I pass trough my SSCCE. Good advice from camickr. But it was not so easy:
Short: not so short
Self contained: believe so
Correct: Java 1.4.2 code
Compilable: yes
I'm back with formatted code.
I'm sure you will fire at me all of you. Anyway if I don't even try, I will never succeed.
//  TooAwoo.java
//  TooAwoo
//     part of this code is from Sun's JavaTutorial 1.4.2
import java.applet.Applet.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.GraphicsEnvironment;
import java.awt.image.*;
import java.lang.*;
import java.lang.String;
import java.lang.Object;
import java.net.URL;
import java.net.MalformedURLException;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.event.MouseInputAdapter;
import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import java.io.FilePermission;
public class TooAwoo extends JApplet implements
                                                            ChangeListener,
                                                            ActionListener,
                                                            ItemListener
     FilePermission p = new FilePermission("<<ALL FILES>>", "read,write");
    public BufferedImage bImg;
     Font newFont = new Font("SansSerif", Font.PLAIN, 10);
     ImageControls RightPanel;
     public static int initOx = 0;
     public static int initOy = 0;
     int init_ww, init_wh, set_x, set_y = 0;
     final int pSP_w = 520; // final width of pictureScrollPane
     final int pSP_h = 650; // final height of pictureScrollPane
     Dimension applet_window; // applet dimensions
     public Image image;
     public ImageIcon imageIcon_;
     public static BufferedImage binull;
     // ScrollablePicture stuff
     public Rule columnView;
    public Rule rowView;
     public JToggleButton isMetric;
    public ScrollablePicture picture;
     public JScrollPane pictureScrollPane;
     public TooAwoo() {
          // nothing here
    public void init() {
          applet_window = getSize();                                                            // read applet dimensions in TooAwoo.html
          init_ww = applet_window.width;
          init_wh = applet_window.height;
          // get the image to use width > 680 (see final int pSP_w above)
          image = getImage(getDocumentBase(), "images/ReallyBig.jpg");
          imageIcon_ = createImageIcon("images/ReallyBig.jpg");
          int iw = imageIcon_.getIconWidth();
          int ih = imageIcon_.getIconHeight();
          bImg = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
          // Panels
          // ImageDisplayPanel
        //Create the row and column headers.
        columnView = new Rule(Rule.HORIZONTAL, true);
        rowView = new Rule(Rule.VERTICAL, true);
        if (imageIcon_ != null) {
            columnView.setPreferredWidth(imageIcon_.getIconWidth());
            rowView.setPreferredHeight(imageIcon_.getIconHeight());
        } else {
            columnView.setPreferredWidth(640);
            rowView.setPreferredHeight(480);
        //Create the upper left corner.
        JPanel buttonCorner = new JPanel();                                                  //use FlowLayout
        isMetric = new JToggleButton("cm", true);
        isMetric.setFont(newFont);
        isMetric.setMargin(new Insets(2,2,2,2));
        isMetric.addItemListener(this);                                                       // !!! not OK = don't work: button is not firing
        buttonCorner.add(isMetric);
          JPanel ImageDisplayPanel = new JPanel(new GridBagLayout());
        //Set up the scroll pane.
          picture = new ScrollablePicture(imageIcon_, columnView.getIncrement());     // either
          //picture = new ScrollablePicture(bImp, columnView.getIncrement());          // or
          // ********** if bImp change the lines in ScrollablePicture.java **********
        Graphics g = bImg.getGraphics();
          g.drawImage(bImg, 0, 0, null);
          JScrollPane pictureScrollPane = new JScrollPane(picture);
        pictureScrollPane.setPreferredSize(new Dimension(pSP_w, pSP_h));
        pictureScrollPane.setViewportBorder(
                BorderFactory.createLineBorder(Color.black));
        pictureScrollPane.setColumnHeaderView(columnView);
        pictureScrollPane.setRowHeaderView(rowView);
          //Set the corners.
        pictureScrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, buttonCorner);
        pictureScrollPane.setCorner(JScrollPane.LOWER_LEFT_CORNER,
                                    new Corner());
        pictureScrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER,
                                    new Corner());
          //set_y++;
          addToGridBag(ImageDisplayPanel,pictureScrollPane, set_x, set_y, 1, 1, 0, 0); // 0,0
          getContentPane().add( BorderLayout.WEST, ImageDisplayPanel);               // where to display the bImg: left
          RightPanel = new ImageControls();                                                  // call the ImageControls class
          RightPanel.setBackground(Color.black);
          getContentPane().add( BorderLayout.EAST, RightPanel);
          //getContentPane().add( BorderLayout.EAST, ToolsPanel);                         // where to display the tools: right
          JPanel GlobalPanel = new JPanel(new GridBagLayout());
          getContentPane().add( BorderLayout.NORTH, GlobalPanel);
     } // end public void init()
     public Graphics2D createGraphics2D(int width,
                                                int height,
                                                BufferedImage bi,
                                                Graphics g) {                                   // called by ImageControls paint
          Graphics2D g2 = null;
          if (bi != null) {
               System.out.println("TooAwoo createGraphics2D: bi != null : " + " w= " + width + " h= " + height);
               g2 = bi.createGraphics();
          } else {
               System.out.println("TooAwoo createGraphics2D: bi == null g2 = (Graphics2D) g");
               g2 = (Graphics2D) g;
          return g2; // return to ImageControls paint
     } // end createGraphics2D
     class ImageControls extends JPanel {
          public void paint(Graphics g) {
               Dimension applet_window = getSize();
               if (bImg == null) {
                    bImg = createBufferedImage(applet_window.width, applet_window.height, 2);
               } else {
                    Graphics2D g2 = createGraphics2D(applet_window.width, applet_window.height, bImg, g);
                    g.drawImage( bImg , initOx , initOy , null );
                    g2.dispose();
                    //toolkit.sync();
               } // end else (bImg != null)
          } // end paint
     } // end ImageControls
     public Dimension setPreferredSize() {
          Dimension applet_window = getSize();
          return applet_window;
     public String getString(String key) {
          return key;
     public BufferedImage createBufferedImage(int w, int h, int imgType) {          // called by ImageControls paint
          BufferedImage bi = null;
          if (imgType == 0) {
               bi = (BufferedImage) getGraphicsConfiguration().createCompatibleImage(w, h);
          } else if (imgType > 0 && imgType < 14) {
               bi = new BufferedImage(w, h, imgType);
          System.out.println("TooAwoo createBufferedImage: imgType= " + imgType + " w= " + w + " h= " + h);
          return bi;
     public static void addToGridBag(JPanel panel, Component comp,
                                             int x, int y, int w, int h, double weightx, double weighty) {
          GridBagLayout gbl = (GridBagLayout) panel.getLayout();
          GridBagConstraints c = new GridBagConstraints();
          c.fill = GridBagConstraints.BOTH;
          c.anchor = GridBagConstraints.WEST;
          c.gridx = x;
          c.gridy = y;
          c.gridwidth = w;
          c.gridheight = h;
          c.weightx = weightx;
          c.weighty = weighty;
          panel.add(comp);
          gbl.setConstraints(comp, c);
     } // end addToGridBag
     protected static ImageIcon createImageIcon(String path) {                         // Returns an ImageIcon, or null if the path was invalid.
          java.net.URL imgURL = TooAwoo.class.getResource(path);
          if (imgURL != null) {
               return new ImageIcon(imgURL);
          } else {
               System.err.println("Couldn't find file: " + path);
               return null;
     } // end createImageIcon
     private static void createAndShowGUI() {                                             // called by main
          JFrame frame = new JFrame("TooAwoo");                                             //Create and set up the window.
          // Make sure we have nice window decorations.
          frame.setDefaultLookAndFeelDecorated(true);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          // Create and set up content pane.
          frame.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent e) {
                    System.exit(0);
          JPanel masterPanel = new JPanel();
          frame.add("Center", masterPanel);
          // Display the window.
          frame.pack();
          frame.setSize(new Dimension( 1000 , 640 ));
          frame.setVisible(true);
     } // end createAndShowGUI
     public static void main(String s[]) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    createAndShowGUI();
     } // end main
     public void actionPerformed(ActionEvent e) {
          repaint(1024);
    public void stateChanged(ChangeEvent e) {
          repaint(1024);
     public void itemStateChanged(ItemEvent e) {
          Object obj = e.getSource();
          if ( obj == isMetric ) {
               System.out.println("obj isMetric");
            //Turn it to metric.
            rowView.setIsMetric(true);
            columnView.setIsMetric(true);
               picture.setMaxUnitIncrement(rowView.getIncrement());
        } else {
            System.out.println("obj isNotMetric");
               //Turn it to inches.
            rowView.setIsMetric(false);
            columnView.setIsMetric(false);
               picture.setMaxUnitIncrement(rowView.getIncrement());
     } // end itemStateChanged(ItemEvent e)
} // end TooAwoo
Next is ScrollablePicture.java
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
public class ScrollablePicture extends JLabel implements Scrollable {
    private int maxUnitIncrement = 1;
     private boolean missingPicture = false;
    public ScrollablePicture (ImageIcon imageIcon_, int m){                              //(BufferedImage bImg, int m)
        super(imageIcon_); // comment this line if bImg...
          if (imageIcon_ == null) { // change imageIcon_ to bImg if bImg...
               missingPicture = true;
               setText("No picture found.");
               setHorizontalAlignment(CENTER);
               setOpaque(true);
               setBackground(Color.black);
          maxUnitIncrement = m;
    public Dimension getPreferredScrollableViewportSize() {
        return getPreferredSize();
    public int getScrollableUnitIncrement(Rectangle visibleRect,
                                          int orientation,
                                          int direction) {
        //Get the current position.
        int currentPosition = 0;
        if (orientation == SwingConstants.HORIZONTAL)
            currentPosition = visibleRect.x;
        else
            currentPosition = visibleRect.y;
        //Return the number of pixels between currentPosition
        //and the nearest tick mark in the indicated direction.
        if (direction < 0) {
            int newPosition = currentPosition -
               (currentPosition / maxUnitIncrement) *
               maxUnitIncrement;
            return (newPosition == 0) ? maxUnitIncrement : newPosition;
        } else {
            return ((currentPosition / maxUnitIncrement) + 1) *
               maxUnitIncrement - currentPosition;
    public int getScrollableBlockIncrement(Rectangle visibleRect,
                                           int orientation,
                                           int direction) {
        if (orientation == SwingConstants.HORIZONTAL)
            return visibleRect.width - maxUnitIncrement;
        else
            return visibleRect.height - maxUnitIncrement;
    public boolean getScrollableTracksViewportWidth() {
        return false;
    public boolean getScrollableTracksViewportHeight() {
        return false;
    public void setMaxUnitIncrement(int pixels) {
        maxUnitIncrement = pixels;
Next is Corner.java
import java.awt.*;
import javax.swing.*;
public class Corner extends JComponent {
    protected void paintComponent(Graphics g) {
        g.setColor(new Color(230, 163, 4));
        g.fillRect(0, 0, getWidth(), getHeight());
Next is Rule.java
import java.awt.*;
import javax.swing.*;
public class Rule extends JComponent {
    public static final int INCH = Toolkit.getDefaultToolkit().
            getScreenResolution();
    public static final int HORIZONTAL = 0;
    public static final int VERTICAL = 1;
    public static final int SIZE = 30;
    public int orientation;
    public boolean isMetric;
    private int increment;
    private int units;
    public Rule(int o, boolean m) {
        orientation = o;
        isMetric = m;
        setIncrementAndUnits();
    public void setIsMetric(boolean isMetric) {
        this.isMetric = isMetric;
        setIncrementAndUnits();
        repaint();
    private void setIncrementAndUnits() {
        if (isMetric) {
            units = (int)((double)INCH / (double)2.54); // dots per centimeter
            increment = units;
        } else {
            units = INCH;
            increment = units / 2;
    public boolean isMetric() {
        return this.isMetric;
    public int getIncrement() {
        return increment;
    public void setPreferredHeight(int ph) {
        setPreferredSize(new Dimension(SIZE, ph));
    public void setPreferredWidth(int pw) {
        setPreferredSize(new Dimension(pw, SIZE));
    protected void paintComponent(Graphics g) {
        Rectangle drawHere = g.getClipBounds();
        // Fill clipping area with dirty brown/orange.
        g.setColor(new Color(230, 163, 4));
        g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
        // Do the ruler labels in a small font that's black.
        g.setFont(new Font("SansSerif", Font.PLAIN, 10));
        g.setColor(Color.black);
        // Some vars we need.
        int end = 0;
        int start = 0;
        int tickLength = 0;
        String text = null;
        // Use clipping bounds to calculate first and last tick locations.
        if (orientation == HORIZONTAL) {
            start = (drawHere.x / increment) * increment;
            end = (((drawHere.x + drawHere.width) / increment) + 1)
                  * increment;
        } else {
            start = (drawHere.y / increment) * increment;
            end = (((drawHere.y + drawHere.height) / increment) + 1)
                  * increment;
        // Make a special case of 0 to display the number
        // within the rule and draw a units label.
        if (start == 0) {
            text = Integer.toString(0) + (isMetric ? " cm" : " in");
            tickLength = 8;//10;
            if (orientation == HORIZONTAL) {
                g.drawLine(0, SIZE-1, 0, SIZE-tickLength-1);
                g.drawString(text, 2, 21);
            } else {
                g.drawLine(SIZE-1, 0, SIZE-tickLength-1, 0);
                g.drawString(text, 9, 10);
            text = null;
            start = increment;
        // ticks and labels
        for (int i = start; i < end; i += increment) {
            if (i % units == 0)  {
                tickLength = 7;//10;
                text = Integer.toString(i/units);
            } else {
                tickLength = 4;//7;
                text = null;
            if (tickLength != 0) {
                if (orientation == HORIZONTAL) {
                    g.drawLine(i, SIZE-1, i, SIZE-tickLength-1);
                    if (text != null)
                        g.drawString(text, i-3, 21);
                } else {
                    g.drawLine(SIZE-1, i, SIZE-tickLength-1, i);
                    if (text != null)
                        g.drawString(text, 9, i+3);
Here is TooAwoo.html
<HTML>
<HEAD>
<TITLE>TooAwoo</TITLE>
</HEAD>
<BODY>
<APPLET archive="TooAwoo.jar" code="TooAwoo" width=1024 height=800>
Your browser does not support Java, so nothing is displayed.
</APPLET>
</BODY>
</HTML>
*/Total number of lines: 486
Weight: 15 199 bytes
Total number of files: 5
TooAwoo.java
ScrollablePicture.java
Corner.java
Rule.java
TooAwoo.html
... in that order in my code
The major default is: I cannot have that BuffuredImage at the left of the screen if run using bImp at line 91 of TooAwoo.java.
Minor bug: the JToggle button (inch/cm) does not fires-up correctly. Nothing change.
Anyway feel free to fire at me if you believe its a good strategy. I will remain very positive to all comments and suggestions.
Thanks.
dimitryous r.

Similar Messages

  • Help with BufferedImage and JPanel

    I have a program that should display some curves, but thats not the problem, the real problem is when i copy the image contained in the JPanel to the buffered image then i draw something there and draw it back to the JPanel. My panel initialy its white but after the operation it gets gray
    Please if some one could help with this
    here is my code divided in three classes
    //class VentanaPrincipal
    package gui;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JSeparator;
    import javax.swing.border.LineBorder;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    * This code was edited or generated using CloudGarden's Jigloo
    * SWT/Swing GUI Builder, which is free for non-commercial
    * use. If Jigloo is being used commercially (ie, by a corporation,
    * company or business for any purpose whatever) then you
    * should purchase a license for each developer using Jigloo.
    * Please visit www.cloudgarden.com for details.
    * Use of Jigloo implies acceptance of these licensing terms.
    * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
    * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
    * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
    public class VentanaPrincipal extends javax.swing.JFrame {
              //Set Look & Feel
              try {
                   javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } catch(Exception e) {
                   e.printStackTrace();
         private JMenuItem helpMenuItem;
         private JMenu jMenu5;
         private JMenuItem deleteMenuItem;
         private JSeparator jSeparator1;
         private JMenuItem pasteMenuItem;
         private JLabel jLabel4;
         private JLabel jLabel5;
         private JLabel jLabel3;
         private JLabel jLabel2;
         private JLabel jLabel1;
         private JButton jSPLineButton;
         private JButton jHermiteButton;
         private JButton jBezierButton;
         private JPanel jPanel2;
         private JPanel jPanel1;
         private JMenuItem jResetMenuItem1;
         private JMenuItem copyMenuItem;
         private JMenuItem cutMenuItem;
         private JMenu jMenu4;
         private JMenuItem exitMenuItem;
         private JSeparator jSeparator2;
         private JMenu jMenu3;
         private JMenuBar jMenuBar1;
          * Variables no autogeneradas
         private int botonSeleccionado;
         * Auto-generated main method to display this JFrame
         public static void main(String[] args) {
              VentanaPrincipal inst = new VentanaPrincipal();
              inst.setVisible(true);
         public VentanaPrincipal() {
              super();
              initGUI();
         private void initGUI() {
              try {
                        this.setTitle("Info3 TP 2");
                             jPanel1 = new pizarra();
                             getContentPane().add(jPanel1, BorderLayout.WEST);
                             jPanel1.setPreferredSize(new java.awt.Dimension(373, 340));
                             jPanel1.setMinimumSize(new java.awt.Dimension(10, 342));
                             jPanel1.setBackground(new java.awt.Color(0,0,255));
                             jPanel1.setBorder(BorderFactory.createCompoundBorder(
                                  new LineBorder(new java.awt.Color(0, 0, 0), 1, true),
                                  null));
                             BufferedImage bufimg = (BufferedImage)jPanel1.createImage(jPanel1.getWidth(), jPanel1.getHeight());
                             ((pizarra) jPanel1).setBufferedImage(bufimg);
                             jPanel2 = new JPanel();
                             getContentPane().add(jPanel2, BorderLayout.CENTER);
                             GridBagLayout jPanel2Layout = new GridBagLayout();
                             jPanel2Layout.rowWeights = new double[] {0.0, 0.0, 0.0, 0.0};
                             jPanel2Layout.rowHeights = new int[] {69, 74, 76, 71};
                             jPanel2Layout.columnWeights = new double[] {0.0, 0.0, 0.1};
                             jPanel2Layout.columnWidths = new int[] {83, 75, 7};
                             jPanel2.setLayout(jPanel2Layout);
                                  jBezierButton = new JButton();
                                  jPanel2.add(jBezierButton, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jBezierButton.setText("Bezier");
                                  jBezierButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jBezierButton.addActionListener(new ActionListener() {
                                       public void actionPerformed(ActionEvent evt) {
                                            bezierActionPerformed();
                                  jHermiteButton = new JButton();
                                  jPanel2.add(jHermiteButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jHermiteButton.setText("Hermite");
                                  jHermiteButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jSPLineButton = new JButton();
                                  jPanel2.add(jSPLineButton, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
                                  jSPLineButton.setText("SP Line");
                                  jSPLineButton.setFont(new java.awt.Font("Tahoma",0,10));
                                  jLabel1 = new JLabel();
                                  jPanel2.add(jLabel1, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
                                  jLabel1.setText("Posicion Mouse");
                                  jLabel2 = new JLabel();
                                  jPanel2.add(jLabel2, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel2.setText("X:");
                                  jLabel3 = new JLabel();
                                  jPanel2.add(jLabel3, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel3.setText("Y:");
                                  jLabel4 = new JLabel();
                                  jPanel2.add(jLabel4, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.NORTH, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
                                  jLabel4.setText("-");
                                  jLabel5 = new JLabel();
                                  jPanel2.add(jLabel5, new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.NONE, new Insets(0, 0, 12, 0), 0, 0));
                                  jLabel5.setText("-");
                   this.setSize(600, 400);
                        jMenuBar1 = new JMenuBar();
                        setJMenuBar(jMenuBar1);
                             jMenu3 = new JMenu();
                             jMenuBar1.add(jMenu3);
                             jMenu3.setText("Archivo");
                                  jSeparator2 = new JSeparator();
                                  jMenu3.add(jSeparator2);
                                  exitMenuItem = new JMenuItem();
                                  jMenu3.add(exitMenuItem);
                                  exitMenuItem.setText("Exit");
                                  jResetMenuItem1 = new JMenuItem();
                                  jMenu3.add(jResetMenuItem1);
                                  jResetMenuItem1.setText("Reset");
                             jMenu4 = new JMenu();
                             jMenuBar1.add(jMenu4);
                             jMenu4.setText("Edit");
                                  cutMenuItem = new JMenuItem();
                                  jMenu4.add(cutMenuItem);
                                  cutMenuItem.setText("Cut");
                                  copyMenuItem = new JMenuItem();
                                  jMenu4.add(copyMenuItem);
                                  copyMenuItem.setText("Copy");
                                  pasteMenuItem = new JMenuItem();
                                  jMenu4.add(pasteMenuItem);
                                  pasteMenuItem.setText("Paste");
                                  jSeparator1 = new JSeparator();
                                  jMenu4.add(jSeparator1);
                                  deleteMenuItem = new JMenuItem();
                                  jMenu4.add(deleteMenuItem);
                                  deleteMenuItem.setText("Delete");
                             jMenu5 = new JMenu();
                             jMenuBar1.add(jMenu5);
                             jMenu5.setText("Help");
                                  helpMenuItem = new JMenuItem();
                                  jMenu5.add(helpMenuItem);
                                  helpMenuItem.setText("Help");
              } catch (Exception e) {
                   e.printStackTrace();
         private void bezierActionPerformed(){
              botonSeleccionado = 1;
              ((pizarra) jPanel1).setTipoFigura(botonSeleccionado);
              ((pizarra) jPanel1).pintarGrafico();
    //class graphUtils
    package func;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.image.BufferedImage;
    public class graphUtils {
         public static void dibujarPixel(BufferedImage img, int x, int y, int color){
              img.setRGB(x, y, color);
         public static void dibujarLinea(BufferedImage img, int x0, int y0, int x1, int y1, int color){
            int dx = x1 - x0;
            int dy = y1 - y0;
            if (Math.abs(dx) > Math.abs(dy)) {          // Pendiente m < 1
                float m = (float) dy / (float) dx;     
                float b = y0 - m*x0;
                if(dx < 0) dx = -1; else dx = 1;
                while (x0 != x1) {
                    x0 += dx;
                    dibujarPixel(img, x0, Math.round(m*x0 + b), color);
            } else
            if (dy != 0) {                              // Pendiente m >= 1
                float m = (float) dx / (float) dy;
                float b = x0 - m*y0;
                if(dy < 0) dy = -1; else dy = 1;
                while (y0 != y1) {
                    y0 += dy;
                    dibujarPixel(img, Math.round(m*y0 + b), y0, color);
         public static void dibujarBezier(BufferedImage img, Point puntos, int color){
    //class pizarra
    package gui;
    import javax.swing.*;
    import sun.awt.VerticalBagLayout;
    import sun.security.krb5.internal.bh;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.image.BufferedImage;
    import java.util.ArrayList;
    import func.graphUtils;
    * esta clase pizarra extiende la clase JPanel y se agregan las funciones de pintado
    * y rellenado que se muestra en pantalla dentro del panel que se crea con esta clase
    * @author victorg
    public class pizarra extends JPanel implements MouseListener{
         private int tipoFigura;
         BufferedImage bufferImagen;
         Image img;
         Graphics img_gc;
         private Color colorRelleno, colorLinea;
         private Point puntosBezier[] = new Point[3];
         public pizarra(){
              super();          
              addMouseListener(this);
              //this.setBackground(Color.BLUE);
              colorLinea = Color.BLUE;
         public void setTipoFigura(int seleccion){
              // se setea para ver si es bezier, hermite, SP line
              tipoFigura = seleccion;
         public void setTipoRelleno(int seleccion){
         public void setColorRelleno(Color relleno){
              colorRelleno = relleno;          
         public void setColorLinea(Color linea){
              colorLinea = linea;
         public void setBufferedImage(BufferedImage bufimg){
              bufferImagen = bufimg;
         public void pintarGrafico(){
              Graphics g = this.getGraphics();     
              g.setColor(colorLinea);
              //accion ejecutada cuando se selecciona para graficar un poligono
              if(tipoFigura == 1){// bezier
                   if(bufferImagen == null){
                        //mantiene guardada la imagen cuando la pantalla pasa a segundo plano
                        bufferImagen = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
                        this.setBackground(Color.WHITE);                                                  
                        bufferImagen = (BufferedImage)createImage(getWidth(), getHeight());
                        //bufferImagen = this.createImage(getWidth(), getHeight());
                   //g.drawImage(bufferImagen,0,0,this);
                   graphUtils.dibujarLinea(bufferImagen,10, 10, 50, 50, colorLinea.getRGB());
                   g.drawImage(bufferImagen,0,0,this);
         protected void paintComponent(Graphics g) { // llamado al repintar
              //setBackground(colorFondo);
              super.paintComponent(g);
    //          Graphics2D g2 = (Graphics2D)g;          
    //          g2.drawImage(bufferImagen, 0,0, this);          
    //          g2.dispose();     
         public void mouseClicked(MouseEvent arg0) {          
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
    }

    1) Swing related questions should be posted in the Swing forum.
    Custom painting should be done in the paintComponent(..) method. You created a "pintarGraphico" method to do the custom painting, but that method is only execute once. When Java determines that the panel needs to be repainted, the paintComponent() method is executed which simply does a super.paintComponent(), which in turn simply paints the background of the panel overwriting you custom painting.

  • Need help: BufferedImage and zooming

    please help me understand what i am doing wrong. i am having a hard time understanding the concept behind BufferedImage and zooming. the applet code loads an image as its background. after loading, you can draw line segments on it. but when i try to zoom in, the image in the background remains the same in terms of size, line segments are the only ones that are being zoomed, and the mouse coordinates are confusing.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.imageio.*;
    import java.io.*;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.net.URL;
    import java.awt.image.*;
    public class Testing extends JApplet {
         private String url;
         private Map map;
         public void init() {
         public void start()
              url = "http://localhost/image.gif";
                  map = new Map(url);
                 getContentPane().add(map, "Center");
                 validate();
                 map.validate();
    class Map extends JPanel implements MouseListener, MouseMotionListener{
         private Image image;
         private ArrayList<Point2D> points;
         private ArrayList<Line2D> lineSegment;
         private Point2D startingPoint;
         private int mouseX;
         private int mouseY;
         private BufferedImage bimg;
         private AffineTransform xform;
         private AffineTransform inverse;
         private double zoomFactor = 1;
         public Map(String url)
                         super();
              //this.image = image;
              try
                   image = ImageIO.read(new URL(url));
              catch(Exception e)
              Insets insets = getInsets();
              xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
              xform.scale(zoomFactor,zoomFactor);
              try {
                   inverse = xform.createInverse();
              } catch (NoninvertibleTransformException e) {
                   System.out.println(e);
              points = new ArrayList();
              startingPoint = new Point();
              bimg = new BufferedImage(this.image.getWidth(this), this.image.getHeight(this), BufferedImage.TYPE_INT_ARGB);
              repaintBImg();
              addMouseListener(this);
              addMouseMotionListener(this);
         public void paintComponent(Graphics g)
            Graphics2D g2d = (Graphics2D)g;
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            bimg = (BufferedImage)image;
            g2d.drawRenderedImage(bimg, xform);
            if(!points.isEmpty())
                 for(int i=0; i<points.size(); i++)
                      if(i > 0)
                           drawLineSegment(g2d,points.get(i-1),points.get(i));
                      drawPoint(g2d, points.get(i));
            if(startingPoint != null)
                drawTempLine(startingPoint, g2d);
            else
                mouseX = 0;
                mouseY = 0;
         private void repaintBImg()
              bimg.flush();
              Graphics2D g2d = bimg.createGraphics();
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
              g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING , RenderingHints.VALUE_RENDER_QUALITY ));
            g2d.drawRenderedImage(bimg, xform);
            g2d.dispose();
         private void drawPoint(Graphics2D g2d, Point2D p)
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
              g2d.setColor(Color.ORANGE);
              g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
         private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2)
              double x1 = p1.getX() * zoomFactor;
                 double y1 = p1.getY() * zoomFactor;
                 double x2 = p2.getX() * zoomFactor;
                 double y2 = p2.getY() * zoomFactor;
                 g2d.setColor(Color.RED);
                 g2d.setStroke(new BasicStroke(3.0F));
                 g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
             private void drawTempLine(Point2D p, Graphics2D g2d)
                 int startX = (int)(p.getX() * zoomFactor);
                 int startY = (int)(p.getY() * zoomFactor);
                 if(mouseX != 0 && mouseY != 0)
                         g2d.setColor(Color.RED);
                          g2d.setStroke(new BasicStroke(2.0F));
                          g2d.drawLine(startX, startY, mouseX, mouseY);
         public void mouseClicked(MouseEvent e)
         public void mouseDragged(MouseEvent e)
              mouseX = (int)(e.getX()*zoomFactor);
              mouseY = (int)(e.getY()*zoomFactor);
              repaint();
         public void mousePressed(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
                   if(points.size() > 0)
                        startingPoint = points.get(points.size()-1);
                        mouseX = mouseY = 0;
                   repaint();
              else if(e.getButton() == 2)
                   zoomFactor = zoomFactor + .05;
                   repaintBImg();
              else if(e.getButton() == 3)
                   zoomFactor = zoomFactor - .05;
                   repaintBImg();
         public void mouseReleased(MouseEvent e)
              if(e.getButton() == 1)
                   points.add(inverse.transform(e.getPoint(), null));
              repaint();
         public void mouseEntered(MouseEvent mouseevent)
         public void mouseExited(MouseEvent mouseevent)
         public void mouseMoved(MouseEvent mouseevent)
    }Message was edited by:
    hardc0d3r

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.awt.geom.*;
    import java.io.*;
    import java.net.URL;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class ZoomTesting extends JApplet {
        public void init() {
            //String dir = "file:/" + System.getProperty("user.dir");
            //System.out.printf("dir = %s%n", dir);
            String url = "http://localhost/image.gif";
                         //dir + "/images/cougar.jpg";
            MapPanel map = new MapPanel(url);
            getContentPane().add(map, "Center");
        public static void main(String[] args) {
            JApplet applet = new ZoomTesting();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(applet);
            f.setSize(400,400);
            f.setLocation(200,200);
            applet.init();
            f.setVisible(true);
    class MapPanel extends JPanel implements MouseListener, MouseMotionListener {
        private BufferedImage image;
        private ArrayList<Point2D> points;
        private Point2D startingPoint;
        private int mouseX;
        private int mouseY;
        private AffineTransform xform;
        private AffineTransform inverse;
        RenderingHints hints;
        private double zoomFactor = 1;
        public MapPanel(String url) {
            super();
            try {
                image = ImageIO.read(new URL(url));
            } catch(Exception e) {
                System.out.println(e.getClass().getName() +
                                   " = " + e.getMessage());
            Map<RenderingHints.Key, Object> map =
                        new HashMap<RenderingHints.Key, Object>();
            map.put(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            map.put(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hints = new RenderingHints(map);
            setTransforms();
            points = new ArrayList<Point2D>();
            startingPoint = new Point();
            addMouseListener(this);
            addMouseMotionListener(this);
        private void setTransforms() {
            Insets insets = getInsets();
            xform = AffineTransform.getTranslateInstance(insets.left, insets.top);
            xform.scale(zoomFactor,zoomFactor);
            try {
                inverse = xform.createInverse();
            } catch (NoninvertibleTransformException e) {
                System.out.println(e);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setRenderingHints(hints);
            g2d.drawRenderedImage(image, xform);
            if(!points.isEmpty()) {
                for(int i=0; i<points.size(); i++) {
                    if(i > 0)
                        drawLineSegment(g2d,points.get(i-1),points.get(i));
                    drawPoint(g2d, points.get(i));
            if(startingPoint != null) {
                drawTempLine(startingPoint, g2d);
            } else {
                mouseX = 0;
                mouseY = 0;
        private void drawPoint(Graphics2D g2d, Point2D p) {
            int x = (int)(p.getX() * zoomFactor);
            int y = (int)(p.getY() * zoomFactor);
            int w = (int)(13 * zoomFactor);
            int h = (int)(13 * zoomFactor);
            g2d.setColor(Color.ORANGE);
            g2d.setStroke(new BasicStroke(1.0F));
            g2d.fillOval(x - w / 2, y - h / 2, w, h);
            g2d.setColor(Color.BLACK);
            g2d.drawOval(x - w / 2, y - h / 2, w - 1, h - 1);
        private void drawLineSegment(Graphics2D g2d, Point2D p1, Point2D p2) {
            double x1 = p1.getX() * zoomFactor;
            double y1 = p1.getY() * zoomFactor;
            double x2 = p2.getX() * zoomFactor;
            double y2 = p2.getY() * zoomFactor;
            g2d.setColor(Color.RED);
            g2d.setStroke(new BasicStroke(3.0F));
            g2d.draw(new java.awt.geom.Line2D.Double(x1, y1, x2, y2));
        private void drawTempLine(Point2D p, Graphics2D g2d) {
            int startX = (int)(p.getX() * zoomFactor);
            int startY = (int)(p.getY() * zoomFactor);
            if(mouseX != 0 && mouseY != 0) {
                g2d.setColor(Color.RED);
                g2d.setStroke(new BasicStroke(2.0F));
                g2d.drawLine(startX, startY, mouseX, mouseY);
        public void mouseClicked(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {
            mouseX = (int)(e.getX()*zoomFactor);
            mouseY = (int)(e.getY()*zoomFactor);
            repaint();
        public void mousePressed(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
                if(points.size() > 0) {
                    startingPoint = points.get(points.size()-1);
                    mouseX = mouseY = 0;
            } else if(e.getButton() == 2) {
                zoomFactor = zoomFactor + .05;
                setTransforms();
            } else if(e.getButton() == 3) {
                zoomFactor = zoomFactor - .05;
                setTransforms();
            repaint();
        public void mouseReleased(MouseEvent e) {
            if(e.getButton() == 1) {
                points.add(inverse.transform(e.getPoint(), null));
            repaint();
        public void mouseEntered(MouseEvent mouseevent) {}
        public void mouseExited(MouseEvent mouseevent) {}
        public void mouseMoved(MouseEvent mouseevent) {}
    }

  • Problem with Double Buffering and Swing

    Hi
    I made a game and basically it works pretty well, my only problem is it flickers really badly right now. I read up on a whole lot of forums about double buffering and none of those methods seemed to work. Then I noticed that Swing has double buffering built in so I tried that but then I get compilation errors and I'm really not sure why. My original code was a console application and worked perfectly, then I ported it into a JApplet and it still works but it flickers and thats what I'm tryign to fix now.
    The code below is in my main class under the constructor.
    Heres the double buffering code I'm trying to use, I'm sure you all seen it before lol
    public void update(Graphics g)
              // initialize buffer
              if (dbImage == null)
                   dbImage = createImage(this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics();
              // clear screen in background
              dbg.setColor(getBackground());
              dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
              // draw elements in background
              dbg.setColor(getForeground());
              paint(dbg);
              // draw image on the screen
              g.drawImage(dbImage, 0, 0, this);
         }My paint is right under neath and heres how it looks
    This snipet of code works but when I change the method to
    public paintComponent(Graphics g){
    super.paintComponent(g)...
    everythign stops working and get a compilation error and says that it can't find paintComponent in javax.swing.JFrame.
    public void paint(Graphics g)
              super.paint(g);
              //if game starting display menue
              if (show_menue)
                   //to restart lives if player dies
                   lives = 3;
                   menue.draw_menue(g);
                   menue_ufo1.draw_shape(g);
                   menue_ufo2.shape_color = Color.DARK_GRAY;
                   menue_ufo2.draw_shape(g);
                   menue_ufo3.shape_color = Color.BLUE;
                   menue_ufo3.draw_shape(g);
                   menue_ufo4.shape_color = new Color(82, 157, 22);
                   menue_ufo4.draw_shape(g);
                   menue_ufo5.draw_shape(g);
                   menue_ufo6.shape_color = new Color(130, 3, 3); ;
                   menue_ufo6.draw_shape(g);
                   menue_turret.draw_ship(g);
                   menue_ammo.draw_ammo(g);
              else
                   //otherwise redraw game objects
                   gunner.draw_ship(g);
                   y_ammo.draw_ammo(g);
                   grass.draw_bar(g);
                   o_ufo.draw_shape(g);
                   b_ufo.draw_shape(g);
                   m_ufo.draw_shape(g);
                   s_ufo.draw_shape(g);
                   z_ufo.draw_shape(g);
                   xx_ufo.draw_shape(g);
                   info.draw_bar(g);
                   live_painter.draw_lives(g, lives);
                   score_painter.draw_score(g, score);
                   level_display.draw_level(g, level);
                   explosion.draw_boom(g);
         }I just want to get rid of the flickering for now so any help will be greatly appreciated. Depending which will be simpler I can either try to double buffer this program or port it all to swing but I'm not sure which elements are effected by AWT and which by Swing. Also I read some of the Java documentation but couldn't really understand how to implement it to fix my program.
    Thanks in advance
    Sebastian

    This is a simple animation example quickly thrown together. I have two classes, an animation panel which is a JPanel subclass that overrides paintComponent and draws the animation, and a JApplet subclass that simply holds the animation panel in the applet's contentpane:
    SimpleAnimationPanel.java
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class SimpleAnimationPanel extends JPanel
        private static final int DELAY = 20;
        public static final int X_TRANSLATION = 2;
        public static final int Y_TRANSLATION = 2;
        private Point point = new Point(5, 32);
        private BufferedImage duke = null;
        private Timer timer = new Timer(DELAY, new TimerAction());
        public SimpleAnimationPanel()
            try
                // borrow an image from sun.com
                duke = ImageIO.read(new URL(
                        "http://java.sun.com/products/plugin/images/duke.wave.med.gif"));
            catch (MalformedURLException e)
                e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            setPreferredSize(new Dimension(600, 400));
            timer.start();
        // do our drawing here in the paintComponent override
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            if (duke != null)
                g.drawImage(duke, point.x, point.y, this);
        private class TimerAction implements ActionListener
            @Override
            public void actionPerformed(ActionEvent e)
                int x = point.x;
                int y = point.y;
                Dimension size = SimpleAnimationPanel.this.getSize();
                if (x > size.width)
                    x = 0;
                else
                    x += X_TRANSLATION;
                if (y > size.height)
                    y = 0;
                else
                    y += Y_TRANSLATION;
                point.setLocation(new Point(x, y)); // update the point
                SimpleAnimationPanel.this.repaint();
    }AnimationApplet.java
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class AnimationApplet extends JApplet
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        // construct the panel
                        JPanel simpleAnimation = new SimpleAnimationPanel();
                        // put it in the contentPane of the JApplet
                        getContentPane().add(simpleAnimation);
                        setSize(simpleAnimation.getPreferredSize());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }Here's a 3rd bonus class that shows how to put the JPanel into a stand-alone program, a JFrame. It's very similar to doing it in the JApplet:
    AnimationFrame.java
    import javax.swing.JFrame;
    public class AnimationFrame
        private static void createAndShowUI()
            JFrame frame = new JFrame("SimpleAnimationPanel");
            frame.getContentPane().add(new SimpleAnimationPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }Edited by: Encephalopathic on Mar 15, 2008 11:01 PM

  • Memory Efficiency of BufferedImage and ImageIO

    This thread discusses the memory efficiency of BufferedImage and ImageIO. I also like to know whether if there's possible memory leak in BufferedImage / ImageIO, or just that the result matches the specifications. Any comments are welcomed.
    My project uses a servlet to create appropriate image tiles (in PNG format) that fits the specification of google map, from images stored in a database. But it only takes a few images to make the system out of heap memory. Increasing the initial heap memory just delays the problem. So it is not acceptable.
    To understand why that happens, I write a simple code to check the memory usage of BufferedImage and ImageIO. The code simply keeps making byte arrays from the same image until it is running out of the heap memory.
    Below shows how many byte arrays it can create:
    1M jpeg picture (2560*1920):
    jpeg = 123
    png = 3
    318K png picture (1000*900):
    jpeg = 1420
    png = 178
    Notice that the program runs out of memory with only 3 PNG byte arrays for the first picture!!!! Is this normal???
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.imageio.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.*;
    public class Test {
         public static void main(String[] args) {
              Collection images = new ArrayList();
              for (;;) {
                   try {
                        BufferedImage img = ImageIO.read(new File("PTHNWIDE.png"));
                        img.flush();
                        ByteArrayOutputStream out =
                             new ByteArrayOutputStream();
                        ImageIO.write(img, "png", out); // change to "jpeg" for jpeg
                        images.add(out.toByteArray());
                        out.close();
                   } catch (OutOfMemoryError ome) {
                        System.err.println(images.size());
                        throw ome;
                   } catch (Exception exc) {
                        exc.printStackTrace();
                        System.err.println(images.size());
    }

    a_silent_lamb wrote:
    1. For the testing program, I just use the default VM setting, ie. 64M memory so it can run out faster. For server, the memory would be at least 256M.You might want to increase the heap size.
    2. Do you mean it's 2560*1920*24bits when loaded? Of course.
    That's pretty (too) large for my server usage, Well you have lots of image data
    because it will need to process large dimension pictures (splitting each into set of 256*256 images). Anyway to be more efficient?Sure, use less colors :)

  • Difference Between Applet and Swing

    Difference Between Applet and Swing

    The advantages and disadvantages of both applets and Swing are the small fluffy elephants you get inside of every box. They're quite well trained and can skeletonize your neighbors' annoying pets upon command.

  • Devloping graphs using pure java without applets and swings

    Hi Guys
    i want to devlop bar graphs,pie charts,line graphs using pure java.i don't want to use applets and swings..does any body help on this asap..
    IT'S VERY URGENT
    cheers
    ANAND

    Go to
    http://java.sun.com/docs/books/tutorial/information/download.html#OLDui
    and get: Creating a User Interface (AWT Only) Archive (tut-OLDui.zip)

  • Eclipse RCP and swing key accelerator

    Hi,
    I have a JTree inside a view and a popup message when you right click
    on the tree.
    I added a key accelerator to the menu and I see the shortcut on the menu but when I use the shortcut, nothing happens.
    I believe the problem is SWT -> SWING issue but I don't have any idea
    how to solve it.
    Thanks in advance
    Dekel

    Java 'WebStart is (in principle) a fine distribution/deployment/update technology.
    It covers smart versioning of jars/jvms.
    Native user experience and Swing poses no problem.
    I prefer Swing as one can construe one own controls in detail.
    Both Eclipse RCP and Netbeans Platform have a very specific starting point.
    Both come with a considerable amount of code.
    In fact have a feasability study in the form of writing hello-worlds in both.
    The unmentioned alternative, starting from scratch with Swing,
    may have some benefits.

  • What are the differences between Applet and Swings

    Please let me know the differences between Applet and Swings.

    Quit cross-posting.
    http://forum.java.sun.com/thread.jspa?threadID=755100
    http://forum.java.sun.com/thread.jspa?threadID=755099
    http://forum.java.sun.com/thread.jspa?threadID=755006

  • Printing with BufferedImage and Text Quality

    I am using PrinterJob to print text/graphics.
    In my paint method, if we paint directly on the graphics handle using Graphics2D methods, the text quality is very good.
    Our application has to manage a lot of data, and to handle the callabcks for the same page, we are painting to a BufferedImage, and then drawing the BufferedImage unto the graphics handle on the subsequent calls. The overhead to draw the page is significant, and this give us much better performance.
    The PROBLEM IS, the quality of the text using the bufferedImage is like draft quality test, not the high resolution text we get when we paint directly on the supplied handle using the native drawing emthods every time.
    Any idea how we can buffer the page image, and retain the text quality ?
    In the paint we do:
    m_Image = ((Graphics2D)pg).getDeviceConfiguration().createCompatibleImage(m_wPage,m_hPage);
    m_Graphics = (Graphics2D) m_Image.getGraphics();

    Culd u share the fix if u found one

  • Why is HeadlessException explicitly thrown in AWT and swing?

    Hi there,
    I just noticed that HeadlessException is explicitly thrown in some of the constructors in AWT and swing components since J2SE 1.4.
    Given that it's a RuntimeException (unchecked) it doesn't need to be included in the throws clause of the method or constructor.
    There also seems to be inconsistent application of it and inconsistent documentation in the javadoc comments.
    Is this a work in progress or did some refactoring go wrong?

    Most probably IE security settings preventing the js file to be executed. Replied in your other post:
    Unable to get property 'style' of undefined or null reference in sp.ui.dialog.debug.js
    Thanks,
    Sohel Rana
    http://ranaictiu-technicalblog.blogspot.com

  • Learning  Flash  AND swing

    hi.....do u think Flash > Applet AND VB.NET> Swing ?
    I have little knowledge on Applet AND Swing......but I think Flash and VB.Net has exceeded and captured the market of Applet and Swing . Now a days most sites are using Flash for interactivity and VB for interface. do u think learning Flash and VB.NET would be worthy ? or should i update my knowledge on Applet and Swing ? One more bad thing regarding swing is , the code becomes bulky to get a simple interface .
    i have one more doubt,......suppose i made a interface in VB.NET ( front end ) , can i run java code in back end ?
    plz let me know what should i emphasis ?
    thanks

    It all depends on your current situation. Are you employed in IT? If so, what technologies is your employer using now. What technologies do they see themselves using next year? In 5 years?
    What skills do you have now? Are you proficient in any technologies? Think about whether you want to be a jack-of-all-trades or very proficient in a smaller number of technologies. Are your current skills saleable to an employer? Should you improve your current skills or start learning new skills?
    Hey, for a forum answer, I've certainly typed a lot of question marks!

  • Are Web Start and Swing stable and mature technologies?

    Hi there
    I'm currently looking at using Webstart and Swing as technology of choice to offer more "ap-like" functionality on our company extranets, without needing serious bandwith. (bandwith in our part of the world is veeery expensive)
    I'd appreciate some advice:
    1) Is the Webstart download still about 6MB as it was at its inception?
    Must Webstart be downloaded everytime one upgrades your browser?
    2) Is it generally easy to develop using Webstart and Swing for someone with general Java (applet) development experience? (reasonable learning curve)
    3) Are there a lot of people using Webstart and Swing - ie has it proven itself to be stable and "development friendly", does it deliver on its promises of enabling one to develop fast client-side Java "apps".
    Bottom line, I need to know if it's worth my while to invest in developer resources for Webstart and Swing to get added functionality on our extranets; or should we rather keep using PHP/ASP, SQL , DHTML and be happy with the functionality these technologies bring to our user interfaces.
    Any input would be appreciated!

    I'll give a summary answer -- I'm not an expert on Swing and Java Web Start, but I've used them both to some extent.
    Java as a whole -- mature and stable, but a heavy download. Practically speaking, if your users use Windows, they'll need to download a JRE from Sun rather than go with Microsoft's outdated and never-to-be-updated Java VM.
    Swing -- mature, stable. A good way to develop platform-independent rich clients. It's hard to make a real desktop application out of DHTML and JavaScript, but desktop applications are what Swing is all about. They won't look like Windows apps, but they can be a lot more interactive than a webpage.
    Java Web Start -- usable but not yet mature. 1.0 has shortcomings (which is typical of 1.0 products) that are being addressed in 1.2, which is part of J2SE 1.4.1. Installation in Windows, in particular, should get easier, with an ActiveX control.
    In all cases, you face large downloads (10 MB or so) to install Java Web Start or a JRE, followed by reasonable downloads (10-200k, depending on the application) per Java Web Start application.

  • Why the AWT components are called heavy-weight and SWING as light-weight?

    Why the AWT components are called heavy-weight and SWING as light-weight?.
    Building our own components means overhead on JVM. hence in what sence the SWING components are called light weight.?
    I know that the Swing componets are the components which are not going to depend upon peer classes and render, OS independent LOOK n FEEL.
    Thanks,
    Sanath Kumar

    All extensions of Component are considered lightweight since, as you point out, they don't have their own dedicated native peer.
    Essentially a lightweight component only has a canvas on which to draw itself and some means of receiving events from the system. In fact, there is no need to have one of these "canvas" and "event" objects for each component - the parent component can manage these abilities on behalf of its children. Eventually you end up with only top-level components needing to be heavyweight in order to communicate with the windowing system.
    A lightweight component therefore has the minimal dependency on the underlying windowing system giving you maximum cross-platform flexibility.
    It is usually true that lightweight => slower and heavyweight => faster since it is reasonable to assume that native peers will be optimal for the windowing system. However, that's not the point of the lightweight/heavyweight distinction.
    Hope this helps.

  • Lighter Java GUI than awt and swing?

    I had recently came across a company website (http://www.bambookit.com) where they developed a java gui library without using awt and swing (seems to what they claim). And on top of that it uses xml to generate the gui components (they call widgets) and the whole library size is only 95kb and supports java 1.1.x and above. Their demos on the applets loads super fast, never know/experience that java applets can actually be this quick. But this confuses me, how is it possible to develop a gui alternative to awt with the basic java classes and no dependency on awt? But since the applets are awt based, it means that they must have some dependencies.
    This is an extract from their website (that it seemed they did not use awt)
    "Java has a fundamental flaw in its paint thread that made it very difficult to build extremely large applications without getting severe performance and resource penalties (This affects both AWT and Swing based applications). It�s main repaint queue\thread when assigning paint regions to various controls uses the Graphics objects to �clip� them. On a Sun Solaris machine this does not cause any problems, however on a windows machine each Graphics object consumes a system resource/handle, (a limit of around 16,000 exists on Win 95 and Win 98 machines). Each Bitmap image, each font object, each icon consumes a single system resource or handle. If a full repaint is performed on an application containing 1000 controls, it would consume at LEAST 1000 system resource handles. If the application was updated many times a second, lets say 10 times a second, then that equates to 10,000 handles a second. This is not taking into account labels within controls, the various fonts styles and sizes created, the various images that get loaded. This could easily exceed 20,000 system resource requests a second. Bambookit on the other hand utilizes the clip routines and passes along a SINGLE Graphics objects to all its various controls. This alone is a HUGE savings in system resources and performance."
    Two questions came to my mind:
    1) Is it possible to build applet gui without using awt and swing in java? If so the only way to do is to use JNI calls?
    2) Am I wrong in interpreting www.bambookit.com's message that they are not using awt?
    Any comments about this?
    Regards,
    Stanly

    They use AWT as basis for their drawing-layer, as any other lightweight toolkits too.
    If you just want a very fast & light alternative to swing/awt have a look at www.lwvcl.com !
    I use it for a large applet-applikation that has to be java-1.1 compatible. It was a horor when using AWT which was implemented different over all JVMs available and very slow (although native widgets were used).
    With lwvcl (which has only 150kB!) I can use state of the art applets that work very fast on modern jvms like 1.4, give me the ability to compile my applikation to native code using GCJ (using the swt-prt of the library) or distribute it to old-school 1.1 browser where it also runs quite fine...
    Its free for GPL and very cheap for commercial use.
    lg Clemens

Maybe you are looking for