Home > Software design >  Open a new JFrame (with lots of components added before) by clicking JButton, but the problem is: th
Open a new JFrame (with lots of components added before) by clicking JButton, but the problem is: th

Time:12-21

I'm doing a java project and I've stumbled upon a problem.

I want to open another JFrame (with lots of components added before) by clicking a button in a JFrame. But the problem is: the Jframe-which I want to open- is completely EMPTY, BLANK, and can not be closed. I don't know why this is the case.

Here are the pictures of my Jframes. enter image description here - this is the frame that I want to open by click a button in another frame.

enter image description here - and this is my code for the button, so that when I click this button in another frame, it will open the frame in the above picture.

enter image description here -- and this is the frame opened after I click the button, completely empty and also I can not close it, even though I want to open the frame in the first image above, with lots of images in it.

Hope that you guys can support me on this.

Thank you! Have a nice day!!!

I have tried many solutions, but they didn't work.

The 1st file is called: DisplayTimeDate.java

    import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class DisplayTimeDate extends JFrame {

    Calendar calendar;
    SimpleDateFormat timeFormat;
    SimpleDateFormat dayFormat;
    SimpleDateFormat dateFormat;
    JLabel timeLabel;
    JLabel dayLabel;
    JLabel dateLabel;
    String time;
    String day;
    String date;
    private JButton btnNewButton;

    public DisplayTimeDate() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("My Clock Program");
        this.setSize(350, 200);
        this.setResizable(false);

        timeFormat = new SimpleDateFormat("hh:mm:ss a");
        dayFormat = new SimpleDateFormat("EEEE");
        dateFormat = new SimpleDateFormat("MMMMM dd, yyyy");

        timeLabel = new JLabel();
        timeLabel.setFont(new Font("Verdana", Font.PLAIN, 50));
        timeLabel.setForeground(new Color(0x00FF00));
        timeLabel.setBackground(Color.black);
        timeLabel.setOpaque(true);

        dayLabel = new JLabel();
        dayLabel.setFont(new Font("Ink Free", Font.PLAIN, 35));

        dateLabel = new JLabel();
        dateLabel.setFont(new Font("Ink Free", Font.PLAIN, 25));
        getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        btnNewButton = new JButton("");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//              dispose();
//               Order_Food_frames obj = new Order_Food_frames(); obj.setVisible(true);
                

                dispose();
                testTime_take_2 newFrame = new testTime_take_2(); newFrame.setVisible(true);
//              // dispose();
            }
        });
        getContentPane().add(btnNewButton);

        getContentPane().add(timeLabel);
        getContentPane().add(dayLabel);
        getContentPane().add(dateLabel);
        this.setVisible(true);

        setTime();
    }

    public void setTime() {
        while (true) {
            time = timeFormat.format(Calendar.getInstance().getTime());
            timeLabel.setText(time);

            day = dayFormat.format(Calendar.getInstance().getTime());
            dayLabel.setText(day);

            date = dateFormat.format(Calendar.getInstance().getTime());
            dateLabel.setText(date);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {

        new DisplayTimeDate();
    }
}

And this is the: testTime_take_2.java , it is the frame I want to open when clicking button:

import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.SwingConstants;

public class testTime_take_2 extends JFrame {
private static JFrame frame;
    private JPanel contentPane;
    //Calendar calendar;
    SimpleDateFormat timeFormat;
    SimpleDateFormat dayFormat;
    SimpleDateFormat dateFormat;
    JLabel timeLabel;
    JLabel dayLabel;
    String day;
    String time;
    String date;
    private JLabel dateLabel;

//  public void setTime() {
//        while(true) {
//        time = timeFormat.format(Calendar.getInstance().getTime());
//        timeLabel.setText(time);
//        
////          day = dayFormat.format(Calendar.getInstance().getTime());
////          dayLabel.setText(day);
////          
////          date = dateFormat.format(Calendar.getInstance().getTime());
////          dateLabel.setText(date);
////          
//        try {
//         Thread.sleep(1000);
//        } catch (InterruptedException e) {
//         // TODO Auto-generated catch block
//         e.printStackTrace();
//        }
//        }
//       }
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
         //frame = new JFrame();
        new testTime_take_2();
    }

    /**
     * Create the frame.
     */
    public testTime_take_2() { frame = new JFrame();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        //setVisible(true);

        setContentPane(contentPane);
        
        timeFormat = new SimpleDateFormat("hh:mm:ss a");
        dayFormat = new SimpleDateFormat("EEEE");
        dateFormat = new SimpleDateFormat("dd-MMMMM-yyyy");
        //time = timeFormat.format(Calendar.getInstance().getTime());
        contentPane.setLayout(null);
        
        timeLabel = new JLabel();
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        timeLabel.setBounds(151, 45, 112, 14);
        timeLabel.setText(time);
        
        dayLabel = new JLabel();
        dayLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dayLabel.setBounds(151, 100, 112, 14);
        getContentPane().add(timeLabel);
        getContentPane().add(dayLabel);
        
        dateLabel = new JLabel();
        dateLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dateLabel.setBounds(151, 151, 112, 14);
        contentPane.add(dateLabel);
        setVisible(true);
        setTime();
    }
    public void setTime() {
          while(true) {
          time = timeFormat.format(Calendar.getInstance().getTime());
          
          timeLabel.setText(time);
          
          day = dayFormat.format(Calendar.getInstance().getTime());
          dayLabel.setText(day);
          
          date = dateFormat.format(Calendar.getInstance().getTime());
          dateLabel.setText(date);
          
          try {
           Thread.sleep(1000);
          } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
          }
          }
         }
//  

    public static void main(String[] args) {
    //      testTime_take_2 frame = new testTime_take_2();
    //  }
    
    }

