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 5 of 5

Thread: Label does not display the second time

  1. #1
    Junior Member
    Join Date
    Jul 2024
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Label does not display the second time

    I apologize if the seems like a long post, but i do need help. I am working on an app the stumps me in one particular issue. It would use a "Please Wait" label while some image procession is going on. My problem is I can have it do it once, the second and subsequent time no label visible, meaning none is showing on display, I have worked unsuccessfully with ChatGpt. It's suggestions keeps giving me the same results. The code included here is the method that is under suspicion.

    It is basically from a single java file app, with a frame containing 2 panels, one for the eventual image, one for controls at the bottom. When the app starts it call a method loadImage() (with some angle, but that's not a issue here). That method displays the Please Wait label, and after a while it removes the label. Good so far. When I then click a button it calls the same method, but this time there is no wait label, and none on subsequent clicks.

    I have implemented fairly detailed logging, and it shows me that all the statements are executed in the correct order, and repeatedly when the button is clicked. But still no wait label. I have run the app with debug form VS Code 2022, but get no better results.

    If it's not asking too much, could one of you guru's look at the code and give me hint at what to do. Your help will be hugely appreciated.

    executed in main()
    {
    // Initialize waitLabel
    waitLabel = new JLabel("Please Wait", SwingConstants.CENTER);
    waitLabel.setFont(new Font("Serif", Font.BOLD, 70));
    waitLabel.setForeground(Color.RED);
    waitLabel.setOpaque(true);
    log("main - 19. - initialized waitLabel");

    log("main - 21. - before loadImage");
    // Call loadImage with angle 0
    loadImage(0);
    log("main - 22. - returned from loadImage");
    }

    public static void loadImage(int angle) {
    log("loadImage - 40. - loadImage started");

    // Show waitLabel
    imagePanel.add(waitLabel, BorderLayout.CENTER);
    waitLabel.setVisible(true);
    log("loadImage - 20. - waitLabel added to imagePanel");

    imagePanel.revalidate();
    imagePanel.repaint();
    log("loadImage - 41. - waitLabel show");

    // Pause for 5 seconds
    try {
    log("loadImage - 42. - pause started");
    Thread.sleep(5000);
    log("loadImage - 43. - pause complete");
    } catch (InterruptedException e) {
    e.printStackTrace();
    log("loadImage - 44. - error during pause: " + e.getMessage());
    }

    // Remove waitLabel
    imagePanel.removeAll();
    imagePanel.revalidate();
    imagePanel.repaint();
    log("loadImage - 45. - waitLabel hidden");
    }
    There should be a way to send the complete java file, but I don't see any buttons or links. May be my access rights are too low, this is my first post.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Label does not display the second time

    Can you make a small, complete program that will compile, execute and show the problem?

    Be sure to wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jul 2024
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Label does not display the second time

    Ah, the "code" , that's why I couldn't submit my previous post. Yes, here is complete listing. It compiles, no error, it run, no errors as such, except no "Please Wait" when I click on the rotate button (that's what I meant by "second time"). Again, your help will be greatly appreciated.
    // Beginning
    package SplitPng;
     
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
     
    public class SplitPng {
     
        // Declare global variables
     
        // turn logging on/off
        static boolean doLog = true;
     
        static JFrame frame;
        static JPanel imagePanel, controlsPanel;
        static JLabel waitLabel;
        static JLabel messageLabel;
        static JButton rotateButton, closeButton;
        static final String LOG_FILE_PATH = "./log.txt"; // Log file in the application execution folder
     
        public static void main(String[] args) {
            // Start logging
            log("main - 1. - appINI");
     
            // Set up the frame
            frame = new JFrame("SplitPng");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
            log("main - 2. - frame configured");
     
            // Add close button to frame
            frame.setUndecorated(false);
            log("main - 3. - close button added");
     
            // Ensure frame gets the preferred size of imagePanel
            frame.pack();
            log("main - 4. - frame packed");
     
            // Set up the panels
            frame.setLayout(new BorderLayout());
            log("main - 5. - frame layout set");
     
            // Initialize and configure imagePanel
            imagePanel = new JPanel();
            log("main - 6. - initialized imagePanel");
     
            frame.add(imagePanel, BorderLayout.CENTER);
            log("main - 7. - imagePanel added to frame");
     
            // Initialize controlsPanel
            controlsPanel = new JPanel();
            log("main - 8. - initialized controlsPanel");
     
            // Initialize and add the rotate button
            rotateButton = new JButton("Rotate Image");
            log("main - 9. - initialized rotateButton");
            rotateButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    log("main - 10. - rotateButton clicked");
                    // Call loadImage with angle 0
                    loadImage(0);
                    log("main - 11. - returned from rotateButton clicked");
                }
            });
            controlsPanel.add(rotateButton);
            log("main - 12. - added rotateButton");
     
            // Initialize and add the close button
            closeButton = new JButton("Close App");
            log("main - 13. - initialized closeButton");
            closeButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    log("main - 14. - closeButton clicked");
                    System.exit(0);
                }
            });
            controlsPanel.add(closeButton);
            log("main - 15. - added closeButton");
     
            frame.add(controlsPanel, BorderLayout.SOUTH);
            log("main - 16. - controlsPanel added to frame");
     
            // Display the frame
            frame.setVisible(true);
            log("main - 17. - frame visible");
     
            // Configure imagePanel
            imagePanel.setLayout(new BorderLayout());
            log("main - 18. - configured imagePanel");
     
            // Initialize waitLabel
            waitLabel = new JLabel("Please Wait", SwingConstants.CENTER);
            waitLabel.setFont(new Font("Serif", Font.BOLD, 70));
            waitLabel.setForeground(Color.RED);
            waitLabel.setOpaque(true);
            log("main - 19. - initialized waitLabel");
     
            log("main - 21. - before loadImage");
            // Call loadImage with angle 0
            loadImage(0);
            log("main - 22. - returned from loadImage");
        }
     
        public static void loadImage(int angle) {
            log("loadImage - 40. - loadImage started");
     
            // Show waitLabel
            imagePanel.add(waitLabel, BorderLayout.CENTER);
            waitLabel.setVisible(true);
            log("loadImage - 20. - waitLabel added to imagePanel");
     
            imagePanel.revalidate();
            imagePanel.repaint();
            log("loadImage - 41. - waitLabel show");
     
            // Pause for 5 seconds
            try {
                log("loadImage - 42. - pause started");
                Thread.sleep(5000);
                log("loadImage - 43. - pause complete");
            } catch (InterruptedException e) {
                e.printStackTrace();
                log("loadImage - 44. - error during pause: " + e.getMessage());
            }
     
            // Hide waitLabel
            imagePanel.removeAll();
            imagePanel.revalidate();
            imagePanel.repaint();
            log("loadImage - 45. - waitLabel hidden");
        }
     
        public static void log(String message) {
            if (doLog) {
                try (FileWriter writer = new FileWriter(LOG_FILE_PATH, true)) {
                    writer.write(String.format("%09d",
                            Long.parseLong(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))))
                            + " - "
                            + message + "\n");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    // End

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Label does not display the second time

    Adding and removing GUI components is tricky. I do not have a solution for that problem yet.
    However, internet searches bring up recommendations for a different technique for changing what is displayed:
    Use the CardLayout
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Label does not display the second time

    The problem with your code is when that the loadImage method executes on Event Dispatch Thread (EDT) that is used by the Swing GUI engine. While your method is executing, Swing can not update the GUI. The actionPerformed method is executed on the EDT.
    For more information go to this site and lookup: Event Dispatch Thread
    https://docs.oracle.com/javase/tutor...ybigindex.html
    Save that link as it has lots of good documentation.

    The solution is for the code in loadImage to be broken up into pieces: first set the GUI and start another task to do the work off of the EDT
    When that task is done, change the GUI to report. That all can be done with the SwingWorker class.
    Here is an example of what your loadImage could look like:
        static boolean oneTime = true;
        public static void loadImage(int angle) {
            System.out.println("thread="+Thread.currentThread().getName()); // first main, then  AWT-EventQueue-0
            log("loadImage - 40. - loadImage started");
     
            // Show waitLabel
            if(oneTime) {
               imagePanel.add(waitLabel, BorderLayout.CENTER); 
               oneTime = false;
            }
     
            waitLabel.setVisible(true);
            log("loadImage - 20. - waitLabel added to imagePanel");
     
            imagePanel.revalidate();
            imagePanel.repaint();
            log("loadImage - 41. - waitLabel show");
     
          class DoWork extends SwingWorker<Void, Void>  {  
              @Override
              public Void doInBackground() {
                   System.out.println("dIBg thread="+Thread.currentThread().getName());
                  rotateButton.setEnabled(false);  // do not allow while doing work
                  // Pause for 5 seconds
                  try {
                      log("loadImage - 42. - pause started");
                      Thread.sleep(5000);               // if ON the EST - hangs the GUI updating and button response
                      log("loadImage - 43. - pause complete");
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                      log("loadImage - 44. - error during pause: " + e.getMessage());
                  }
                  return null;
              }
     
              @Override
              public void done() {
                  System.out.println("done thread="+Thread.currentThread().getName());
                  rotateButton.setEnabled(true);  //  allow when done
                // Hide waitLabel
                  waitLabel.setVisible(false); 
                  imagePanel.revalidate();
                  imagePanel.repaint();
                  log("loadImage - 45. - waitLabel hidden");
              }
          };
           (new DoWork()).execute();
     
        }
    To see what thread the code is executing on, insert this statement:
    System.out.println("thread="+Thread.currentThread( ).getName());
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [SOLVED] How To get Data button to Display user inputted "numbers" to data label?
    By Supreme233 in forum What's Wrong With My Code?
    Replies: 12
    Last Post: May 26th, 2014, 02:41 PM
  2. Issues With Layout And Time Being Display
    By digitalsystems in forum AWT / Java Swing
    Replies: 16
    Last Post: April 21st, 2014, 08:23 AM
  3. How to display data and time in JTable
    By kpat in forum AWT / Java Swing
    Replies: 2
    Last Post: April 8th, 2012, 12:19 PM
  4. Replies: 4
    Last Post: July 21st, 2010, 04:07 PM
  5. display time
    By kalees in forum JavaServer Pages: JSP & JSTL
    Replies: 0
    Last Post: January 1st, 2010, 07:40 AM

Tags for this Thread