Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Updating JPanel on JTabbedPane with a Resize Event

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Updating JPanel on JTabbedPane with a Resize Event

    Folks,

    I have been struggling for some time with a problem. I think I have it half solved, but as a beginner at Java (and hindered by decades of programming in older languages), I can't get it solved. Any help would be appreciated, and pardon if I don't follow protocol well.

    I have a JPanel that populates a JTabbedPane. It seems to work fine. Right now I've just got it painting full of random pixels. A couple other tabs are present, and the panel is only on the first tab, so success. I need to redraw that image as a simulation progresses. I also want to redraw it when the JFrame is resized. Right now I am just looking for the random pixels to change during a resize.

    I've got the Resize plugged in correctly, I think. The text I asked to be echoed does print. But I can't get the panel to update. I worry about creating 1000 instances of the JPanel, or worse the entire tab. I will attach the most relevant code below. I've tried many variations not shown here, with repaint, revalidate, etc. Just can't figure it out. Thank you for any insights!

    Randy

    //***********************
    public final class M_Move extends JPanel {
     
        static Random generator;
        static JComponent panel1; 
     
        public M_Move() {
            super(new GridLayout(1, 1));
     
            JTabbedPane tabbedPane = new JTabbedPane();
            ImageIcon icon1 = createImageIcon("http://www.javaprogrammingforums.com/images/map.gif");
            ImageIcon icon2 = createImageIcon("http://www.javaprogrammingforums.com/images/input.gif");
            ImageIcon icon3 = createImageIcon("http://www.javaprogrammingforums.com/images/output.gif");
     
      //      JComponent panel1 = makeTextPanel("Spatial");
      //      JComponent panel1 = new MakeBufferedImage(640, 480);
            panel1 = new MakeBufferedImage(640, 480);
            tabbedPane.addTab("Spatial", icon1, panel1, "Map agent movements");
            tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
            panel1.setPreferredSize(new Dimension(640, 480));
     
           < snip ... panels 2 and 3 are set up, and work>
     
            //Add the tabbed pane to this panel.
            add(tabbedPane);
     
        }
     
        protected JComponent makeTextPanel(String text) {     < snipped >     }
        protected static ImageIcon createImageIcon(String path) {  < snipped >    }
     
        private static void createAndShowGUI() {
            //Create and set up the window.
            //JFrame frame = new JFrame("Multi Move");
            JFrame frame = new Main();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            //Set up the content pane.
            addComponentsToPane(frame.getContentPane());
     
            //Display the window.
            frame.pack();
            frame.setVisible(true);                
        }
     
     
        public static void main(String[] args) {
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
            generator = new Random();
     
     
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    //Turn off metal's use of bold fonts
            // UIManager.put("swing.boldMetal", Boolean.FALSE);
            createAndShowGUI();
                }
            });
        }
     
     
    //**************************
    package m_move;
     
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JPanel;
     
    public final class MakeBufferedImage extends JPanel {
     
        private BufferedImage canvas;
     
        public MakeBufferedImage(int width, int height) {
            canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            for (int y=0; y<height; y++) {
                for (int x=0; x<width; x++) {
                    int r = M_Move.generator.nextInt(256);
                    int g = M_Move.generator.nextInt(256);
                    int b = M_Move.generator.nextInt(256);
                    int rgb = new Color(r,g,b).getRGB();
                    canvas.setRGB(x, y, rgb);
                }
            }
        }
     
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(canvas.getWidth(), canvas.getHeight());
        }
     
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.drawImage(canvas, null, null);
        }
     
        public void redrawer() {        
         System.out.println("IN REDRAWER!!!!!!!!!!!!!!!!!!!!!!!!!!!");   
            canvas = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
            for (int y=0; y<480; y++) {                                              
                for (int x=0; x<640; x++) {                                          
                    int r = M_Move.generator.nextInt(256);                           
                    int g = M_Move.generator.nextInt(256);                           
                    int b = M_Move.generator.nextInt(256);                           
                    int rgb = new Color(r,g,b).getRGB();                             
                    canvas.setRGB(x, y, rgb);                                        
                }                                                                    
            }                                                         
     
        }  
     
    }
     
    // ********************************************
    package m_move;
    //
    //import java.awt.Frame;
     
    import java.awt.Frame;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
     
    public class Main extends JFrame implements ComponentListener {
     
    //  private BufferedImage canvas;
     
      public Main() {
        addComponentListener(this);
      }
     
        @Override
      public void componentHidden(ComponentEvent e) {
        System.out.println("componentHidden");
      }
     
        @Override
      public void componentMoved(ComponentEvent e) {
        System.out.println("componentMoved");
      }
     
        @Override
      public void componentResized(ComponentEvent e) {
       // M_Move.resizer();
       //    maker.Redrawer();
        M_Move.panel1 = new MakeBufferedImage(640, 480);
       //   panel1.revalidate();
       // MakeBufferedImage t = new MakeBufferedImage(640,480);
       // panel1.redrawer();
     
        System.out.println(" RESIZER!!! --- Resized ");            
     
        System.out.println("componentResized");
        System.out.println(getExtendedState());
     
        if (getExtendedState() == Frame.ICONIFIED) { 
          System.out.println("RESIZED TO ICONIFIED");
        } else if (getExtendedState() == Frame.NORMAL) {
          System.out.println("RESIZED TO NORMAL");
        } else {
          System.out.println("RESIZED TO MAXIMIZED");
        }
      }
     
        @Override
        public void componentShown(ComponentEvent e) {
    //        throw new UnsupportedOperationException("Not supported yet.");
        }
     
    }
    Last edited by rboone2020; June 17th, 2012 at 03:17 PM. Reason: Improved the code formatting


  2. #2
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Updating JPanel on JTabbedPane with a Resize Event

    I need to redraw that image as a simulation progresses.
    Can you explain what you mean by that?

    I also want to redraw it when the JFrame is resized.
    When a JFrame is resized, it should repaint itself and all its children. If you override the paintComponent(Graphics g) method of the JPanel, as I think you've done, then this custom paint should be performed when the JFrame passes the repaint down to the JTabbedPane, and it down to the JPanel.

    But I can't get the panel to update.
    Do you mean that the JPanel doesn't repaint, or does your simulation not advance?
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  3. #3
    Junior Member
    Join Date
    Jun 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Updating JPanel on JTabbedPane with a Resize Event

    Thanks for your time, Snowguy. (Not sure I've used this quote function correctly, but ...)

    Quote Originally Posted by snowguy13 View Post
    Can you explain what you mean by that?

    There will be a simulation in this Java code in the future. It will generate values that will tell me what color to shade pixels. But it doesn't exist yet, right now I'm just trying to change the random pixels assigned to the JPanel.

    When a JFrame is resized, it should repaint itself and all its children. If you override the paintComponent(Graphics g) method of the JPanel, as I think you've done, then this custom paint should be performed when the JFrame passes the repaint down to the JTabbedPane, and it down to the JPanel.


    Do you mean that the JPanel doesn't repaint, or does your simulation not advance?
    The JPanel doesn't repaint. There is no simulation yet. I seem to be having trouble with the painting of an existing JPanel associated with a tab.

    Thanks again,
    Randy

  4. #4
    Junior Member
    Join Date
    Jun 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Updating JPanel on JTabbedPane with a Resize Event

    Sorry for the short reply ... Father's Day rushes. Settled in again, so I'll expand a bit.

    I've been using examples as guides. The example I found uses an instance of a JComponent called canvas that extends a JPanel. That canvas is filled with gibberish, correctly. Then it is assigned to a JTabbedPan, and made visible. As I say, that seems to work fine.

    The rest just seems to follow from my not knowing enough about proper calls and such. I have a componentListener to listen for a resize event. That works too. It took me awhile, but I figured out had to call routines in other classes, and judging from some string echos, that seems to work. So the challenge for me is to update the JPanel. I just want to be able to draw to it and have it show. Right now it doesn't update (in this case, make a new random pixel image) when I resize. So I guess what I'm struggling with is ... In a given class, how do I access a panel in a tab in another (main) class, and have it redraw? Should I create a new instance of the canvas and then a new instance of the panel and add it to the tab? How do I remove the old tab? Seems potentially chaotic. I'd prefer to just follow the old Visual Basic pathway (non object-oriented I know), of getting a handle on the existing canvas and make changes to it directly, and have it be assigned to the panel. So some minor mysteries.

    Thanks again,
    Randy

  5. #5
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Updating JPanel on JTabbedPane with a Resize Event

    JTabbedPanes have methods called getTabComponentAt(int index). This method will allow you to get a component at a certain index in the JTabbedPane. If your JPanel is the first component, it can be reached by using index 0. Once you access the JPanel using that method, you can call repaint() on it.

    This means that you just have to keep a reference to the JTabbedPane you create (in other words, you must assign a variable to the JTabbedPane so that you can access it from the main class whenever you need).
    Last edited by snowguy13; June 18th, 2012 at 08:47 AM. Reason: Elaborating
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  6. #6
    Junior Member
    Join Date
    Jun 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Updating JPanel on JTabbedPane with a Resize Event

    Thanks again, Snowguy. It ends up that the paintComponent procedure needed more of the code to paint material (plus 100 other errors, no doubt). A few days of debugging and learning have brought me much closer. I am all the way to having the dimensions of the resized frame being passed, and correctly echoed, within the window drawing class (with that class based on a Java example called DirectDrawDemo.java). It seems I'm quite close. However, the dimensions of the canvas being drawn do not change. The tabbedPanel resizes fine, but the canvas remains its initial 640 x 480 pixels.
    Thanks again for any pointers you can provide.

    Randy

    The relevant code is:

    package m_move;
     
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JPanel;
     
    public final class MakeBufferedImage extends JPanel {
     
        public BufferedImage canvas;
     
        public MakeBufferedImage(int width, int height) {
            System.out.println("PASSED WIDTH AND HEIGHT: " + width + "   " + height);     // These values echo correctly.      
            canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        }
     
        @Override
        public Dimension getPreferredSize() {
            System.out.println("GETTING PREFERRED SIZE");
            return new Dimension(canvas.getWidth(), canvas.getHeight());
        }
     
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            // Appears based on online materials to be a reasonable means of clearing a BufferedImage.  
            int clr = new Color(200, 200, 200).getRGB();              // Clearing to a light gray.
            // The following values never change ... always the initial values,
            // even though the WIDTH and HEIGHT above print correctly,
            // That is the dimensions of the resized frame are correctly passed and used in "new BufferedImage" above.
            // So the canvas = new BufferedImage doesn't seem to create a new canvas correctly.
            System.out.println("CANVAS WIDTH AND HEIGHT: " + canvas.getWidth() + "   " + canvas.getHeight());
            int w = canvas.getWidth();
            int h = canvas.getHeight();
            for (int y=0; y<h; y++) {
                for (int x=0; x<w; x++) {
                    canvas.setRGB(x, y, clr);
                }
            }
     
            //** I DRAW SOME RANDOM PIXELS HERE, WHICH IS WORKING.  But canvas remains the original size. 
            //  g2.dispose(), canvus.flush() don't change anything.
     
           g2.drawImage(canvas, null, null);
           g2.dispose();
        }
    }
    Last edited by rboone2020; June 20th, 2012 at 09:57 PM.

  7. #7
    Junior Member
    Join Date
    Jun 2012
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Updating JPanel on JTabbedPane with a Resize Event

    Folks,

    Another group helped me solve this issue. It involved moving the new BufferedImage call into the paintComponent section. For completeness, I will include the solution, as remapped to my program, here. Thanks for considering my issue.

    Randy

    package m_move;
     
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import javax.swing.JPanel;
     
    public final class MakeBufferedImage extends JPanel {
     
        public BufferedImage canvas;
     
        public MakeBufferedImage(int width, int height) {
            this.setSize(width, height);
        }
     
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(this.getWidth(), this.getHeight());
        }
     
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
     
            // Appears based on online materials to be a reasonable means of clearing a BufferedImage
            int clr = new Color(200, 200, 200).getRGB(); 
            int w = getPreferredSize().width;  
            int h = getPreferredSize().height; 
            canvas = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
            for (int y=0; y<h; y++) {
                for (int x=0; x<w; x++) {
                    canvas.setRGB(x, y, clr);
                }
            }
     
            //  Here I draw some random pixels, correctly.
            //  The canvas now fills any resized frame, as planned.
            g2.drawImage(canvas, null, null);
        }
    }

Similar Threads

  1. Resize an immage
    By gvgenop in forum Java Theory & Questions
    Replies: 2
    Last Post: October 28th, 2011, 01:06 PM
  2. (Javascript) Resize an image according to browser.
    By cybershadow in forum Other Programming Languages
    Replies: 3
    Last Post: October 13th, 2011, 11:24 AM
  3. Resize a window without native decorators
    By supertreta in forum AWT / Java Swing
    Replies: 0
    Last Post: January 11th, 2011, 02:06 PM
  4. image scaling on window resize
    By chopficaro in forum Java Theory & Questions
    Replies: 2
    Last Post: August 27th, 2010, 03:09 PM
  5. [SOLVED] how can i resize JTextField, JButton using GridBagLayout,... TNX
    By sny in forum AWT / Java Swing
    Replies: 0
    Last Post: March 4th, 2010, 09:57 AM

Tags for this Thread