Results 1 to 16 of 16
Like Tree3Likes
  • 1 Post By jim829
  • 1 Post By Norm
  • 1 Post By Tolls

Thread: JPanel is not updated when I click on button

  1. #1
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default JPanel is not updated when I click on button

    Hello. I have a JPanel that must redraw several lines when a click on a button after downloading from on-line server has been completed. The problem is that the data is downloaded, new data is sent to the instance of the JPanel class, but the panel is not updated/redrawn. If I change the size of the frame, it redraws as needed. Or if I go to another panel and then return, it redraws it. Looks like paintComponent() is not invoked when I do revalidate() or repaint():

    class AppSingleton

    Java Code:
    package test4;
    
    public class AppSingleton 
    {
        private static AppSingleton instance = null;
        
        private String windsAloftMessageShared = "";
    
        public List<List<String>> windAloftDataShared = new ArrayList<List<String>>(){{
            add(Arrays.asList(""));
            add(Arrays.asList(""));
            add(Arrays.asList(""));
        }};
        
        private String windAloftAltitude0Shared = "";
        private String windAloftAltitude1Shared = "";
        private String windAloftAltitude2Shared = "";
        
        private AppSingleton() 
        {
         
        }
        
        public static AppSingleton getInstance() 
        {
            if(instance == null) 
            {
                instance = new AppSingleton();
            }
          return instance;
        }
        
        public void initDefaultValues()
        {
            Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
        }
        
        public String getWindsAloftMessageShared() {
            return windsAloftMessageShared;
        }
    
        public void setWindsAloftMessageShared(String windsAloftMessageShared) {
            this.windsAloftMessageShared = windsAloftMessageShared;
        }
    
        public String getWindAloftAltitude0Shared() {
            return windAloftAltitude0Shared;
        }
    
        public void setWindAloftAltitude0Shared(String windAloftAltitude0Shared) {
            this.windAloftAltitude0Shared = windAloftAltitude0Shared;
        }
    
        public String getWindAloftAltitude1Shared() {
            return windAloftAltitude1Shared;
        }
    
        public void setWindAloftAltitude1Shared(String windAloftAltitude1Shared) {
            this.windAloftAltitude1Shared = windAloftAltitude1Shared;
        }
    
        public String getWindAloftAltitude2Shared() {
            return windAloftAltitude2Shared;
        }
    
        public void setWindAloftAltitude2Shared(String windAloftAltitude2Shared) {
            this.windAloftAltitude2Shared = windAloftAltitude2Shared;
        }
    }

    class MainFrame

    Java Code:
    package test4;
    
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    
    
    public class MainFrame extends javax.swing.JFrame {
        
        PanelWindsAloft panelWindsAloft;
        
    
        public MainFrame() {
            initComponents();
        }
    
        /**
         * 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() {
    
            panelContext = new javax.swing.JPanel();
            jPanel3 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jPanel2 = new javax.swing.JPanel();
            jLabel2 = new javax.swing.JLabel();
            jButton2 = new javax.swing.JButton();
            pnlWindsAloft = new javax.swing.JPanel();
            jButton3 = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            panelContext.setLayout(new java.awt.CardLayout());
    
            jLabel1.setText("CARD 1");
    
            jButton1.setText("CARD 2");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
            jPanel3.setLayout(jPanel3Layout);
            jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel3Layout.createSequentialGroup()
                            .addGap(325, 325, 325)
                            .addComponent(jLabel1))
                        .addGroup(jPanel3Layout.createSequentialGroup()
                            .addGap(35, 35, 35)
                            .addComponent(jButton1)))
                    .addContainerGap(333, Short.MAX_VALUE))
            );
            jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel3Layout.createSequentialGroup()
                    .addGap(17, 17, 17)
                    .addComponent(jButton1)
                    .addGap(51, 51, 51)
                    .addComponent(jLabel1)
                    .addContainerGap(439, Short.MAX_VALUE))
            );
    
            panelContext.add(jPanel3, "card1");
    
            jLabel2.setText("CARD 2");
    
            jButton2.setText("CARD 1");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout pnlWindsAloftLayout = new javax.swing.GroupLayout(pnlWindsAloft);
            pnlWindsAloft.setLayout(pnlWindsAloftLayout);
            pnlWindsAloftLayout.setHorizontalGroup(
                pnlWindsAloftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 317, Short.MAX_VALUE)
            );
            pnlWindsAloftLayout.setVerticalGroup(
                pnlWindsAloftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 394, Short.MAX_VALUE)
            );
    
            jButton3.setText("jButton3");
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addGap(32, 32, 32)
                            .addComponent(jButton2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3))
                        .addGroup(jPanel2Layout.createSequentialGroup()
                            .addGap(323, 323, 323)
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2)
                                .addComponent(pnlWindsAloft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addContainerGap(66, Short.MAX_VALUE))
            );
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGap(21, 21, 21)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton2)
                        .addComponent(jButton3))
                    .addGap(18, 18, 18)
                    .addComponent(jLabel2)
                    .addGap(39, 39, 39)
                    .addComponent(pnlWindsAloft, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(35, Short.MAX_VALUE))
            );
    
            panelContext.add(jPanel2, "card2");
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panelContext, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panelContext, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            );
    
            pack();
        }                      
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            CardLayout card = (CardLayout)panelContext.getLayout();
            card.show(panelContext, "card2");
            displayWindsAloft();
            
        }                                        
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            CardLayout card = (CardLayout)panelContext.getLayout();
            card.show(panelContext, "card1");
        }                                        
    
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            IGAWindsAloft windsObj = new IGAWindsAloft();
                windsObj.downloadWindXplane();
        }                                        
    
        
        public void displayWindsAloft()
        {
            if (panelWindsAloft == null)
            {
                // Initialize panel with the size equal pnlAltWinds size
                Dimension size = new Dimension(300,500);
                panelWindsAloft = new PanelWindsAloft(size);
                
                panelWindsAloft.setBounds(40,80,200,200);    
                panelWindsAloft.setBackground(Color.BLUE);  
                
                // Adding a component Listener so that the panel size would change if the Frame size changed
                pnlWindsAloft.addComponentListener(new ComponentListener() 
                {
                    @Override
                    public void componentResized(ComponentEvent e) 
                    { 
                        if (panelWindsAloft != null)
                        {
                            panelWindsAloft.setBox_width(pnlWindsAloft.getWidth());
                            panelWindsAloft.setBox_height(pnlWindsAloft.getHeight());
                            panelWindsAloft.revalidate();
                        }
                        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    }
    
                    @Override
                    public void componentMoved(ComponentEvent e) 
                    {
                        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    }
    
                    @Override
                    public void componentShown(ComponentEvent e) 
                    {    
                        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    }
    
                    @Override
                    public void componentHidden(ComponentEvent e) 
                    {
                        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    }
                });
    
                pnlWindsAloft.add(panelWindsAloft);
            }
            
            if(panelWindsAloft != null)
            {
                panelWindsAloft.calculateWindsAloftAltitudes();
                panelWindsAloft.revalidate();
                panelWindsAloft.repaint();
            }
        }
        
    
        public static void main(String args[]) {
            // Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            // If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
            // For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
    
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainFrame().setVisible(true);
                }
            });
        }
                   
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JPanel jPanel3;
        private javax.swing.JPanel panelContext;
        private javax.swing.JPanel pnlWindsAloft;                 
    }

    class IGAWindsAloft

    Java Code:
    package test4;
    
    
    import java.awt.Color;
    import java.awt.Dialog;
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JRootPane;
    import javax.swing.SwingUtilities;
    
    
    
    public class IGAWindsAloft 
    {
        AppSingleton appSingleton = AppSingleton.getInstance( );
    
        public void downloadWindXplane()
        {
     
                // Create notification dialog 
                JFrame f = new JFrame();
                JDialog modalDialog = new JDialog(f, "Busy", Dialog.ModalityType.MODELESS);
                modalDialog.setSize(200, 100);
                modalDialog.setLocationRelativeTo(f);
                modalDialog.setUndecorated(true);
                // Remove menu buttons
                modalDialog.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
                modalDialog.getContentPane().setBackground( Color.WHITE );
                // Add rotating activity indicator
                ImageIcon loading = new ImageIcon("src/images/activityIndicator.gif");
                modalDialog.add(new JLabel("Please wait... ", loading, JLabel.CENTER));
                // Set activity indicator visible
                modalDialog.setVisible(true);
    
                new Thread(() ->
                    {
                        String windsData = connectClient();
                        
                        /* When the activity in the background thread ends, change GUI on the
                        dispatch thread*/
                        SwingUtilities.invokeLater(() ->
                        {
                            // Close the pop-up menu when finished
                            modalDialog.setVisible(false);
                            modalDialog.dispose();
                            
                            // Calculate winds aloft data
                            calculateWindAloftsXplane(windsData);
                        });
                    }).start();
        }
        
    
        public String connectClient()
        {
         
            // Final message from the server
            String data = "";
            // Message from the server that should terminate TCP connection
            String  terminator = "END_IGOCONNECT_DATA";
            
            // Connection String
            URL url;
            BufferedReader in = null;
            
            // Name of Text file that has the airport ICAO code
            String fileName = ("http://www.igoapp.ca/windDataTest4.txt");
    	
            try 
            {
                url = new URL(fileName);
    
                URLConnection connection = url.openConnection();
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    
                StringBuilder sb = new StringBuilder();
                String s = "";
                int value = 0;
                
                // Process the message from the server and add to the StringBuilder
                while((value = in.read()) != -1) 
                {
                    // converts int to character
                    char c = (char)value;
    
                    sb.append(c);
                    
                    if(sb.toString().contains(terminator))
                    {
                        break;
                    }
                }
                
                // Create the final string
                data = sb.toString();    
            }
    	    
            catch (FileNotFoundException e) 
            {
                
            }
    	    
            catch (Exception e) 
            {
                
            }
    
            finally 	
            {
                if (in!=null)	
                {
                    try {
                        in.close();
                    } catch (IOException ex) {
                        Logger.getLogger(IGAWindsAloft.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            
            System.out.println("DOWNLOADED DATA " + data);
    		    
            return data;
        } 
        
        private void calculateWindAloftsXplane(String message)
        {
            // Break the received message into arrays
            String reportItems[] = message.split("\\|");
            String reporting = reportItems[1];
    
            String dataItems[] = reporting.split(":");
            
            appSingleton.setWindAloftAltitude0Shared(dataItems[0]);
            appSingleton.setWindAloftAltitude1Shared(dataItems[3]);
            appSingleton.setWindAloftAltitude2Shared(dataItems[6]);
            
            
            // Set Wind Label values
            MainFrame mainFrame = new MainFrame();
            mainFrame.displayWindsAloft();
        }
    }

    class PanelWindsAloft

    Java Code:
    package test4;
    
    
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Line2D;
    
    
    public class PanelWindsAloft extends javax.swing.JPanel 
    {
        AppSingleton appSingleton = AppSingleton.getInstance( );
    
        /** Width of the Panel. */
        private int box_width;
        /** Height of the Panel. */
        private int box_height;
        /** Width of the Container. */
        private int container_width;
        /** Height of the Container. */
        private int container_height;
        
        String windAloftAltitude0Big = "0";
        String windAloftAltitude1Big = "0";
        String windAloftAltitude2Big = "0";
        
    
        public PanelWindsAloft(Dimension dimension) 
        {
            // Get the size of the container
            this.box_width = (int)dimension.getWidth();
            this.box_height = (int)dimension.getHeight();
            
        }
        
        
        @Override
        public void paintComponent(Graphics g) 
        {
         
            super.paintComponent(g); 
      
            // Draw the box
            Graphics2D g2d = (Graphics2D)g.create();
            
            float windAloftAltitude0;
            float windAloftAltitude1;
            float windAloftAltitude2;
            try
            {
                int x = 0;
                int y = 20;
                container_width = getWidth()-80;
                container_height = getHeight()-40;
                
                // Set the gradient colors
                Color color1 = new Color(20,90,133);
                Color color2 = new Color(16,2,173);
                GradientPaint gp = new GradientPaint(0, 0, color2,0, container_height, color1);
                g2d.setPaint(gp);
                g2d.fillRect(x, y, container_width, container_height);
            
                windAloftAltitude0 = Float.parseFloat(appSingleton.getWindAloftAltitude0Shared());
                windAloftAltitude1 = Float.parseFloat(appSingleton.getWindAloftAltitude1Shared());
                windAloftAltitude2 = Float.parseFloat(appSingleton.getWindAloftAltitude2Shared());
                
                // Winds Altitudes as % of 0-40K feet. Deduct from 100% since it needs to be reversed
                float wind0Percent = 1 - windAloftAltitude0/40000f;
                float wind1Percent = 1 - windAloftAltitude1/40000f;
                float wind2Percent = 1 - windAloftAltitude2/40000f;
                
                int gridlineWind0_x1 = 0;
                int gridlineWind0_x2 = x+container_width+1;
                int gridlineWind0_y1 = (int)(y + container_height*wind0Percent);
                int gridlineWind0_y2 = gridlineWind0_y1;
                
                int gridlineWind1_x1 = 0;
                int gridlineWind1_x2 = x+container_width+1;
                int gridlineWind1_y1 = (int)(y + container_height*wind1Percent);
                int gridlineWind1_y2 = gridlineWind1_y1;
                
                int gridlineWind2_x1 = 0;
                int gridlineWind2_x2 = x+container_width+1;
                int gridlineWind2_y1 = (int)(y + container_height*wind2Percent);
                int gridlineWind2_y2 = gridlineWind2_y1;
                
                g2d.setColor(Color.WHITE);
                g2d.draw(new Line2D.Float(gridlineWind0_x1, gridlineWind0_y1, gridlineWind0_x2, gridlineWind0_y2));
                g2d.draw(new Line2D.Float(gridlineWind1_x1, gridlineWind1_y1, gridlineWind1_x2, gridlineWind1_y2));
                g2d.draw(new Line2D.Float(gridlineWind2_x1, gridlineWind2_y1, gridlineWind2_x2, gridlineWind2_y2));
                
            }
            catch(NumberFormatException e)
            {
                
            }
        }
        
    
        public void calculateWindsAloftAltitudes()
        {
            windAloftAltitude0Big = appSingleton.getWindAloftAltitude0Shared();
            windAloftAltitude1Big = appSingleton.getWindAloftAltitude1Shared();
            windAloftAltitude2Big = appSingleton.getWindAloftAltitude2Shared();
            
            System.out.println("ALT 1: " + windAloftAltitude0Big);
            System.out.println("ALT 2: " + windAloftAltitude1Big);
            System.out.println("ALT 3: " + windAloftAltitude2Big);
        }
        
                               
        private void initComponents() {
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            );
        }                   
    
    
        public int getBox_width() {
            return box_width;
        }
    
    
        public void setBox_width(int box_width) {
            this.box_width = box_width;
        }
    
    
        public int getBox_height() {
            return box_height;
        }
    
    
        public void setBox_height(int box_height) {
            this.box_height = box_height;
        }
    
    
        public int getContainer_width() {
            return container_width;
        }
    
    
        public void setContainer_width(int container_width) {
            this.container_width = container_width;
        }
    
    
        public int getContainer_height() {
            return container_height;
        }
    
    
        public void setContainer_height(int container_height) {
            this.container_height = container_height;
        }                 
    }
    Any suggestions? Thanks a lot!
    Last edited by igorland; 06-07-2017 at 03:10 AM.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,942
    Rep Power
    30

    Default Re: JPanel is not updated when I click on button

    Can you make and post a small complete program that compiles, executes and shows the problem?

    Also copy the full text of the console and paste it here showing the debug print outs.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,189
    Rep Power
    12

    Default Re: JPanel is not updated when I click on button

    I don't see where you add the panel to the JFrame. And you should not be extending JFrame. Just use a JFrame instance. Actually,
    you don't show much of anything. You should do what Norm asks. Make a complete working program to demonstrate the problem.
    That means "we" can easily compile it with no syntax or compiler errors.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  4. #4
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: JPanel is not updated when I click on button

    I have tried to write a simple example showing the problem (the original question has been updated). You download data on the second card and the JPanel is not updated (lines are not drawn). You go back to the first card and then again to the second card and the lines are shown as expected. This is my console output:

    ALT 1:
    ALT 2:
    ALT 3:
    DOWNLOADED DATA WIND|609.600037:14.5736046:0:2438.40015:14.5736046 :0:5486.3999:14.5736046:0
    END_IGOCONNECT_DATA
    ALT 1: 609.600037
    ALT 2: 2438.40015
    ALT 3: 5486.3999
    ALT 1: 609.600037
    ALT 2: 2438.40015
    ALT 3: 5486.3999


    Thank you so much, guys!

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: JPanel is not updated when I click on button

    You're using the GUI builder, which doesn't help us follow the code to be honest.
    Might also cause issues running it in a non-Netbeans environment (I don't know).

    Anyway, which class represents the panel that is not updating?
    Which method represents the button click you expect to happen?
    Which is the code that is supposed to pass on data to the panel?

    At the moment there's no indication of what you expect the flow to be, so it's hard to narrow down where the issue is.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: JPanel is not updated when I click on button

    Tolls. I know that it is a bit messy but I was asked to present a code that could be easily compiled.

    Anyway, which class represents the panel that is not updating?
    Class PanelWindsAloft draws the panel using paintComponent().

    Which method represents the button click you expect to happen?
    Class MainFrame.
    Method jButton3ActionPerformed(java.awt.event.ActionEvent evt) starts downloading the data.

    Which is the code that is supposed to pass on data to the panel?
    Data is stored in a singleton. Class MainFrame, method displayWindsAloft() triggers Panel to redraw the graph. This is not happening unless I go to another panel and return.

    Thank you.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,942
    Rep Power
    30

    Default Re: JPanel is not updated when I click on button

    Why are extra instances of the MainFrame class created?
    Last edited by Norm; 06-07-2017 at 01:07 PM.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: JPanel is not updated when I click on button

    Quote Originally Posted by Norm View Post
    Why are extra instances of the MainFrame class created?
    Yeah. That worries me as well. This is done to make sure that the method displayWindsAloft() in MainFrame is called only after data has been downloaded and processed.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,942
    Rep Power
    30

    Default Re: JPanel is not updated when I click on button

    Change the code to only use one instance.
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: JPanel is not updated when I click on button

    Any suggestions of the best way to do it? Thank you.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,942
    Rep Power
    30

    Default Re: JPanel is not updated when I click on button

    Make the reference to the class available where it is needed.
    If you don't understand my response, don't ignore it, ask a question.

  12. #12
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: JPanel is not updated when I click on button

    Sorry, Norm. I still do not understand. Are you talking about this?

    Java Code:
    // Set Wind Label values
    MainFrame mainFrame = new MainFrame();
    mainFrame.displayWindsAloft();
    If it is not needed here, where else? By the way, I have written a similar application in Swift and used a delegate to notify my view controller when to update the panel view. Here, I am completely at a loss. Cheers.

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,189
    Rep Power
    12

    Default Re: JPanel is not updated when I click on button

    If you haven't already done so, I would suggest you put print statements in strategic places to see if your button events are firing correctly. At the same time you may want to see if repaint is working as expected and if the data is there. And in case you didn't know, painting requires you to save subsequent data if you want it all displayed for each refresh. So whatever you painted before, will be gone unless you repaint it plus any new data.

    Also, on line 187 you create an anonymous class of ComponentListener. If you use ComponentAdapter, you won't have to provide the unimplemented method bodies.

    Regards,
    Jim
    igorland likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    19,942
    Rep Power
    30

    Default Re: JPanel is not updated when I click on button

    Some suggestions:
    Don't extend JFrame, create an instance of JFrame and use it.
    Pass a reference to the MainFrame class to the class that needs to calls its methods
    or move the displayWindsAloft method to another class.
    Is the displayWindsAloft() method in the right class?
    igorland likes this.
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: JPanel is not updated when I click on button

    Thanks, guys, for your hints. So I made printouts (hm... I seem to be unable to edit my original post). This is what I get:

    ----> Here I open the second Card with the download button:
    STEP 13: reloading panel.
    STEP 14: paint component.

    ----> Here I click on the download button:
    STEP 1: Button clicked.
    STEP 2: downloadWindXplane.
    STEP 3: connect to client on background thread.
    STEP 4: connect to client.
    STEP 5: data downloaded.
    DOWNLOADED DATA WIND|609.600037:14.5736046:0:2438.40015:14.5736046 :0:5486.3999:14.5736046:0
    END_IGOCONNECT_DATA
    STEP 6: Finishing downloading on background thread.
    STEP 7: calculate winds aloft xplane.
    STEP 8: passing to main frame.
    STEP 9: displaywindsaloft.
    STEP 10: initialize panel.
    STEP 11: call to calculating winds on the panel.
    STEP 12: calculating winds on the panel.
    ALT 1: 609.600037
    ALT 2: 2438.40015
    ALT 3: 5486.3999
    STEP 13: reloading panel.

    As you see, the panel is not re-initialized until the data has been downloaded and processed. Nevertheless, after it reinitialized, the paintComponent() method is not called at all. Why is that?

    Edit 1: Moving method displayWindsAloft() from class MainFrame to IGAWindsAloft does not help. Same problem. Panel is reinitialized but paintComponent is not called.

    Edit 2: Looks like moving all code from IGAWindsAloft to PanelWindsAloft solved the issue. On the other hand, I wanted to keep view controller code and business logic separate. Well...
    Last edited by igorland; 06-08-2017 at 01:29 AM.

  16. #16
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    25

    Default Re: JPanel is not updated when I click on button

    This goes back to the creation of a second MainFrame instance.

    Java Code:
            MainFrame mainFrame = new MainFrame();
            mainFrame.displayWindsAloft();
    You create a new instance here, and then call the display method.
    However that is not the MainFrame that is currently displayed.

    indeed that new MainFrame is never displayed.
    Because the panel you expect to see is associated with this invisible Frame then it to is never displayed, so a call to repaint does nothing...there's nothing visible so Swing doesn't bother doing any painting.

    This is not a terribly well constructed Swing app, but that is one of the side effects of using the GUI builder without really understanding Swing...and the GUI builder.
    Your app tends to become an unstructured blob of code.

    You ought to have a controller (or controllers) in there that manages all of this, from the navigation between panes to the acquiring of data.
    benji2505 likes this.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 10
    Last Post: 09-09-2014, 06:45 PM
  2. Replies: 8
    Last Post: 02-23-2012, 06:08 PM
  3. Replies: 3
    Last Post: 02-23-2012, 05:50 PM
  4. return value on a button click
    By wotupduck in forum New To Java
    Replies: 1
    Last Post: 03-24-2011, 01:09 PM
  5. SaveAs button click
    By kasiram.p@gmail.com in forum AWT / Swing
    Replies: 2
    Last Post: 07-06-2010, 08:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •