Gif in a JPanel

How to make a gif file be displayed in a JPanel?

The easiest way is use ImageIcon to get the image and then put that imageicon on a label and then put label on a panel.

Similar Messages

  • ANuB figures out how == overlap transparent gif in a JPanel!

    I have to say I have a hate/love realtionship with this forum. Sorry if I ofend but I know it's hard sometimes to get an answer for help as it is purely voluntary. But I've asked help for this a bazillion times and help has been min to null, but I want to say I'm hoping to post something to help someone how to figure out how to Overlap a transparent image or transparent gif over another in a custom JPanel and display it when an action is called. (action called code to follow soon in another forum)
    import java.awt.*;                                                                                          //     import extension packages
    import javax.swing.*;
    * <strong>TransparentImageExample</strong> -- drawing a transparent
    * image on top of a background image.
    public class PizzaImage extends JPanel
         private Icon     icnPizza,
                             icnLoaded,
                             icnSausage,
                             icnPepp,
                             icnOnion,
                             icnGrPep,
                             icnMush,
                             icnOlive,
                             icnGarlic,
                             icnPineApp,
                             icnSpinach;
         private Color bgColor;
         public void paintComponent( Graphics g )
              super.paintComponent( g );
              bgColor = new Color( 255, 235, 160 );
              this.setBackground( bgColor );
              icnPizza = new ImageIcon( "pzaThin.gif" );
              icnLoaded = new ImageIcon( "icnLoaded.gif" );
              icnSausage = new ImageIcon( "topSausage.gif" );
              icnPepp = new ImageIcon( "topPepp.gif" );
              icnOnion = new ImageIcon( "topOnion.gif" );
              icnGrPep = new ImageIcon( "topGrPep.gif" );
              icnMush = new ImageIcon( "topMush.gif" );
              icnOlive = new ImageIcon( "topOlives.gif" );
              icnGarlic = new ImageIcon( "topGarlic.gif" );
              //icnPineApp = new ImageIcon( "topPineApp.gif" );
              //icnSpinach = new ImageIcon( "icnLoaded.gif" );
              icnPizza.paintIcon( this, g, 0, 0 );
              icnSausage.paintIcon( this, g, 0, 0 );
              icnPepp.paintIcon( this, g, 0, 0 );
              icnOnion.paintIcon( this, g, 0, 0 );
              icnGrPep.paintIcon( this, g, 0, 0 );
              icnMush.paintIcon( this, g, 0, 0 );
              icnOlive.paintIcon( this, g, 0, 0 );
              icnGarlic.paintIcon( this, g, 0, 0 );
         public void draw()
              repaint();
    so just import the above code in a class fime which extends JPanel and display the PizzaImage objVariable  = new PizzaImage() in the component of your choice.
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    You guys are right about setting the background color outside of the paint method. I was more pre-occupied with trying to overlap the images. So now I have it set. NOW I need to draw each item when it is selected with a JCheckBox and I can't think of a good way to do that. Is there a way to undraw an image? I suppose I've gone too long w/o sleep. Here's what I have.
    // this code is in another class file
    private class chkBoxHandler implements ItemListener
              public void itemStateChanged( ItemEvent e )
                   for( int i = 0; i < chkBoxName.length; i++ )
                        if( e.getSource() == toppingChk[ i ] )     
                             if( e.getStateChange() == ItemEvent.SELECTED )
                                  pzaImage.setImage( i );
                                  pzaImage.draw();
                             if( e.getStateChange() != ItemEvent.SELECTED )
                                  JOptionPane.showMessageDialog( null, "Button Unselected",     //     displays a message
                                       "About MyPizzeria", JOptionPane.PLAIN_MESSAGE );          //     code to "undraw" the image will go here
    import java.awt.*;     
    import javax.swing.*;
    public class PizzaImage extends JPanel
         int     thisImgNum = -1;
         Icon pzaThin, icnLoaded;
         public String imgName[] = {     "topSausage.gif",
                                            "topPepp.gif",
                                            "topOnion.gif",
                                            "topGrPep.gif",
                                            "topMush.gif",
                                            "topOlives.gif",
                                            "topGarlic.gif",
                                            "topPine.gif",
                                            "topSpinach.gif"
         public Icon topping[] = {     new ImageIcon ( imgName[ 0 ] ),
                                            new ImageIcon ( imgName[ 1 ] ),
                                            new ImageIcon ( imgName[ 2 ] ),
                                            new ImageIcon ( imgName[ 3 ] ),
                                            new ImageIcon ( imgName[ 4 ] ),
                                            new ImageIcon ( imgName[ 5 ] ),
                                            new ImageIcon ( imgName[ 6 ] ),
                                            new ImageIcon ( imgName[ 7 ] ),
                                            new ImageIcon ( imgName[ 8 ] )
         private Color bgColor;
         public PizzaImage()
              setBackground(new Color(255, 235, 160));                         
              pzaThin = new ImageIcon( "pzaThin.gif" );                         
              icnLoaded = new ImageIcon( "icnLoaded.gif" );                    
         public void setImage( int img )                                             
              thisImgNum = img;                                                       
         public void paintComponent( Graphics g )                              
              super.paintComponent( g );
              pzaThin.paintIcon( this, g, 0, 0 );                                   
              if( thisImgNum == 0 )
                   topping[ 0 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 1 )
                   topping[ 1 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 2 )
                   topping[ 2 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 3 )
                   topping[ 3 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 4 )
                   topping[ 4 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 5 )
                   topping[ 5 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 6 )
                   topping[ 6 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 7 )
                   topping[ 7 ].paintIcon( this, g, 0, 0 );
              if( thisImgNum == 8 )
                   topping[ 8 ].paintIcon( this, g, 0, 0 );
         public void draw()
              repaint();
    }

  • Animated .gif in JPanel

    Hello,
    I'm trying to render an animated .gif in a JPanel. I'm overriding paintComponent as follows:
       public void paintComponent(Graphics g)
          super.paintComponent(g);
          // center the background image.
          //backgroundImage is an Image
          if (backgroundImage != null)
             g.drawImage(backgroundImage, (this.getWidth() - backgroundImage
                   .getWidth(this)) / 2, (this.getHeight() - backgroundImage
                   .getHeight(this)) / 2, this);
       }The problem: I'm only getting the first frame displayed. What do I need to do to properly display the animated image?
    Thanks.
    Marc

    Adding a JLabel is not convenient, nor is it the proper way to do it. The panel has other components and coming up with a layout manager that will overlay components is not the proper thing to do.
    Creating a Thread is also not the proper thing to do.
    I found a solution that works fine. Instead of using an Image, I create an ImageIcon and use that to display the animated gif.
       public void paintComponent(Graphics g)
          super.paintComponent(g);
          // center the background image.
          // backgroundImage is an ImageIcon
          if (backgroundImage != null)
             g.drawImage(backgroundImage.getImage(), (this.getWidth() - backgroundImage
                   .getIconWidth()) / 2, (this.getHeight() - backgroundImage
                   .getIconHeight()) / 2, this);
       }Thanks for your help.

  • Trying to add an icon to a JPanel!

    After declaring the icon w/ :
    ImageIcon icon = new ImageIcon("logo2.gif");
    and the JPanel is added to the content pane, the error I am recieving is w/ this peice of code: jPanel1.add(icon);
    The error is: cannot reslove symbol, jPanel1.add(icon);
    ^
    I'm nit sure what the deal is...

    Here is some working code.You just have to center and resize the image.
    JFrame frame = new JFrame();
        frame.setSize(800,600);
        JLabel jLabel1 = new javax.swing.JLabel();
        JPanel jPanel1 = new javax.swing.JPanel();
        frame.getContentPane().setLayout(new javax.swing.BoxLayout(frame.getContentPane(), javax.swing.BoxLayout.X_AXIS));
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
          public void windowClosing(java.awt.event.WindowEvent evt) {
        jLabel1.setText("DMV Icon");
        ImageIcon icon = new ImageIcon("logo2.gif");
        frame.getContentPane().add(jLabel1);
        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setMaximumSize(new java.awt.Dimension(120, 90));
        jPanel1.setMinimumSize(new java.awt.Dimension(120, 90));
        jPanel1.setPreferredSize(new java.awt.Dimension(120, 90));
        JLabel l = new JLabel();
        l.setIcon(icon);
        jPanel1.add(l);
        jPanel1.setBackground(Color.red);
        frame.getContentPane().add(jPanel1);
        frame.show();Hope this helps.

  • Interactive map display

    Hello. I've a small problem if anyone can help... As part of an ongoing project I'm trying to create a GPS interfacing program that talks via the serial port to retrieve stored GPS reference data stored on aGPS device. This data will then be converted and displayed on an image of a map (such as one would get from multimap or similar) in 'breadcrumb' form (each spot will appear on the particular road (derived from processing the co-ordinates)) whereby then each breadcrumb can then be clicked on and specifics will be displayed (such as the speed, direction etc.)
    My problem, however, is how to create the 'interactive' map. Everything else works in the backend;I just can't seem to figure out how to do this bit! I'm currently holding the map image (images/map.gif) in a JPanel. The nodes are created in a class called GPSNode. The communications are done through the classes GPSController(the main class), GPSDataInterface(the interface for the data - the GPS returns an unformatted string), GPSDataUnit(calculates the information for the node), PortOpen and a few exception classes.
    Cheers,
    Al Sweetman.

    The interaction process should be as follows:
    1. User clicks on JPanel
    2. MouseEvent tells you where they clicked (x,y)
    3. Cross reference the location with the information aquired from the serial port.
    The key is to filter out all useless information based on where the user clicks (x,y). Then translate the useful information back to the graphical surface.

  • Queue/Array into JTable

    Hi, I am reading some data from a database and I have got it stored locally inside a queue. What i want to do is read in the queue (already got a mehtod for this) but then add each object in the queue, into a row in my JTable. also I want to be able to delete a row of a jtable when i am finished with it. any help very much apprecaited. all i have got so far is declaring the JTable and jscrollpane etc. i sint too crash hot on swing so you might have to make it obvious. thanks.

    Right, I seem to have got myself into a mess with this. i dont think i'm too far off though. if i get this bit then i should have cracked it. I am getting a null pointer exception as i try to enter my first string into the TableModel. PS Its a bit of a hashed together attempt so any tips of how to improve the class generally, greatly appreciated.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ProtocolGUI extends JPanel implements ActionListener
              private JPanel menuPanel;
              private JMenuBar menuBar;
            private JMenu fileMenu;
            private JMenu helpMenu;
              private JMenuItem startMon;
             private JMenuItem exitItem;
            private JMenuItem about;
            private JTabbedPane tabbedPane;
              private JPanel graphicsPanel;
              private JPanel textPanel;
            private JTable pclTable;
         public ProtocolGUI()
            super(new BorderLayout());
            menuBar = new JMenuBar();
            fileMenu = new JMenu("File");
            helpMenu = new JMenu("Help");
            startMon = new JMenuItem("Start");
             exitItem = new JMenuItem("Exit");
            about = new JMenu("About");
            menuPanel= new JPanel();
            menuPanel.setLayout(new BorderLayout());
            this.add(menuPanel, BorderLayout.NORTH);
            exitItem.addActionListener(this);
            fileMenu.add(startMon);
            fileMenu.add(exitItem);
            helpMenu.add(about);
            menuBar.add(fileMenu);
            menuBar.add(helpMenu);
            menuPanel.add(menuBar, BorderLayout.NORTH);
              ///////////end of menu///////////////
            tabbedPane = new JTabbedPane();
              ImageIcon graphIcon = createImageIcon("images/graphtab.gif");
              ImageIcon textIcon = createImageIcon("images/texttab.gif");
            graphIcon = new ImageIcon("images/graphtab.gif");
            textIcon = new ImageIcon("images/texttab.gif");
            graphicsPanel = new JPanel();
            textPanel = new JPanel();
              tabbedPane.addTab("Graphical", graphIcon, graphicsPanel,
                              "Swaps to graphical output");
            tabbedPane.addTab("Text", textIcon, textPanel,
                              "Swaps to text output");
            /*TableModel dataModel = new AbstractTableModel()
              public int getColumnCount()
                     return 6;
              public int getRowCount()
                     return 20;
              public Object getValueAt(int row, int col)
                     return new Integer(row*col);
              //pclTable = new JTable(dataModel);
            MessageSet ms2 = new MessageSet();
              textPanel.add(new JScrollPane(createTable(ms2.getArray())));
            //Add the tabbed pane to the outer panel.
              add(tabbedPane, BorderLayout.CENTER);
            setPreferredSize(new Dimension(500, 500));
            //Uncomment the following line to use scrolling tabs.
            //tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        // Creates a JTable and returns it
         private JTable createTable(Message[] theArray)
              // Define empty data for model creation
              String[][] cellData = new String[0][6];
              String[] colNames = { "ID", "Sent To", "Sent From", "Command", "Data Ref", "Monitored" };
              // Create the table model
              DefaultTableModel tableModel = new DefaultTableModel(cellData, colNames);
              // Create some records and add them to the model
              String[] record = new String[6];
              for (int row=0; row<=theArray.length; row++)
                record[0] = Integer.toString(theArray[row].getID());
                record[1] = theArray[row].getToSection_ID();
                   record[2] = theArray[row].getFromSection_ID();
                   record[3] = Integer.toString(theArray[row].getType_ID());
                   record[4] = theArray[row].getDataRef();
                   record[5] = Integer.toString(theArray[row].getMonitored());
                   tableModel.addRow(record);
              // Create the table and return it
              return new JTable(tableModel);
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path)
            java.net.URL imgURL = ProtocolGUI.class.getResource(path);
            if (imgURL != null)
                return new ImageIcon(imgURL);
              else
                System.err.println("Couldn't find file: " + path);
                return null;
        public void actionPerformed(ActionEvent e)
            Object source = e.getSource();
            if (source == exitItem)
                System.exit(0);
         private static void createAndShowGUI()
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Protocol GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new ProtocolGUI();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.getContentPane().add(new ProtocolGUI(),
                                     BorderLayout.CENTER);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

  • Probs. with JLayeredPane & JFrames

    Hi!
    I have a serious problem with a JLayeredPane in a JFrame... it doesn�t show any of my components, just a grey background.
    I have tried almost every single hint and advise I have been able to find - with no luck. So here goes my code - please help - I�m really stuck.
    //GUI.java Authors: Lis Riediger & Dawn H. Hammer
    //Klassen der indeholder vores brugergr�nseflade
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class GUI extends JFrame
    private GUI_felt[] gui_f = new GUI_felt[40];
    private JPanel[] jp1 = new JPanel[40], jp2 = new JPanel[40];
    private JLayeredPane JLP;
    private Spil s;
    private JPanel pBraet, pHuse, pBrikker, pNord, pSyd, pVest, pOst, pCenter, lastCenter = null,
    Ost1, Ost2, Vest1, Vest2, Syd1, Syd2, Nord1, Nord2;
    //S�tter GUI'en op
    public GUI(String[] spillere)
    super("Matador");
    s = new Spil(spillere);
    //S�tter lag 0 op
    for (int i = 0; i <=39; i++)
    if (((s.getFelt(i)).getType()).compareTo("grund") == 0)
    gui_f[i] = new GUI_grund((Grund)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("bryggeri") == 0)
    gui_f[i] = new GUI_bryggeri((Bryggeri)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("faerge") == 0)
    gui_f[i] = new GUI_faerge((Faerge)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("ddb") == 0)
    gui_f[i] = new GUI_ddb((DDB)s.getFelt(i));
    else if(s.getFelt(i).getType().compareTo("skat") == 0)
    gui_f[i] = new GUI_skat((Skat)s.getFelt(i));
    else
    gui_f[i] = new GUI_felt(s.getFelt(i));
    for (int i = 0; i <=39;i++)
    gui_f.addMouseListener(new mouseListener());
    gui_f[i].setBackground(new Color(0,128,0));
    pSyd = new JPanel(new GridLayout(1,11));
    pSyd.setSize(462,42);
    for (int i = 10; i >= 0;i--)
    pSyd.add(gui_f[i]);
    pVest = new JPanel(new GridLayout(9,1));
    pVest.setSize(42,378);
    for (int i = 19; i >= 11; i--)
    pVest.add(gui_f[i]);
    pNord = new JPanel(new GridLayout(1,11));
    pNord.setSize(462,42);
    for (int i = 20; i <= 30; i++)
    pNord.add(gui_f[i]);
    pOst = new JPanel(new GridLayout(9,1));
    pOst.setSize(42,378);
    for (int i = 31; i <= 39; i++)
    pOst.add(gui_f[i]);
    pCenter = new JPanel();
    pCenter.setSize(378,378);
    pCenter.setBackground(new Color(0,128,0));
    pBraet = new JPanel(new BorderLayout());
    pBraet.setSize(462,462);
    pBraet.setVisible(true);
    pBraet.setBackground(new Color(0,128,0));
    pBraet.add(pSyd, BorderLayout.SOUTH);
    pBraet.add(pVest, BorderLayout.WEST);
    pBraet.add(pNord, BorderLayout.NORTH);
    pBraet.add(pOst, BorderLayout.EAST);
    pBraet.add(pCenter, BorderLayout.CENTER);
    //S�tter lag 1 op
    for (int i = 0; i <= 39;i++)
    jp1[i] = new JPanel();
    jp1[i].add(new JLabel(new ImageIcon("layer.gif")));
    jp1[i].setSize(42,42);
    Syd1 = new JPanel(new GridLayout(1,11));
    Syd1.setSize(462,42);
    for (int i = 10; i >= 0;i--)
    pSyd.add(jp1[i]);
    Vest1 = new JPanel(new GridLayout(9,1));
    Vest1.setSize(42,378);
    for (int i = 19; i >= 11; i--)
    pVest.add(jp1[i]);
    Nord1 = new JPanel(new GridLayout(1,11));
    Nord1.setSize(462,42);
    for (int i = 20; i <= 30; i++)
    pNord.add(jp1[i]);
    Ost1 = new JPanel(new GridLayout(9,1));
    Ost1.setSize(42,378);
    for (int i = 31; i <= 39; i++)
    pOst.add(jp1[i]);
    pHuse = new JPanel(new BorderLayout());
    pHuse.setSize(new Dimension(500,500));
    pHuse.setVisible(true);
    pHuse.setBackground(new Color(0,128,0));
    pHuse.add(Syd1, BorderLayout.SOUTH);
    pHuse.add(Vest1, BorderLayout.WEST);
    pHuse.add(Nord1, BorderLayout.NORTH);
    pHuse.add(Ost1, BorderLayout.EAST);
    //S�tter lag 2 op
    jp2[0] = new JPanel();
    jp2[0].setSize(42,42);
    JLabel dimmer = new JLabel(new ImageIcon("spiller1.gif"));
    dimmer.setSize(42,42);
    jp2[0].add(dimmer);
    for (int i = 1; i <= 39;i++)
    jp2[i] = new JPanel();
    jp2[i].add(new JLabel(new ImageIcon("layer.gif")));
    Syd2 = new JPanel(new GridLayout(1,11));
    Syd2.setSize(462,42);
    for (int i = 10; i >= 0;i--)
    pSyd.add(jp2[i]);
    Vest2 = new JPanel(new GridLayout(9,1));
    Vest2.setSize(42,378);
    for (int i = 19; i >= 11; i--)
    pVest.add(jp2[i]);
    Nord2 = new JPanel(new GridLayout(1,11));
    Nord2.setSize(462,42);
    for (int i = 20; i <= 30; i++)
    pNord.add(jp2[i]);
    Ost2 = new JPanel(new GridLayout(9,1));
    Ost2.setSize(42,378);
    for (int i = 31; i <= 39; i++)
    pOst.add(jp2[i]);
    pBrikker = new JPanel(new BorderLayout());
    pBrikker.setSize(new Dimension(462,462));
    pBrikker.setVisible(true);
    pBrikker.setBackground(new Color(0,128,0));
    pBrikker.add(Syd1, BorderLayout.SOUTH);
    pBrikker.add(Vest1, BorderLayout.WEST);
    pBrikker.add(Nord1, BorderLayout.NORTH);
    pBrikker.add(Ost1, BorderLayout.EAST);
    JLP = new JLayeredPane();
    JLP.setPreferredSize(new Dimension(462,462));
    JLP.setVisible(true);
    JLP.add(pBraet,new Integer(0));
    JLP.add(pHuse, new Integer(1));
    JLP.add(pBrikker, new Integer(2));
    Container contentPane = getContentPane();
    contentPane.add(JLP);
    contentPane.setLayout(new BorderLayout());
    //Indre klasse der h�ndterer mouseEvents
    private class mouseListener extends MouseAdapter
    //Metode der svarer p� et musseklik
    public void mouseClicked(MouseEvent event)
    if (lastCenter != null) pCenter.remove(lastCenter);
    lastCenter = ((GUI_felt)event.getSource()).getCenterCard();
    pCenter.add(lastCenter);
    pCenter.updateUI();
    Sincerely,
    Trisse

    I can tell from looking at it that your code won't even compile, yet you say it runs, just doesn't give the right result. I found 8 syntax errors in the first two for loops alone. Please post the actual code next time.
    Now, onto the logic errors (assuming I understand what the code should be)
    1. Last code block in the constructor...you add a component to the content pane, THEN set the layout?
    2. You've got a bunch of setVisible(true) calls on JPanel objects....why?
    3. Please call your mouseListener class something else. It's confusing considering the Java interface MouseListener.
    4. Second for loop, assuming you mean to index into the gui_f array, create the Color object once outside the loop, then assign it within the loop. Otherwise, that loop alone is going to create 40 Color objects (plus another 40 implicitly, but that's a discussion for another time). You do the same thing with all those ImageIcon objects.
    5. Same assumption as #4, your mouseListener code is independent of the source object (it doesn't assume what's its source is), don't create a new listener object for every object. One listener instance can handle all the GUI_Felt objects.
    6. It looks like you're trying to use JLayeredPane when you want one of a number of panels to be visible given some circumstances. Don't use JLayeredPane, use a generic JPanel with the CardLayout.
    7. You've got WAY too much code for a constructor. Each of your primary panels should be its own class.
    8. Your call in the mouseListener to updateUI is wrong. If what you want is to change the layout of a container after its been displayed, use the revalidate call. This is also the primary reason you're not seeing anything. You're calling setVisible on all these JPanels, which tells them to lay out their child components, but they don't have any yet. THEN, you add components, which will never get laid out.
    9. You're setting the actual size of a bunch of components, then adding them to a container that has a BorderLayout. Don't..BorderLayout will ignore the sizing you're doing and use only the preferredSize.
    10. I'm pretty sure there's more, but work on this, then try again.
    PS: If after all that I don't get at least some DDs, I will be very unhappy.

  • How to make Internal Frame on Focus

    Hi All,
    i have an application where in i have a JInternalFrame within in A JFrame.
    Queries:
    1.I want to make JInternalFrame focused,(without clicking on any portoion of Internal Frame) once i run the apllication(java Demo)
    2.i want to fix the JInternal Frame.(Non movable)
    //Demo.java
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;     
    import javax.swing.event.*;     
    import javax.swing.border.*;          
    public class Demo extends JFrame implements ActionListener {
    static JDesktopPane desk;
    String labelstr="Test ";
    JPanel contentpane;
    JLabel titlelabel;
    public Demo() {
              setTitle("Swing Test");
                    contentpane=(JPanel)getContentPane();
                    contentpane.setLayout(new BorderLayout());
                    desk=new JDesktopPane();     
                    desk.setBackground(Color.gray);
                    contentpane.add("Center",desk);
                    titlelabel=new JLabel(labelstr);
                    titlelabel.setForeground(Color.black);
                    titlelabel.setBorder(new BevelBorder(BevelBorder.LOWERED));
                    getContentPane().add(titlelabel,BorderLayout.SOUTH);            
              public void actionPerformed(ActionEvent e) {
                 public static void main(String args[]) {     
                    try  {
                      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                      //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                     }catch(Exception e) {
                                               System.out.println("Error loading L&F:"+e);     
                                               JOptionPane.showMessageDialog(null,e);
                    JFrame frame=new Demo();
                    frame.setSize(800,600);
                    frame.setVisible(true);
                      InternalFr jif=new InternalFr();
                      jif.start();
                    frame.addWindowListener(new CloseWindow());
           class CloseWindow extends WindowAdapter {
             public void windowClosing(WindowEvent we) {
                 Window w=we.getWindow();
                 w.dispose();
                 System.exit(0);
          }//InternalFr.java
    import java.io.*;
         import java.net.*;
         import java.lang.*;
         import java.awt.*;
         import java.awt.event.*;
         import javax.swing.*;
         import javax.swing.border.*;
         import javax.swing.text.*;
         public class InternalFr extends JInternalFrame {
             JLabel jlName, jlPass;
             static JTextField jtName,jtPass;
                 JButton submit,cancel;
            public InternalFr() {  
              super( "InternalFr");
              Icon img=new ImageIcon("Neticon.gif");
              setFrameIcon(img);
              JPanel contentpane=(JPanel)getContentPane();
               contentpane.setLayout(null);
              JPanel mainpanel=new JPanel();
              mainpanel.setLayout(null);
              mainpanel.setBounds(0,0,290,180);
              jlName=new JLabel("Username   :");
              jlName.setBounds(20,20,180,20);
              jlName.setForeground(Color.black);
              jtName=new JTextField();
              jtName.setBounds(150,20,100,20);
              mainpanel.add(jtName);
              mainpanel.add(jlName);
              jlPass=new JLabel("Password   :");
              jlPass.setBounds(20,50,180,20);
              jlPass.setForeground(Color.black);
              jtPass=new JTextField();
              jtPass.setBounds(150,50,100,20);
              mainpanel.add(jlPass);
              mainpanel.add(jtPass);
              JPanel buttonpanel=new JPanel();
              buttonpanel.setLayout(null);
              buttonpanel.setBounds(30,90,215,30);
              buttonpanel.setBorder(new EtchedBorder(EtchedBorder.RAISED));
              submit=new JButton("Submit");
              submit.setMnemonic('O');
              submit.setBounds(5,5,100,20);
              buttonpanel.add(submit);
              submit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                 if(ae.getSource()==submit)  {
            cancel=new JButton("Cancel");
              cancel.setMnemonic('C');
              cancel.setBounds(110,5,100,20);
              buttonpanel.add(cancel);
              cancel.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent ae) {
                      Object obj=ae.getSource();
                     if(obj==cancel){
                          System.exit(0);
           contentpane.add(buttonpanel);
           contentpane.add(mainpanel);
        public void start()  {
             InternalFr at=new InternalFr();
             at.setSize(290,180);
            at.setLocation(220,150);
            at.setVisible(true);
            Demo.desk.add(at);
      }Thanks
    Mohan

    To give focus to an internal frame, do the following (where iFrame is your internal frame):try {
        iFrame.setIcon( false );  // In case it is minimized
        iFrame.moveToFront();     // Make sure it is in front
        iFrame.requestFocus();    // Ask for focus
        iFrame.setSelected( true );  // Select it
    } catch( java.beans.PropertyVetoException pve ) {
    }

  • Inverted image

    I am having a problem with the image being displayed upside down. How do I get the image to display correctly without having to rotate it? Thanks for any help!
    I am using a very old version of Java - JDK1.1.8 and Swing 1.0.3
    Code:
    import com.sun.java.swing.*;
    import java.awt.*;
    public class TestIcon
    JPanel panel;
    TestIcon()
    JFrame frame = new JFrame("Test");
    ImageIcon rbIcon = new ImageIcon("12304-fuzzy-molly.gif");
    panel = new JPanel();
    panel.setPreferredSize(new Dimension(200, 100));
    panel.add(new JLabel((Icon)rbIcon));
    frame.pack();
    frame.setSize(200,100);
    frame.getContentPane().add(panel);
    frame.setVisible(true);
    public static void main(String [] args)
    TestIcon ti = new TestIcon();

    How do I get the image to display correctly without having to rotate it? Is this programmatic rotation or normal graphics editing rotation?
    I don't know much about JDK1.1.8 but does it have the java.awt.Graphics2D class? If it does, then look up the rotate method and try this.
    1. Subclass javax.swing.ImageIcon
    2. override the paintIcon method like this public void piantIcon(Component c, Graphics g, int x, int y) {
      super.paintIcon(c, g, x, y);
      Graphics2D g2 = (Graphics2D) g
      g2.rotate(Math.PI);
      // i think there should be a translate after this. Something like g2.translate(x,y);
    } Please check the above code and method well cos I haven't tested it, this is just a suggestion.
    If the above suggestion cannot help, then I think you should get out your graphics editor and do a manual rotation of the image yourself and save it with a different file name, so that you can load the upright or inverted image when you need it.
    ICE

  • Animated GIF Image on a JPanel.

    How can I display an animated GIF image on a JPanel? It should animate after displaying.
    Regards

    I think this code should display an animated GIF image on a JPanel.
    -Mani
    import javax.swing.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.*;
    public class Animation {
    public static void main(String args[]) {
    JLabel imageLabel = new JLabel();
    JLabel headerLabel = new JLabel();
    JFrame frame = new JFrame("JFrame Animation");
    JPanel jPanel = new JPanel();
    //Add a window listner for close button
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    // add the header label
    headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
    headerLabel.setText("Animated Image!");
    jPanel.add(headerLabel, java.awt.BorderLayout.NORTH);
    //frame.getContentPane().add(headerLabel, java.awt.BorderLayout.NORTH);
    // add the image label
    ImageIcon ii = new ImageIcon("d:/dog.gif");
    imageLabel.setIcon(ii);
    jPanel.add(imageLabel, BorderLayout.CENTER);
    frame.getContentPane().add(jPanel, java.awt.BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

  • Encode JPanel as Gif

    i want to use ACME's GifEncoder to encode the JPanel as gif ...
    for encoding Jpeg, i just printAll() the JPanel to form a BufferedImage for encoding ...
    but the GifEncode need a Image object (not BufferedImage), so how could i create a BufferedImage from a JPanel ??
    thx

    Hi Yundi! :-)
    One hand washes the other one, right?
    I suppose you mean: How to create an Image from a JPanel and not a BuffedImage?
    I do this like that (ok, bit of dirty way, but I have to scale my image):
    BufferedImage bi;
    Image img = bi.getScaledInstance( width, height, Image.SCALE_DEFAULT );

  • Jpeg or gif inside JPanel

    how do i put an image into a JPanel ?

    If you're using Swing, then look into using an ImageIcon inside a JLabel. If not, then load the gif or jpeg into an Image instance and overriding the paint() method of a panel.

  • Java Swing - save JPanel as GIF/JPEG.

    WE are using Java swing to draw graph(Genes, SNP ,repeats etc related to bio-informatics).text files we are using are quite big eg- more than 25 MB. first it makes the process slow.One of our problem is to save whatever "we draw as an image file(GIF/JPEG file)" and another problem is save a data in a data structure(array,vector) which grow upto 15-20 MB.
    plotting this data makes the speed too slow.We want to optimize this.

    For saving images have a look at JAI - the Java Advanced Imaging API. It's got fairly straightforward ways of saving images. Note that saving as GIF images is not recommended; patents were placed on the encoding so it's no longer a free option. PNG will give you lossless compression like GIF but is more flexible.
    http://java.sun.com/products/java-media/jai/
    Saving the generated (mined?) data structure for future retrieval can be quite straightforward depending on how you're doing it. The easiest way is simply to serialise it (use an ObjectOutputStream) but this has compatibility problems if you change your data structure.
    Saving out in a custom format may seem like a lot of work but it's not all that hard to do. Alternatively you can use one of the Java to XML convertors - in your case this might generate too large a file, however.
    YOu can always use Java's zip functions to improve file size should this become problematic.
    Hope this helps

  • Resized animated gif ImageIcon not working properly with JButton etc.

    The problem is that when I resize an ImageIcon representing an animated gif and place it on a Jbutton, JToggelButton or JLabel, in some cases the image does not show or does not animate. More precicely, depending on the specific image file, the image shows always, most of the time or sometimes. Images which are susceptible to not showing often do not animate when showing. Moving over or clicking with the mouse on the AbstractButton instance while the frame is supposed to updated causes the image to disappear (even when viewing the non-animating image that sometimes appears). No errors are thrown.
    Here some example code: (compiled with Java 6.0 compliance)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              new Test();
         static final int  IMAGES        = 3;
         JButton[]           buttons       = new JButton[IMAGES];
         JButton             toggleButton  = new JButton("Toggle scaling");
         boolean            doScale       = true;
         public Test()
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel(new GridLayout(1, IMAGES));
              for (int i = 0; i < IMAGES; i++)
                   p.add(this.buttons[i] = new JButton());
              f.add(p, BorderLayout.CENTER);
              f.add(this.toggleButton, BorderLayout.SOUTH);
              this.toggleButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e)
                        Test.this.refresh();
              f.setSize(600, 300);
              f.setVisible(true);
              this.refresh();
         public void refresh()
              this.doScale = !this.doScale;
              for (int i = 0; i < IMAGES; i++)
                   ImageIcon image = new ImageIcon(i + ".gif");
                   if (this.doScale)
                        image = new ImageIcon(image.getImage().getScaledInstance(180, 180, Image.SCALE_AREA_AVERAGING));
                   image.setImageObserver(this.buttons);
                   this.buttons[i].setIcon(image);
                   this.buttons[i].setSelectedIcon(image);
                   this.buttons[i].setDisabledIcon(image);
                   this.buttons[i].setDisabledSelectedIcon(image);
                   this.buttons[i].setRolloverIcon(image);
                   this.buttons[i].setRolloverSelectedIcon(image);
                   this.buttons[i].setPressedIcon(image);
    Download the gif images here:
    http://djmadz.com/zombie/0.gif
    http://djmadz.com/zombie/1.gif
    http://djmadz.com/zombie/2.gif
    When you press the "Toggle scaling"button it switches between unresized (properly working) and resized instances of three of my gif images. Notice that the left image almost never appears, the middle image always, and the right image most of the time. The right image seems to (almost) never animate. When you click on the left image (when visble) it disappears only when the backend is updating the animation (between those two frames with a long delay)
    Why are the original ImageIcon and the resized ImageIcon behaving differently? Are they differently organized internally?
    Is there any chance my way of resizing might be wrong?

    It does work, however I refuse to use SCALE_REPLICATE for my application because resizing images is butt ugly, whether scaling up or down. Could there be a clue in the rescaling implementations, which I can override?
    Maybe is there a way that I can check if an image is a multi-frame animation and set the scaling algorithm accordingly?
    Message was edited by:
    Zom-B

  • Animated GIF frame loss

    I have an applet that has a JPanel with a JLabel in it. That JLabel was created with an ImageIcon constructor with an animated gif image. The gif has eleven frames (each with replace set) and is set to loop. When I bring up the applet the image animates through the first 7 frames then stops. I can File/Open the gif in Netscape and it looks fine - animates all images and loops. Looking at it with:
    setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION); or FLASH_OPTION
    it looks good until that 7th frame then I start to see flash of grey the size of the JLabel.
    I understand that the ImageObserver defaults to the JLabel. But I have tried directly setting it with no joy. I have also tried calling .flush() on the image with no joy. So I tried a different animated gif and it stopped on the 3rd frame (but also appears fine in a browser).
    I am on day 2 of trying to figure this out (pulling my hair out).
    I cut this down quite a bit, so there may be syntax errors.
    public class RRR extends JApplet implements RRRConsts
    public void init()
    loadImages();
    myJPanel = new MyJPanel();
    contentPane.add(myJPael);
    private void loadImages()
    try
    problemImage = loadImage(new URL(getDocumentBase(),
    "problem.gif"));
    catch (Exception e)
    { logger.log(Level.SEVERE, "Unable to load images", e); }
    private Image loadImage(URL url) throws InterruptedException
    Image image = getImage(url);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(image, 0);
    tracker.waitForID(0);
    return image;
    MyJPanel myJPanel = null;
    static Image problemImage = null;
    class MyJPanel extends JPanel implements RRRConsts
    MyJPanel()
    setLayout(null);
    setBounds(0,0,468,540);
    setOpaque(false);
    buildUI();
    private void buildUI()
    myLabel = new MyLabel();
    add(myLabel);
    private MyLabel myLabel = null;
    class MyLabel extends JLabel implements RRRConsts, ActionListener
    MyLabel()
    super(new ImageIcon(RRR.problemImage));
    }

    I just had the same problem. It seems that when using an animated gif as ImageIcon it will not be loaded compeltly if it is too large. The maximum seems to be somewhere between 60 - 70 KB.
    I managed to use a higher compression on my gifs to make them smaller, but I haven't found any general solution yet.

Maybe you are looking for