Tiled image in JScrollPane paint issues...

Hello,
I'd like to have a JTable in a JScrollPane, where the area between the table and scrollpane borders
has a tiled and faded background.
I can achieve this by overriding paintComponent for either JScrollPane or JViewport:
public void paintComponent(final Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
  //paint a tiled image over background.
Rectangle2D tr = new Rectangle2D.Double(0,0, img.getWidth(), img.getHeight());
TexturePaint tp = new TexturePaint(img, tr);
  g2.setPaint(tp);
  g2.fillRect(0,0, getWidth(), getHeight());
   //paint a translucent fade over tiled background.
  GradientPaint gp = new GradientPaint(0,0, firstColor, 0, getHeight(), secondColor);
  g2.setPaint(gp);
  g2.fillRect(0,0, getWidth(), getHeight());
} When the scrollpane appears, the background looks great. But as the user scrolls, the background
gets corrupted - the newly uncovered areas have overlapping tiled images or no image at all. If the
scroll pane is resized, the background repaints correctly.
What is the correct way to implement this effect ? How should the code be corrected? ( I've tried subclassing JScrollPane and JViewport with the same results.)

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class TileScroll
    public static void main(String[] args)
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(new TiledPanel()));
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
class TiledPanel extends JPanel
    TexturePaint texture;
    GradientPaint gradient;
    boolean firstTime;
    public TiledPanel()
        firstTime = true;
        addComponentListener(new ComponentAdapter()
            public void componentResized(ComponentEvent e)
                firstTime = true;
        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.gridwidth = gbc.REMAINDER;
        JTable table = getTable();
        table.setRowHeight(30);
        JPanel header = new JPanel(gridbag);
        gbc.fill = gbc.BOTH;
        header.add(table.getTableHeader(), gbc);
        setLayout(gridbag);
        gbc.fill = gbc.HORIZONTAL;
        gbc.insets = new Insets(20,20,0,20);
        add(header, gbc);
        gbc.weighty = 1.0;
        gbc.fill = gbc.BOTH;
        gbc.insets = new Insets(0,20,20,20);
        add(table, gbc);
    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();
        if(firstTime)
            init(w,h);
        g2.setPaint(texture);
        g2.fillRect(0,0,w,h);
        g2.setPaint(gradient);
        g2.fillRect(0,0,w,h);
    private void init(int w, int h)
        int s = Math.min(w,h)/18;
        BufferedImage image = new BufferedImage(s, s, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setPaint(Color.red);
        g2.fillRect(0, 0, s, s);
        g2.setPaint(Color.blue);
        g2.fillRect(0, 0, s/2, s/2);
        g2.fillRect(s/2, s/2, s, s);
        g2.dispose();
        texture = new TexturePaint(image, new Rectangle2D.Double(0,0,s,s));
        gradient = new GradientPaint(new Point2D.Double(w,0),
                                     new Color(140,120,0,140),
                                     new Point2D.Double(0,h),
                                     new Color(0,150,0,140));
    private JTable getTable()
        String[] headers = {
            "column 1", "column 2", "column 3", "column 4"
        int cols = 4;
        int rows = 16;
        String[][] data = new String[rows][cols];
        for(int j = 0; j < rows; j++)
            for(int k = 0; k < cols; k++)
                data[j][k] = "item " + (j * cols + k + 1);
        return new JTable(data, headers);
}

Similar Messages

  • Images disappearing / being painted over

    Hi,
    Not especially familiar with images and am having issues with images being painted over when ever I move or adjust the size of my GUI. I built a majority of the GUI using the Form Designer included with Netbeans.
    Would really appreciate any advice, happy to include more detail if required.
    Cheers,
    Tim
    GUIView
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.util.Vector;
    import javax.imageio.ImageIO;
    * GUIView.java
    * Created on 22 April 2007, 21:25
    * The GUIView class is responsible to display a graphical interface.
    * This class interacts with the user and the GUIControl class allowing the user to operate the system.
    * @author  Tim
    public class GUIView extends JFrame implements ActionListener {
    // Declare method variables
        private JTextField prodIDInput0;
        private JLabel prodIDLabel0;
        private JLabel prodIDLabel1;
        private JLabel prodIDLabel2;
        private JLabel prodNameLabel0;
        private JLabel prodNameLabel1;
        private JTextField amtRcvdInput0;
        private JLabel amtRcvdLabel0;
        private JButton cancelButton0;
        private JMenu fileMenu0;
        private JMenuItem exportXMLMenuItem;
        private JMenuItem exitMenuItem;
        private JButton findButton0;
        private JLabel itemPrice0;
        private JScrollPane jScrollPane1;
        private JMenuBar menuBar0;
        private JButton paymentButton0;
        private JLabel prodDescLabel0;
        private JLabel prodDescLabel1;
        private JPanel prodImagePanel0;
        private JPanel prodPanel0;
        private JLabel qtyLabel0;
        private JTextField qtyInput0;
        private JLabel totalPrice0;
        private JLabel totalPrice1;
        private JList transList0;
        private JPanel transPanel0;
        private Vector listData;
        private BufferedImage img;
        private GUIControl guiCtl0;
        /** Creates new form GUIView */
        public GUIView (GUIControl guiCtl0) {
            // reference guiCtl object
            this.guiCtl0 = guiCtl0;
        /** initilise gui object */
        public void initGui () {
            // initialise the GUI
            initComponents ();
            // paint image
            paintImage ("images/transparent.gif");
            // show the GUI
            setVisible (true);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents () {
            // Instantiate GUI objects
            prodIDLabel0 = new JLabel ();
            prodIDLabel1 = new JLabel ();
            prodNameLabel0 = new JLabel ();
            prodNameLabel1 = new JLabel ();
            prodDescLabel0 = new JLabel ();
            prodDescLabel1 = new JLabel ();
            prodImagePanel0 = new JPanel ();
            itemPrice0 = new JLabel ();
            totalPrice0 = new JLabel ();
            totalPrice1 = new JLabel ();
            prodPanel0 = new JPanel ();
            prodIDLabel2 = new JLabel ();
            prodIDInput0 = new JTextField ();
            qtyInput0 = new JTextField ();
            qtyLabel0 = new JLabel ();
            findButton0 = new JButton ();
            transPanel0 = new JPanel ();
            paymentButton0 = new JButton ();
            cancelButton0 = new JButton ();
            amtRcvdInput0 = new JTextField ();
            amtRcvdLabel0 = new JLabel ();
            jScrollPane1 = new JScrollPane ();
            transList0 = new JList ();
            menuBar0 = new JMenuBar ();
            fileMenu0 = new JMenu ();
            listData = new Vector ();
            // default close operation is to terminate the application
            setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE);
            // title of the window
            setTitle ("Supermarket Management System");
            // centre the GUI on the screen
            Rectangle rect = GraphicsEnvironment.getLocalGraphicsEnvironment ().getMaximumWindowBounds ();
            rect.grow (-185,-100);
            setBounds (rect);
            // sets the minimum size the wonw can be shrunk to
            setMinimumSize (new java.awt.Dimension (880, 480));
            // sets the name of the frame
            setName ("mainFrame");
            // setup label to show Product ID:
            prodIDLabel0.setFont (new java.awt.Font ("Tahoma", 1, 14));
            prodIDLabel0.setText ("Product ID:");
            // setup label to show the id of the latest product object
            prodIDLabel1.setFont (new java.awt.Font ("Tahoma", 0, 14));
            prodIDLabel1.setText ("");
            prodIDLabel1.setToolTipText ("Product ID");
            // setup label to show Name:
            prodNameLabel0.setFont (new java.awt.Font ("Tahoma", 1, 14));
            prodNameLabel0.setText ("Name:");
            // setup label to show the name of the latest product object
            prodNameLabel1.setFont (new java.awt.Font ("Tahoma", 0, 14));
            prodNameLabel1.setText ("");
            prodNameLabel1.setToolTipText ("Product Name");
            // setup label to show Description:
            prodDescLabel0.setFont (new java.awt.Font ("Tahoma", 1, 14));
            prodDescLabel0.setText ("Description:");
            // setup label to show the description of the latest product object
            prodDescLabel1.setFont (new java.awt.Font ("Tahoma", 0, 14));
            prodDescLabel1.setText ("");
            prodDescLabel1.setToolTipText ("Product Description");
            // align the prodDescLabel1 to TOP
            prodDescLabel1.setVerticalAlignment (SwingConstants.TOP);
            // setup panel to display image
            prodImagePanel0.setBackground (new java.awt.Color (255, 255, 255));
            prodImagePanel0.setBorder (javax.swing.BorderFactory.createEtchedBorder (javax.swing.border.EtchedBorder.RAISED));
            org.jdesktop.layout.GroupLayout prodImagePanel0Layout = new org.jdesktop.layout.GroupLayout (prodImagePanel0);
            prodImagePanel0.setLayout (prodImagePanel0Layout);
            // specify how much the panel expands on the horizontal axis
            prodImagePanel0Layout.setHorizontalGroup (
                    prodImagePanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (0, 304, Short.MAX_VALUE)
            // specify how much the panel expands on the vertical axis
            prodImagePanel0Layout.setVerticalGroup (
                    prodImagePanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (0, 255, Short.MAX_VALUE)
            // setup item price label
            itemPrice0.setFont (new java.awt.Font ("Tahoma", 1, 14));
            itemPrice0.setText ("");
            itemPrice0.setToolTipText ("Transaction Item Price information");
            // setup label to display Total Price:
            totalPrice0.setFont (new java.awt.Font ("Tahoma", 1, 18));
            totalPrice0.setText ("Total Price:");
            // setup label to display current transaction total price
            totalPrice1.setFont (new java.awt.Font ("Tahoma", 0, 18));
            totalPrice1.setText ("$0.00");
            totalPrice1.setToolTipText ("Total cost of transaction");
            // setup JPanel to contain product look up components
            prodPanel0.setBorder (BorderFactory.createTitledBorder ("Enter Product"));
            // setup label to display Product ID:
            prodIDLabel2.setText ("Product ID:");
            // setup label to display Quantity:
            qtyLabel0.setText ("Quantity:");
            // setup button and display FIND as the text
            findButton0.setFont (new java.awt.Font ("Tahoma", 0, 14));
            findButton0.setText ("FIND");
            findButton0.setToolTipText ("Click to find product");
            findButton0.addActionListener (this);
            // create new GroupLayout for prodPanel0
            org.jdesktop.layout.GroupLayout prodPanel0Layout = new org.jdesktop.layout.GroupLayout (prodPanel0);
            prodPanel0.setLayout (prodPanel0Layout);
            // set horizontal group
            prodPanel0Layout.setHorizontalGroup (
                    prodPanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (prodPanel0Layout.createSequentialGroup ()
                    .add (15, 15, 15)
                    .add (prodIDLabel2)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    // add prodIDInput0 JTextField to form
                    .add (prodIDInput0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 126, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add (22, 22, 22)
                    .add (qtyLabel0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    // addd qtyInput0 JTextField to form
                    .add (qtyInput0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add (22, 22, 22)
                    .add (findButton0)
                    .addContainerGap (org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            // set vertical group
            prodPanel0Layout.setVerticalGroup (
                    prodPanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (prodPanel0Layout.createSequentialGroup ()
                    .addContainerGap ()
                    .add (prodPanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.BASELINE)
                    .add (prodIDLabel2)
                    // add prodIDInput0 JTextField to form
                    .add (prodIDInput0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add (qtyLabel0)
                    // add qtyInput0 JTextField to form
                    .add (qtyInput0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add (findButton0))
                    .addContainerGap (org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            // setup JPanel to contain finialise payment components
            transPanel0.setBorder (BorderFactory.createTitledBorder ("Finalise Transaction"));
            // setup button and display PAYMENT as the text
            paymentButton0.setFont (new java.awt.Font ("Tahoma", 0, 14));
            paymentButton0.setText ("PAYMENT");
            paymentButton0.setToolTipText ("Click to finalise transaction");
            // setup button and display CANCEL as the text
            cancelButton0.setFont (new java.awt.Font ("Tahoma", 0, 14));
            cancelButton0.setText ("CANCEL");
            cancelButton0.setToolTipText ("Cancel the current transaction");
            cancelButton0.addActionListener (this);
            // setup label to display Amount received:
            amtRcvdLabel0.setText ("Amount received:");
            // create new GroupLayout for TransPanel0
            org.jdesktop.layout.GroupLayout transPanel0Layout = new org.jdesktop.layout.GroupLayout (transPanel0);
            transPanel0.setLayout (transPanel0Layout);
            // set horizontal group
            transPanel0Layout.setHorizontalGroup (
                    transPanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (org.jdesktop.layout.GroupLayout.TRAILING, transPanel0Layout.createSequentialGroup ()
                    .addContainerGap (org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add (amtRcvdLabel0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    // add amtRcvdInput0 JTextField to form
                    .add (amtRcvdInput0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 58, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add (22, 22, 22)
                    .add (paymentButton0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (cancelButton0)
                    .addContainerGap ())
            // set vertical group
            transPanel0Layout.setVerticalGroup (
                    transPanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (transPanel0Layout.createSequentialGroup ()
                    .addContainerGap ()
                    .add (transPanel0Layout.createParallelGroup (org.jdesktop.layout.GroupLayout.BASELINE)
                    .add (cancelButton0)
                    .add (paymentButton0)
                    // add amtRcvdInput0 JTextField to form
                    .add (amtRcvdInput0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add (amtRcvdLabel0))
                    .addContainerGap (org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            // setup JScrollPanel to display transaction items
            transList0.setFont (new java.awt.Font ("Tahoma", 0, 14));
            transList0.setListData (listData);
            transList0.setToolTipText ("Items entered in the current transaction");
            // specify scrollbars
            jScrollPane1.setViewportView (transList0);
            // setup the file menu
            fileMenu0.setText ("File");
            // add Export XML menu item to file menu
            exportXMLMenuItem = new JMenuItem ("Export to XML");
            exportXMLMenuItem.setToolTipText ("Export current product list to product.xml");
            fileMenu0.add (exportXMLMenuItem);
            // add menu seperator
            fileMenu0.addSeparator ();
            // add Exit menu item to file menu
            exitMenuItem = new JMenuItem ("Exit");
            exitMenuItem.setToolTipText ("Exit application");
            fileMenu0.add (exitMenuItem);
            // add the file menu to the menu bar
            menuBar0.add (fileMenu0);
            // set the menu bar to be menuBar0
            setJMenuBar (menuBar0);
            // layout remaining components onto JFrame
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout (getContentPane ());
            getContentPane ().setLayout (layout);
            // set horizontal group
            layout.setHorizontalGroup (
                    layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (layout.createSequentialGroup ()
                    .addContainerGap ()
                    .add (layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (layout.createSequentialGroup ()
                    .add (prodIDLabel0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (prodIDLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 78, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (prodNameLabel0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (prodNameLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 164, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add (layout.createSequentialGroup ()
                    .add (prodDescLabel0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (prodDescLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 725, Short.MAX_VALUE))
                    .add (layout.createSequentialGroup ()
                    .add (prodImagePanel0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE))
                    .add (layout.createSequentialGroup ()
                    .add (itemPrice0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED, 441, Short.MAX_VALUE)
                    .add (totalPrice0)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (totalPrice1))
                    .add (layout.createSequentialGroup ()
                    .add (prodPanel0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (transPanel0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addContainerGap ())
            // set vertical group
            layout.setVerticalGroup (
                    layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (layout.createSequentialGroup ()
                    .addContainerGap ()
                    .add (layout.createParallelGroup (org.jdesktop.layout.GroupLayout.BASELINE)
                    .add (prodIDLabel1)
                    .add (prodNameLabel1)
                    .add (prodNameLabel0)
                    .add (prodIDLabel0))
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (layout.createParallelGroup (org.jdesktop.layout.GroupLayout.BASELINE)
                    .add (prodDescLabel0)
                    .add (prodDescLabel1))
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE)
                    .add (prodImagePanel0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (itemPrice0)
                    .add (layout.createParallelGroup (org.jdesktop.layout.GroupLayout.BASELINE)
                    .add (totalPrice1)
                    .add (totalPrice0)))
                    .addPreferredGap (org.jdesktop.layout.LayoutStyle.RELATED)
                    .add (layout.createParallelGroup (org.jdesktop.layout.GroupLayout.LEADING)
                    .add (prodPanel0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add (transPanel0, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap ())
            // resize the frame to the minimum size needed to satisfy the preferred size of each of the components in the layout
            pack ();
        /** actionPerformed()
         *  handles events from components.
        public void actionPerformed (ActionEvent e) {
            if ( e.getSource () == findButton0 )
                guiCtl0.findButtonAction (prodIDInput0.getText (), qtyInput0.getText ());
            if ( e.getSource () == cancelButton0 )
                guiCtl0.cancelButtonAction ();
        /** showWelcomeMsg()
         *  Shows a welcome dialogue message to the user.
        public void showWelcomeMsg (){
            // Create a new dialogue box
            JOptionPane welcomeMsg = new JOptionPane ();
            // Show welcome dialogue box
            welcomeMsg.showMessageDialog (null, "Welcome to the Supermarket Management System.  Click OK to begin.", "Welcome", welcomeMsg.INFORMATION_MESSAGE);
        /** showMsg()
         *  Shows a message to the user.
        public void showErrorMsg (String s){
            // Create a new dialogue box
            JOptionPane errorMsg = new JOptionPane ();
            // Show welcome dialogue box
            errorMsg.showMessageDialog (null, s, "Message", errorMsg.ERROR_MESSAGE);
        /** set prodIDInput0 text field */
        public void setProdIDInput0 (String s){
            prodIDInput0.setText (s);
        /** set qtyInput0 text field */
        public void setQtyInput0 (String s){
            qtyInput0.setText (s);
        /** set ProdDescLabel1 label */
        public void setProdDescLabel1 (String s) {
            prodDescLabel1.setText (s);
        /** set prodIDLabel1 label */
        public void setProdIDLabel1 (String s) {
            prodIDLabel1.setText (s);
        /** set prodNameLabel1 label */
        public void setProdNameLabel1 (String s) {
            prodNameLabel1.setText (s);
        /** set totalPrice1 label */
        public void setTotalPrice1 (String s) {
            totalPrice1.setText (s);
        /** populate transList0 with latest trans info */
        public void setTransList0 (Vector v){
            transList0.setListData (v);
        /** set itemPrice0 label */
        public void setItemPrice0 (String s) {
            itemPrice0.setText (s);
        /** draw prod images onto gui */
        public void paintImage (String imagePath) {
            // get Graphics
            Graphics g = prodImagePanel0.getGraphics ();
            // draw image into prodImagePanel0
            img = null;
            try {
                img = ImageIO.read (new File (imagePath));
            } catch (IOException e) {
                System.err.println ("Caught IOException: "
                        + e.getMessage ());
            // draw the image on screen
            g.drawImage (img, 2, 2, prodImagePanel0);
        /** Change image */
        public void updateImage (String imagePath){
            // draw image into prodImagePanel0
            img = null;
            try {
                img = ImageIO.read (new File (imagePath));
            } catch (IOException e) {
                System.err.println ("Caught IOException: "
                        + e.getMessage ());
    GUIControl
    import javax.swing.*;
    import java.text.*;
    * GUIControl.java
    * The GUIControl class is responsible to perform actions requested from the GUIView class.
    * It also liaises with the TransControl and ProdControl objects to generate output to the
    * gui and handle input from the gui.
    * @author Tim
    public class GUIControl {
        // Declare object variables
        private GUIView gui;
        private ProdControl prodCtl0;
        private TransControl transCtl0;
        /** Creates a new instance of GUIControl */
        public GUIControl (ProdControl prodCtl0, TransControl transCtl0) {
            // make reference to prodCtl0, transCtl0 and gui objects
            this.prodCtl0 = prodCtl0;
            this.transCtl0 = transCtl0;
        /** Set gui view object */
        public void setGui (GUIView gui) {
            this.gui = gui;
        /** show the welcome dialouge */
        public void showWelcome (){
            // Call the showWelcomeMsg() method from gui to dispay welcome dialogue.
            gui.showWelcomeMsg ();
        /** find product */
        public Product findProd (int prodId){
            Product foundProd = prodCtl0.getProdByID (prodId);
            return foundProd;
        /** add product to transaction */
        public String addProdToTrans (int prodId, double transQuantity){
            // declare method variables
            String status = "Product not added";
            Product curProd0;
            // find prodduct by ID
            curProd0 = prodCtl0.getProdByID (prodId);
            //  1. if product exists then add a new transaction item to the transaction list.
            if (curProd0 != null) {
                // 2. check quantity is a whole number for UPC Products
                if (curProd0 instanceof UPCProd) {
                    // check if the result is a whole number
                    boolean isWhole = (Math.rint (transQuantity) == transQuantity);
                    // 3. if isWhole is false change status message.
                    if (isWhole == false) {
                        // return status as Product cannot be found.
                        status = "You must enter the quantity as a whole number for UPC products.";
                        return status;
                    } else {
                        // 4. check there is enough stock in the store
                        if (transQuantity > curProd0.getQuantity ()) {
                            // return status as there is not enough stock.
                            status = "There is currently not enough stock to fulfill this transaction.  Please reduce the quantity." ;
                            return status;
                        } else {
                        }  // end if 4.
                    }  // end if 3.
                } else {
                }  // end if 2.
                // add curProd as new transItem
                transCtl0.addTransItem (curProd0, transQuantity);
                // return status as null to notify that the Product was added.
                status = null;
                return status;
            } else {
                // return status as Product cannot be found.
                status = "Product " + prodId + " cannot be found.";
                return status;
            }  // end if 1.
        }  // end addProdToTrans method
        /** action Find button */
        public void findButtonAction (String prodId0, String quantity0){
            // status msg
            String status;
            // check prodId0 is not null
            if (prodId0.equals ("")) {
                // set status message to error and display error msg
                status = "Please enter a valid Product ID.";
                gui.showErrorMsg (status);
                // check quantity0 is not null
            } else if (quantity0.equals ("")) {
                // set status message to error and display error msg
                status = "Please enter a valid quantity.";
                gui.showErrorMsg (status);
            } else {
                // parse String values into int and double
                int prodId1 = Integer.parseInt (prodId0);
                double quantity1 = Double.parseDouble (quantity0);
                // reset prodIDInput0 and qtyInput0 text fields in the gui
                gui.setProdIDInput0 ("");
                gui.setQtyInput0 ("");
                // add trans item and return result as a string
                status = addProdToTrans (prodId1, quantity1);
                if (status == null) {
                    updateProdTransView ();
                } else {
                    // display msg to the user
                    gui.showErrorMsg (status);
                } // end if
            } // end if
        } // end findButtonAction method
        /** update product and transaction view on gui */
        public void updateProdTransView (){
            // get the last trans item added
            TransItem lastTransItem0 = transCtl0.getLastTransItem ();
            // find the product
            Product p = findProd (lastTransItem0.getId ());
            // update product info displayed in the gui
            gui.setProdIDLabel1 (Integer.toString (p.getId ()));
            gui.setProdNameLabel1 (p.getName ());
            gui.setProdDescLabel1 (p.getDescription ());
            // paint prod image
            gui.paintImage (p.getImage ());
            // update transaction info displayed in the gui
            gui.setTransList0 (transCtl0.getTransItems ());
            gui.setItemPrice0 (transCtl0.transItemPriceInfo (lastTransItem0));
            // update total transaction cost displayed in the gui
            gui.setTotalPrice1 ("$" + transCtl0.transTotal ());
        } // end updateProdTransView method
        /** action Cancel button */
        public void cancelButtonAction (){
            // cleat transaction items from transaction array list
            transCtl0.clearTrans ();
            // reset gui components
            gui.setProdIDLabel1 ("");
            gui.setProdNameLabel1 ("");
            gui.setProdDescLabel1 ("");
            gui.setTransList0 (transCtl0.getTransItems ());
            gui.setItemPrice0 ("");
            gui.setTotalPrice1 ("$0.00");
            gui.paintImage ("images/transparent.gif");
    }

    happy to include more detail if required.You've included too much detail.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.
    And don't post code generated by NetBeans. It uses the GroupLayout which is not a standard layout manager until JDK6 and a lot of people don't use JDK6 yet so we won't be able to execute you code to see whats happening.

  • Problem drawing tiled image

    I have a tiled buffred image. I have implemented caching and tiling myself i.e. the complete image (that can be as big as 100+MB) is tiled into 512x512 tiles and i am keeping them in a cache implemented as hashmap. The cache size is adjusted based on the available memory.
    My logic is that when the user scrolls the image i figure out the tiles that needed to be shown to the user and then see if i can find it in the cache, in case of a cache miss i create the tile in memory (using createCompatibleImage()). Once the tile is created i stuff it in my cache. After making sure the required tiles are available i then simply use drawImage(tile,x,y,null) to draw the tiles inside the paintComponent() method. My problem is that the tiles get drawn erratically i.e. if the viewport requires six tiles to be drawn then every so often few of the tiles do not get drawn. I have made sure that the my program does call drawImage() six times once for each tile - but it seems that despite drawImage call the actual drawing has a mind of its own.
    I do not suspect my tile creation or cachig code since when someof the tiles are not shown properly all i have to do is to move mouse over the undrawn area and the tiles appear immediately.
    My code is spread all over so it is difficult to produce all the relevant code in here, so i will give some code snippet:
    // Code for creating a new tile
    public createTile()
    GraphicsConfiguration gc = Utility.getDefaultConfiguration();
    BufferedImage overlayImage = gc.createCompatibleImage(width, height);
    int ii = 0;
    int jj = 0;
         for (int i= 0; i<width; i++){                
              for (int j=0; j<height; j++){
                   int rgb = ....;//the rgb is calculated based on some specific logic.
                   overlayImage.setRGB(ii,jj,rgb);
                   jj++;
              ii++;
              jj = 0;
    // After creating the image I then resize the image to handle zoom in/zoom out
    // using nearest neighbor interpolation. I don't suspect the resize code so
    // have not reporduce it here.
         return (resizeImage(overlayImage,newWidth,newHeight)).
    ====================================================
    // Extract of some of my paint code is given below.
    //I am not calling super.paintComponent() because i am redrawing the
    // whole screen with my tiled image.
      public void paintComponent(Graphics g)
           Graphics2D g2d = (Graphics2D)g;
         Tile[]tiles = getChosenTiles();
                   for (int i=0; i<tiles.length; i++){
                        g2d.drawImage(tiles.getImage(), tiles[i].x, tiles[i].y, null);

    Since nobody replied to the post - i had no option but to dig into the problem myself. Good thing is that I managed to find the solution.
    As it turned out my logic was as below:
    Step 1: find out the tiles that need to be shown on the viewport.
    Step 2: obtain these tiles from the cache
    Step 2a: If tiles not found in cache then create the tiles in memory.
    Step 3: for (int i=0;i<tiles.length; i++) {             
                    g2d.drawImage(tiles.getImage(), null, tiles[i].x, tiles[i].y);
    The problem was that for some reason the Java graphics drawing could not keep up with the for loop. What i did was to move the drawing logic inside Step 2. i.e. I would get a tile and then draw it immediately after getting it. In other words the logic was changed to
    Step 1: find out the tiles that need to be shown on the viewport
    Step 2:
                 for (int i=0;i<tiles.length; i++) {
                     BufferedImage image = tiles.getImage();
    if (image == null) {
    image = createTileImage(tiles[i]);
    tiles[i].setImage(image);
    g2d.drawImage(tiles[i].getImage(), null, tiles[i].x, tiles[i].y);
    This solved my problem.
    -km

  • TouchPad  Vertical-Scroll Painting Issues

    I have yet to reproduce the problem myself but I am getting
    reports of a painting issue on some laptops. Apparently, using the
    touch pad vertical scroll option on some (not mine unfortunately)
    laptops causes the contents of the flash player to paint outside of
    the player boundaries. The code is written in AS3 and is targeted
    for the Flash 9 player.
    The code implements a very basic FLVPlayback (skin on top)
    that sits behind a button and a static image in layers on the stage
    until the button is clicked. When clicked, the static image and
    button have their visible property set to false and the video is
    played. The painting problem happens when the static image is
    displayed and when the video is playing.
    Since I’m having no luck finding complaints of this
    problem after much searching, I can only assume that I have done
    something wrong in my implementation and being new to Flash it is
    the most likely scenario. Any suggestions on what I could be doing
    wrong?

    I got better response on my w520 by installing "Two finger Scroll" from here:
    https://code.google.com/p/two-finger-scroll/
    A LifeHacker post that turned up about the software:
    http://lifehacker.com/5493849/get-mac+like-scrolling-and-gestures-on-a-windows-laptop
    ...and it's helpful on my machine. For example, I often increase the size of font display in web text-heavy articles with CTRL-(two fingers up). I have no idea of its effect on a w530 but pull a Restore Point first and try it. Bail if bogus on that model.
    Pretty lame help from the techs.
    BTW, you can search here with that sw name because I heard about it in this forum and if there are negatives they woud have been discussed back in late 2011, early 2012 when I was looking into this. Good luck.
    4276-37U -- W520. Still have an X61t. First laptop in my house was an Osborne! Now that was a cool computer. (...for its time!)

  • Tiled Image - JViewport?

    HELP wimper
    I want to create a large tiled image that you only see a 302x128 section of that can be scrolled to see different sections 'a la' ye old 2D commadore 64 games like paradroid.
    I would be EXTREMELY grateful if any of you wonderous people out there could point me in the best direction. I am quite new to Object Oriented programming and have been directed towards the JViewport class, but other tutorials on the net use g.drawImage... to limited success. (http://userpages.umbc.edu/~enorth1/tilemapper/tile.htm).
    I realise that to you Java gurus this request probally seems extremely dippy, but I have reached desperation point looking for a place to start from.
    Thanks in advance,
    Simon Engledew - a very stuck newbie.

    You can create an extension of the JPanel class and override the paintComponent() method to draw your graphics. If you implement the Scrollable interface, you will be able to interact with a JScrollPane or, if you are adventurous, a standalone JViewport.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • Server goes out of memory when annotating TIFF File. Help with Tiled Images

    I am new to JAI and have a problem with the system going out of memory
    Objective:
    1)Load up a TIFF file (each approx 5- 8 MB when compressed with CCITT.6 compression)
    2)Annotate image (consider it as a simple drawString with the Graphics2D object of the RenderedImage)
    3)Send it to the servlet outputStream
    Problem:
    Server goes out of memory when 5 threads try to access it concurrently
    Runtime conditions:
    VM param set to -Xmx1024m
    Observation
    Writing the files takes a lot of time when compared to reading the files
    Some more information
    1)I need to do the annotating at a pre-defined specific positions on the images(ex: in the first quadrant, or may be in the second quadrant).
    2)I know that using the TiledImage class its possible to load up a portion of the image and process it.
    Things I need help with:
    I do not know how to send the whole file back to servlet output stream after annotating a tile of the image.
    If write the tiled image back to a file, or to the outputstream, it gives me only the portion of the tile I read in and watermarked, not the whole image file
    I have attached the code I use when I load up the whole image
    Could somebody please help with the TiledImage solution?
    Thx
    public void annotateFile(File file, String wText, OutputStream out, AnnotationParameter param) throws Throwable {
    ImageReader imgReader = null;
    ImageWriter imgWriter = null;
    TiledImage in_image = null, out_image = null;
    IIOMetadata metadata = null;
    ImageOutputStream ios = null;
    try {
    Iterator readIter = ImageIO.getImageReadersBySuffix("tif");
    imgReader = (ImageReader) readIter.next();
    imgReader.setInput(ImageIO.createImageInputStream(file));
    metadata = imgReader.getImageMetadata(0);
    in_image = new TiledImage(JAI.create("fileload", file.getPath()), true);
    System.out.println("Image Read!");
    Annotater annotater = new Annotater(in_image);
    out_image = annotater.annotate(wText, param);
    Iterator writeIter = ImageIO.getImageWritersBySuffix("tif");
    if (writeIter.hasNext()) {
    imgWriter = (ImageWriter) writeIter.next();
    ios = ImageIO.createImageOutputStream(out);
    imgWriter.setOutput(ios);
    ImageWriteParam iwparam = imgWriter.getDefaultWriteParam();
    if (iwparam instanceof TIFFImageWriteParam) {
    iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    TIFFDirectory dir = (TIFFDirectory) out_image.getProperty("tiff_directory");
    double compressionParam = dir.getFieldAsDouble(BaselineTIFFTagSet.TAG_COMPRESSION);
    setTIFFCompression(iwparam, (int) compressionParam);
    else {
    iwparam.setCompressionMode(ImageWriteParam.MODE_COPY_FROM_METADATA);
    System.out.println("Trying to write Image ....");
    imgWriter.write(null, new IIOImage(out_image, null, metadata), iwparam);
    System.out.println("Image written....");
    finally {
    if (imgWriter != null)
    imgWriter.dispose();
    if (imgReader != null)
    imgReader.dispose();
    if (ios != null) {
    ios.flush();
    ios.close();
    }

    user8684061 wrote:
    U are right, SGA is too large for my server.
    I guess oracle set SGA automaticlly while i choose default installion , but ,why SGA would be so big? Is oracle not smart enough ?Default database configuration is going to reserve 40% of physical memory for SGA for an instance, which you as a user can always change. I don't see anything wrong with that to say Oracle is not smart.
    If i don't disincrease SGA, but increase max-shm-memory, would it work?This needs support from the CPU architecture (32 bit or 64 bit) and the kernel as well. Read more about the huge pages.

  • CS6 creates tiled image when moving from LR4 and HDR Effex Pro

    Just recently I've had a problem with CS6 where it creates a partial (tiled) image when "Edit In" from LR4 and when saving back to CS6 from HDR Effex Pro. THe image may have one or several retangles which may be black, white, or part of the image that's in the wrong place if that makes any sense. All software is running with current updates. I've had the software about 6 months and never incurred this problem until the last week. Help!

    I've run through several scenarios and find that it's always in CS6 that I have the problem. I opened a file in all modules of Nik as well as OnOne's Perfect Photo Suite. When I go back (save) to CS6 there is always a problem. When I save in CS6 and then open up in LR the image is fine. So the file must not be corrupt, it just doesn't present it properly in CS6. The GPU driver appears to be up to date....last update was in 2011 and I've had this computer since late 2012.

  • Selecting Tiled Images then Displaying the image

    I am looking for a good way to display a collection of images (jpg) tiled in a pane, then the user can click on one of the tiled images, and then the selected tiled image will then be displayed full size in a seperate pane.
    Before, I have done this by having buttons in a grid layout, and setting the button's ImageIcon in order to produce the tiled images. Then it is easy to implement the 'user clicks on tiled image, then image is displayed '.
    I am wondering if there is a better way to do this. Your help is much appreciated!

    Before, I have done this by having buttons in a grid layout, and setting the button's ImageIcon in order to produce the tiled images. Then it is easy to implement the 'user clicks on tiled image, then image is displayed '.Sounds good to me.

  • Loading images using Microsoft Paint

    Is there a way to make a servlet load an image using Microsoft Paint (on Windows) ?
    I have a huge image that does not fit in the browser window and the client would like to see it without scrolling. .. and prefers to have this opened in Microsoft Paint. Scaling an image using widht/height is not preferred.
    We can set the MIME type to image/gif for example... but, how can we tell the browser to load using a particular image-editing applciation?
    Thank you.

    Thanks for your response. It might work for bitmap images.
    But my images are gifs and jpgegs.... I forgot to mention this in the initial post. Sorry about that.
    I was looking for something like "application/mspaint" for the contentType rather than image/bmp

  • How can I put an image of a painting centered on to a blank 4x6 postcard?

    How can I put an image of a painting centered on to a blank 4x6 postcard?

    moopartist wrote:
    How can I put an image of a painting centered on to a blank 4x6 postcard?
    Go to File>new>blank file. Enter the dimensions, background color to suit. For resolution, it's best to have the same value as that of the image. For printing, it is desirable to have the resolution in the 240-300px/in range, although I have printed below this range.
    Open the file with the painting. Use one of the selection tools, e.g. selection brush, lasso tool, and select the image.
    Go to Edit>copy
    Open the blank file
    Go to Edit>paste. The selection will come in on its own layer
    Use the move tool to position, and, to resize (if necessary) with the corner handles of the bounding box.

  • Tiling image within infinitely vertically expandable rounded box

    I would like to place a 1px high image within a round box which will expand inifnitely in a dynamic ecommerce site. I know how to create a div for the header (ie rounded box, roundedbox h1) and place the top part, then the rest in the main div with the bottom of the rounded box positioned at "bottom." However, there are physical limitations to this method; it seems it would be ideal to place a tiled image to complete everything within the top and bottom portions; the problem is that it appears at the top no matter how it's placed. Is there any way to specify a margin for the background image only?
    Incidentally, I hate the look of this new forum. Why everyone wants to jump on the Facebook wagon is beyond me...

    Hi Murray; for example, I crop the top 60px of the rounded box and make it the background for the #body_content h1 div, then use the bottom rounded remains of the box and make it the background image for the #body_content div. The problem is that without sufficient content, the cropped body bg image shows at the top of the div; whereas if there is too much, a blank space will occur between the two. I'd like to think there is a way to insert a third div with a 1 px high tiled image but someho give it a 60px margin at both top and bottom to prevent overlapping...
    #body_content {
    margin-left: 20px;
    background-image: url(../../../Images/maincontent_bg_footer.gif);
    background-repeat: no-repeat;
    background-position: left bottom;
    width: 820px;
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 20px;
    padding: 0px;
    #body_content h1 {
    background-image: url(../../../Images/maincontent_bg_heading.gif);
    background-repeat: no-repeat;
    height: 60px;
    margin: 0px;
    padding: 0px;

  • Painting issue with swing titlebar

    Hi,
    I had already posted this but no body replied so I am posting it again hoping somebody might reply to this now.
    In my swing application I wanted a custom titlebar, so I created my own RootPaneUI by taking most of the code from MetalRootPaneUI to get what I wanted.
    In order to make my titlebar visible I had to call:
    frame.setUndecorated(true);
    frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
    The major issue I am facing now which sounds very weird to me is with the painting of the window. When I start the application sometimes (not always), I see the frame being stuck to the top left corner of the monitor, when I move the mouse over the toolbar/menubar, the frame starts painting the icons of underlying IDE like eclipse or IntelliJ over my application. It seems like a painting issue which is really a very strange behaviour.
    This issue does not happen with windowslookandfeel and also works fine for MetalLookAndFeel when the JFrame is decorated to show window decorations(windows titlebar) not the look and feel one(custom titlebar).
    I wanted to know if its me who is doing something wrong or is it a swing bug. Is there a way to fix this issue. I searched a number of forums but couldn't find an answer to it.
    Thanks in advance.

    Hello @Andre_Uhres:
    In my application, I am using swing application framework (JSR 296) and I have a splash screen(JFrame) which loads some configuration data and then shows a modal login dialog on top of it. On successful login the login dialog and splash is disposed and the main application frame shows up.
    The job of showing splash screen and logging in the application was being done in the main/initial thread. I apolgoize for not being able to provide a sample runnable code because the issue is seen only with my application and not with any other demo programs and it was not quite possible for me to put that huge code here.
    public static void main(String args[])
    SplashFrame.start();
    //Launch the main application
    Application.launch(ApplicationMain.class); // swing application framework would launch the frame in the invokeLater method.
    class SplashFrame
       public void start()
            // create a splash and show it
           // load the configurations
           // show login dialog
           // on successful login dispose splash and login
    }I eventually moved this code into SwingUtilities.invokeLater() but even this didn't help me. I still see the same issue.
    public static void main(String args[])
    // or use invokeAndWait
    SwingUtilities.invokeLater(new Runnable(){
    SplashFrame.start();
    //Launch the main application
    Application.launch(ApplicationMain.class); // swing application framework would launch the frame in the invokeLater method.
    }I also tried doing this:
      RepaintManager.setCurrentManager(new RepaintManager()); as I read in some forums that sometimes RepaintManager might need to be overwritten to resolve some painting issues.
    FYI: I am using JDK 1.6.0_17
    In spite all these, I still see the same issue. Any help much appreciated.
    Thanks

  • Photoshop CS4 3d painting issues.

    Hello!
    I am using Photoshop CS4 Extended. I have imported a 3D image and am trying to paint onto it. I have watched a ton of videos and read a bunch of forums. Once I put even a dot of paint on my object, the whole 3D image is covered in paint. Does anyone have any ideas what the issue is?
    Thanks!

    Could You post the file (provided it’s not too big) or at least a screenshot of the 3D (Materials)-Panel with some of the problematic Material selected?

  • 3d painting issue - why is my selected value showing up different then the actual color I'm picking?

    Love the CS5's 3d painting features but I'm running into a really frustrating issue:
    When I select a value from the 3d object and try to paint with that value, it's showing up as a different value altogether (the image hopefully illustrates this much better than words).
    Not sure if it's got something to do the the lights setup or something else but I cannot figure it out.  Anyone else running into this or have a solution?
    Thanks!!!

    Ok, let me try to be explain the issue in more detail.
    Note: 
    All 3D layer settings are default.  No lights, ambient color setting, etc have been tweaked.
    Description:
    In order to paint out texture seams on a 3d character model, I have imported an .obj of the model into PS CS5 and applied a texture map to it which I have previously painted.
    Using the eye dropper I have selected a color value from the sides of the seam and have attempted to paint that value over the seam to remove it.
    Results:
    The color value picked from a texture applied to a 3d model which is 161,161,173, is not the same color value when painted directly back onto the model. It has now mysteriously turned into 152,152,177.
    Expected results:
    When a color value is picked from a texture applied to a 3d model (161,161,173) and painted back onto the textured model it should remain exactly the same (161,161,173)
    I hope lighting/shading is not figured in when color picking.  That would make your results completely unpredictable.  It could possibly be what is happening but is there a way turn this off or work around it?
    Thanks for the help.

  • Reloading and redisplay images on JScrollPane

    I am using
    Java platform:jdk 1.4.1
    Windows platform: Windows 98se
    Problem:I am making one application in which i need to display images when i get
    it from socket.I had used one JScrollPane over JPanel with scrollbars.But when i get the image i stored it into an Image object.
    such as in my main program
    screen = Toolkit.getDefaultToolkit().getImage ( "screen.jpg" );
    //Draw picture first time it works fine...
    paintPicture(screen);
    paintPicture(Image image)
         {picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
            image = Toolkit.getDefaultToolkit(  ).getImage(image);
    //Is picpnl is unable to display image second time       
          picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
            c.add( picpnl, BorderLayout.CENTER );
            picpnl.setVisible(true);
    from my refresh code:
           if(image!=null)
              image.flush();
           Runtime rt = Runtime.getRuntime();
           rt.runFinalization();
           rt.gc();
           image = null;
    //is this 2nd time image not properly stored in variable image
           image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );
           paintPicture(image);
    //go to paintPicture second time doesn't work
    class ImageComponent extends JComponent {
      Image image;
      Dimension size;
      public ImageComponent(Image image) {
        this.image = image;
        MediaTracker mt = new MediaTracker(this);
        mt.addImage(image, 0);
        try {
          mt.waitForAll(  );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
    The above code works fine for (the first time).But when i try to display a different socket image (the second time) it doesn't work.
    I didn't know what the problem is...
    ---whether the previous image didn't get erased from RAM or
    ---the OS is not aware of the current changed image in variable (image) or the
    ---JScrollPane is unable to redraw it second time.
    How can i display one changed image from the socket onto the JScrollPane? (the second time).
    Also i want to know if we are using one file with the name "screen.jpg" and at runtime if i changed that file with another file with the same name. How can i display that changed file?Is it possible in Java or not.(Is it the limitation of Java).
    I totally get frustated by reading all forums but i didn't get the answer.Please reply me soon with the complete code?
    The complete source code for the problem:
    (SERVER):
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.text.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Remote extends JFrame
    private JPanel btnpnl,picpnl;
    private JButton button[];
    private UIManager.LookAndFeelInfo looks[];
    private static int change = 1;
    private JLabel label1;
    private Icon icon[];
    private String names[] = { "looks","connect","control", "refresh", "auto",    "commands" };
    private String iconnames[] = { "gifs/look.gif","gifs/connect.gif","gifs/control.gif","gifs/refresh.gif","gifs/auto.gif","gifs/command.gif" };
    private String looknames[] = { "Motif", "Windows", "Metal" };
    private int port=5000;
    private ScrollablePicture picture=null;
    private ServerSocket server;
    private Socket client;
    private ObjectInputStream ins = null;
    private ObjectOutputStream ous = null;
    private File file;
    private String fileName;
    private boolean autocontrol=true;
    private Image image=null;
    private Container c;
         public remote()
              super( "Remote Desktop" );
    c = getContentPane();
              c.setLayout( new BorderLayout() );
    //String file = "screen.jpg";
    looks = UIManager.getInstalledLookAndFeels();
              btnpnl = new JPanel();
              btnpnl.setLayout( new FlowLayout() );
              button = new JButton[names.length];
              icon = new ImageIcon[iconnames.length];
              Buttonhandler handler = new Buttonhandler();
              for( int i=0; i<names.length; ++i )
    icon[i] = new ImageIcon( iconnames[i] );
                   button[i] = new JButton( names, icon[i] );
                   button[i].addActionListener(handler);
    btnpnl.add(button[i]);
              c.add( btnpnl, BorderLayout.NORTH );
              //Adding Label1
              label1 = new JLabel("LABEL1");
              c.add( label1, BorderLayout.SOUTH );
    picpnl = new JPanel();
         picpnl.setLayout(new BorderLayout());
              //image = Toolkit.getDefaultToolkit( ).getImage(file);
    // paintPicture(image);
              c.add( picpnl, BorderLayout.CENTER );
              //setResizable(false);
              setSize( 808, 640 );
              show();
    public void paintPicture(Image image)
    picpnl.add(new JScrollPane(new ImageComponent(image)),BorderLayout.CENTER);
    picpnl.setVisible(true);
    public class Buttonhandler implements ActionListener
              public void actionPerformed( ActionEvent e )
    try{
                   if( e.getActionCommand() == "looks" )
    try
                   label1.setText( Integer.toString( change ) );
              UIManager.setLookAndFeel( looks[change++].getClassName() );
                        SwingUtilities.updateComponentTreeUI(remote.this);
                   if(change==3)
                        change=0;
    catch (Exception ex)
    ex.printStackTrace();
                   if( e.getActionCommand() == "connect" )
                        label1.setText( "connect" );
    runServer();
                   if( e.getActionCommand() == "refresh" )
                        label1.setText( "refresh" );
                        ous.writeObject("refresh");
                        ous.flush();
                        recieveFile();
                   if( e.getActionCommand() == "auto" )
                        label1.setText( "auto" );
                        ous.writeObject("auto");
                        button[4].setText("stop");
                        ous.flush();
                        setButton(false,false,false,false,true,false);
                   auto();
                   if( e.getActionCommand() == "stop" )
                        ous.writeObject("stop");
                        ous.flush();
                        button[4].setText("auto");
                        setButton(true,true,true,true,true,true);
                   autocontrol=false;
              catch(Exception ef)
                   ef.getMessage();
         public void auto()
              while(autocontrol)
    recieveFile();
         public void setButton( boolean b1, boolean b2, boolean b3, boolean b4, boolean b5, boolean b6)
              button[0].setEnabled(b1);
              button[1].setEnabled(b2);
              button[2].setEnabled(b3);
              button[3].setEnabled(b4);
              button[4].setEnabled(b5);
              button[5].setEnabled(b6);
         public void recieveFile()
         int flag = 0;
              try{
                   while(flag<=2){
                   Object recieved = ins.readObject();
                   System.out.println("from client:" + recieved);
    switch (flag) {
    case 0:
    if (recieved.equals("sot")) {
    System.out.println("sot recieved");
                                       flag++;
    break;
                   case 1:
    fileName = (String) recieved;
    file = new File(fileName);
                                  System.out.println("fileName received");
                                  flag++;
    break;
                   case 2:
                   if (file.exists())
                        file.delete();
                   byte[] b = (byte[])recieved;
                   FileOutputStream ff = new FileOutputStream(fileName);
    ff.write(b);
    flag = 3;
    if(image!=null)
                             image.flush();
                                                                Runtime rt = Runtime.getRuntime();
                   rt.runFinalization();
                   rt.gc();
                   image = null;
              Image = Toolkit.getDefaultToolkit().createImage( b ,0, b.length );          
                        paintPicture(image);
    break;
              catch(Exception e)
                   e.printStackTrace();
    class ImageComponent extends JComponent {
    Image image;
    Dimension size;
    public ImageComponent(Image image) {
    this.image = image;
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
    mt.waitForAll( );
    catch (InterruptedException e) {
    // error ...
    size = new Dimension (image.getWidth(null),
    image.getHeight(null));
    setSize(size);}
    public void paint(Graphics g) {
         g.drawImage(image, 0, 0, this);
    public Dimension getPreferredSize( ) {
    return size;
         public void runServer()
         try{
                   server = new ServerSocket(port);
                   client = server.accept();
    JOptionPane.showMessageDialog(null,"Connected");
                   System.out.println("connection received from" + client.getInetAddress().getHostName());
                   ous = new ObjectOutputStream( client.getOutputStream() );
    ous.flush();
                   ins = new ObjectInputStream( client.getInputStream() );
                   System.out.println("get i/o streams");
              catch(Exception e)
                   e.printStackTrace();
         public static void main(String[] args)
         remote app = new remote();
         app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    CLIENT code:
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class Client extends JFrame
    private JLabel label1;
    private JButton button1;
    private Socket server;
    private ObjectInputStream ins=null;
    private ObjectOutputStream ous=null;
    private File file;
    private boolean autocontrol=true;     
    public Client()
         super("Client");
         Container c = getContentPane();
         ButtonHandler handler = new ButtonHandler();
         c.setLayout( new FlowLayout() );
         label1 = new JLabel("");
         button1 = new JButton("connect");
         c.add(label1);
         c.add(button1);
         button1.addActionListener(handler);
         setSize(300,300);
         show();
    class ButtonHandler implements ActionListener
         public void actionPerformed(ActionEvent e)
         if(e.getActionCommand()=="connect")
                   runClient();
    public void runClient()
         try{     
              server = new Socket(InetAddress.getByName("127.0.0.1"),5000);
    System.out.println("connected to" + server.getInetAddress().getHostName());
              ous = new ObjectOutputStream(server.getOutputStream());
         ous.flush();
              ins = new ObjectInputStream(server.getInputStream());
              System.out.println("get i/o streams");
                   file = new File("screen.jpg");
              listencommands();
         }catch(Exception e)
              e.getMessage();
    public void listencommands()
         try
              while(true){
              Object message = ins.readObject();
         if(message.equals("refresh"))
                   screenshot();
                   sendFile(file);
         if(message.equals("auto"))
                   autocontrol=true;
                   while(autocontrol)
                        screenshot();
                        sendFile(file);
    if(message.equals("stop"))
                   autocontrol = false;
         catch(Exception e)
              e.printStackTrace();
    public void sendFile( File file ) throws IOException
         try{     
              System.out.println("Ready to send file");
              ous.writeObject("sot");
    ous.flush();
    System.out.println("sot send");
              ous.writeObject("screen.jpg");
              ous.flush();
    System.out.println("fileName send");
              FileInputStream f = new FileInputStream (file);
    System.out.println("fileinputstream received");
              int size = f.available();
    byte array[] = new byte[size];
    f.read(array,0,size);
              System.out.println("Declared array");               
                        //ous.write(size);
                        //ous.flush();
              ous.writeObject(array);
    ous.flush();
              System.out.println("image send");
              catch (Exception e)
                   System.out.println(e.getMessage());
    public void screenshot()
    try
         //Get the screen size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
         Rectangle rectangle = new Rectangle(0, 0, screenSize.width, screenSize.height);
    Robot robot = new Robot();     
         BufferedImage image = robot.createScreenCapture(rectangle);
         File file;
    //Save the screenshot as a jpg
         file = new File("screen.jpg");
         ImageIO.write(image, "jpg", file);
    catch (Exception e)
         System.out.println(e.getMessage());
    public static void main( String args[] )
              Client app = new Client();
    app.addWindowListener(
              new WindowAdapter(){
                        public void windowClosing( WindowEvent e )
                             System.exit( 0 );
    Steps to run code:
    if everything goes fine:
    1.Run the server.
    2.Run the client.
    3.Press connect button on server.
    4.Press connect on client.
    5.You get a Message box "Connected".
    6.Press refresh button on Server.
    7.You get the first image.
    8.Press refresh button on Server.
    9.You are not going to get anything but the same image.....this is where the problem begins to display that second changed image screenshot.

    This is a Swing related question and you've already posted this question in the Swing forum.
    Don't clutter the forum by posting the same question in 3 different forums.

Maybe you are looking for

  • HP ENVY m6 Notebook PC overheats several times per day

    My laptop overheats and crashes CONSTANTLY-several times per day!  I have vacuumed all of the vents in back, I took it to the Geek Squad, who sold me a chill pad that helps minimally, I have started putting ice packs on the lower left corner, I don't

  • Equium A100-306 Is the monitor out on the side the same as a DVI out?

    Hello i was wondering is the monitor out on the side of my laptop the same as a DVI output? I am looking to connect my laptop to my hd tv, what is the best way? Can i use some sort of HDMI cable? Like a DVI to HDMI cable? Or is there a special cable

  • How to define a part of subnet in ACL?

    Is it possible to define only this range of hosts: 192.168.80.200-254 /24 in standard ACL without entering each host per line? Thank you. ip access-list standard PAT permit 192.168.80.200 permit 192.168.80.201 permit 192.168.80.254 Any other ways?

  • To find allocation type in tablespaces

    Hi, I need to find whether my tablespaces allocation type is automatic. Could anyone please assist me with a query?

  • Actionscript 1 in Flash CS 5

    Hi,   I have been given the "opportunity" of working with a Flash application using AS 1.  The big however, besides being new to Flash, is that I have also been provided with CS 5 to use as development tool.  The question I have is will this work or