And the frame I want to open when clicking the button in DisplayTimeDate

CodePudding user response:

"I think the problem comes from the setTime() function, I guess because setTime() contains: Thread???"

That's one problem along with a lot of others in both classes. That while (true) { to run a clock is never a good idea. I don't think it's a good idea for anything! It just bungs up the EDT. Use a Swing Timer instead (in both classes).

In the testTime_take_2 class (which should be named TestTimeTake2) you extend JFrame yet you also declare a public static JFrame and instantiate it within the constructor. Get rid of it. The extends JFrame is good enough for this use-case.

I have quickly reworked the code so that it works. When you click the button on the first form, that form closes and the second form opens. When you close the second form, the first form opens again (you can easily change this).

The DisplayTimeDate class:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class DisplayTimeDate extends JFrame {

    private static final long serialVersionUID = 425524L;

    Calendar calendar;
    SimpleDateFormat timeFormat;
    SimpleDateFormat dayFormat;
    SimpleDateFormat dateFormat;
    JLabel timeLabel;
    JLabel dayLabel;
    JLabel dateLabel;
    String time;
    String day;
    String date;
    private JButton btnNewButton;

    javax.swing.Timer clockTimer;

    public DisplayTimeDate() {
        initializeForm();
    }

    @SuppressWarnings("Convert2Lambda")
    private void initializeForm() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                clockTimer.stop();
            }
        });
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setTitle("My Clock Program");
        setAlwaysOnTop(true);  // Form always ON TOP
        setSize(350, 200);
        setResizable(false);

        timeFormat = new SimpleDateFormat("hh:mm:ss a");
        dayFormat = new SimpleDateFormat("EEEE");
        dateFormat = new SimpleDateFormat("MMMMM dd, yyyy");

        timeLabel = new JLabel();
        timeLabel.setFont(new Font("Verdana", Font.PLAIN, 50));
        timeLabel.setForeground(new Color(0x00FF00));
        timeLabel.setBackground(Color.black);
        timeLabel.setOpaque(true);

        dayLabel = new JLabel();
        dayLabel.setFont(new Font("Ink Free", Font.PLAIN, 35));

        dateLabel = new JLabel();
        dateLabel.setFont(new Font("Ink Free", Font.PLAIN, 25));
        getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        btnNewButton = new JButton("");
        btnNewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                java.awt.EventQueue.invokeLater(() -> {
                    new TestTimeTake2().setVisible(true);
                });
            }
        });
        getContentPane().add(btnNewButton);

        getContentPane().add(timeLabel);
        getContentPane().add(dayLabel);
        getContentPane().add(dateLabel);
        
        setLocationRelativeTo(null);
        setTime();
    }

    @SuppressWarnings("Convert2Lambda")
    public void setTime() {
        // Create a Swing Timer thread.
        clockTimer = new javax.swing.Timer(1000,
                                  new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent ae) {
                // Code you want to run on every timer cycle goes here.
                time = timeFormat.format(Calendar.getInstance().getTime());
                timeLabel.setText(time);

                day = dayFormat.format(Calendar.getInstance().getTime());
                dayLabel.setText(day);

                date = dateFormat.format(Calendar.getInstance().getTime());
                dateLabel.setText(date);
                // System.out.println("Timer Cycled!");
            }
        });

        // To Start the swing timer
        clockTimer.start();
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(() -> {
            new DisplayTimeDate().setVisible(true);
       });
        
    }
}

The TestTimeTake2 class:

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;


public class TestTimeTake2 extends JFrame {

    private static final long serialVersionUID = 342241L;
    
    private JPanel contentPane;
    //Calendar calendar;
    SimpleDateFormat timeFormat;
    SimpleDateFormat dayFormat;
    SimpleDateFormat dateFormat;
    JLabel timeLabel;
    JLabel dayLabel;
    String day;
    String time;
    String date;
    private JLabel dateLabel;
    
    
    javax.swing.Timer clockTimer2;
    

    /**
     * Create the frame.
     */
    public TestTimeTake2() {
        initializeForm();
    }

    private void initializeForm() {
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                clockTimer2.stop();
                java.awt.EventQueue.invokeLater(() -> {
                    new DisplayTimeDate().setVisible(true);
                });
            }
        });
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        
        setContentPane(contentPane);

        timeFormat = new SimpleDateFormat("hh:mm:ss a");
        dayFormat = new SimpleDateFormat("EEEE");
        dateFormat = new SimpleDateFormat("dd-MMMMM-yyyy");
        contentPane.setLayout(null);

        timeLabel = new JLabel();
        timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        timeLabel.setBounds(151, 45, 112, 14);
        timeLabel.setText(time);

        dayLabel = new JLabel();
        dayLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dayLabel.setBounds(151, 100, 112, 14);
        getContentPane().add(timeLabel);
        getContentPane().add(dayLabel);

        dateLabel = new JLabel();
        dateLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dateLabel.setBounds(151, 151, 112, 14);
        contentPane.add(dateLabel);
        setLocationRelativeTo(null);
        setTime();
    }
    
    @SuppressWarnings("Convert2Lambda")
    public void setTime() {
        // Create a Swing Timer thread.
        clockTimer2 = new javax.swing.Timer(1000,
                                  new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent ae) {
                // Code you want to run on every timer cycle goes here.
                time = timeFormat.format(Calendar.getInstance().getTime());
                timeLabel.setText(time);

                day = dayFormat.format(Calendar.getInstance().getTime());
                dayLabel.setText(day);

                date = dateFormat.format(Calendar.getInstance().getTime());
                dateLabel.setText(date);
                //System.out.println("Timer 2 Cycled!");
            }
        });

        // To Start the swing timer
        clockTimer2.start();
    }
    
}
  • Related