Jump to content

Java Swing Timer to hide and show components

Go to solution Solved by LukeTim,

 

Yeah if I had more time, I could clean up some logic but the project that I'm working on at school has a few weeks to design the GUI and get the logic working. Hell, I'm just using setVisible to navigate between the frames. I know I should use the cardlayout but I haven't got time to implement it.

 

I actually wanted for SearchingForYour and Imagelabel to be visible on clicking submit and disappear after 5 seconds and at the same time have MatchFound and ProceedToChat be visible.

 

Anyway, after playing around with the ActionListeners, I managed to get it working. MatchFound and ProceedToChat has to be in a different ActionListener than the components that I'm hiding.

ActionListener taskPerformer = new ActionListener() {            public void actionPerformed(ActionEvent evt) {            	lblSearchingForYour.setVisible(false);				imagelabel.setVisible(false);            }        };        Timer timer = new Timer(5000, taskPerformer);                ActionListener resultDisplay = new ActionListener() {        	public void actionPerformed(ActionEvent evt) {				lblMatchFound.setVisible(true);				btnProceedToChat.setVisible(true);        	}        };        Timer displaytimer = new Timer(5000, resultDisplay);                btnSubmit.addActionListener(new ActionListener() {			public void actionPerformed(ActionEvent e) {				lblSearchingForYour.setVisible(true);				imagelabel.setVisible(true);				btnClear.setEnabled(false);				btnSubmit.setEnabled(false);				btnUploadPicture.setEnabled(false);				timer.start();				displaytimer.start();			}		});

 

 

It was putting the timer.start() calls in the button submit action listener that has fixed it for you. Before, you were starting the timer at the end of your constructor. Hence, 5 seconds after starting the application the timer fired and they showed up. There wasn't really a need to split them up into two separate timers.

import java.awt.EventQueue;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.swing.JLabel;import javax.swing.SwingConstants;import javax.swing.JButton;import java.awt.Color;import javax.swing.JRadioButton;import javax.swing.JTextField;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.io.IOException;import javax.swing.*;import javax.swing.Timer;public class Matchmaking extends JFrame {	private JPanel contentPane;	private JTextField textField;	private JTextField textField_1;	private JTextField textField_2;		public final static int FIVE_SECOND = 5000;	/**	 * Launch the application.	 */	public static void main(String[] args) throws IOException{		EventQueue.invokeLater(new Runnable() {			public void run() {				try {					Matchmaking frame = new Matchmaking();					frame.setVisible(true);				} catch (Exception e) {					e.printStackTrace();				}			}		});	}	/**	 * Create the frame.	 * @throws IOException 	 */	public Matchmaking() throws IOException {		setTitle("Matchmaker");		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);		setBounds(100, 100, 450, 300);		contentPane = new JPanel();		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));		setContentPane(contentPane);		contentPane.setLayout(null);				JButton btnSubmit = new JButton("Search");				btnSubmit.setBounds(14, 164, 116, 23);		contentPane.add(btnSubmit);				JButton btnClear = new JButton("Reset");		btnClear.setBounds(14, 198, 116, 23);		contentPane.add(btnClear);				JButton btnBack = new JButton("Back");		btnBack.setBounds(14, 232, 116, 23);		contentPane.add(btnBack);				JLabel lblProfilePicture = new JLabel("Profile Picture");		lblProfilePicture.setBackground(Color.YELLOW);		lblProfilePicture.setHorizontalAlignment(SwingConstants.CENTER);		lblProfilePicture.setBounds(14, 11, 116, 106);		contentPane.add(lblProfilePicture);				JLabel lblName = new JLabel("Name:");		lblName.setBounds(167, 40, 46, 14);		contentPane.add(lblName);				JLabel lblAge = new JLabel("Age:");		lblAge.setBounds(167, 65, 46, 14);		contentPane.add(lblAge);				JLabel lblGender = new JLabel("Gender:");		lblGender.setBounds(167, 90, 46, 14);		contentPane.add(lblGender);				JRadioButton rdbtnMale = new JRadioButton("Male");		rdbtnMale.setBounds(245, 86, 54, 23);		contentPane.add(rdbtnMale);				JRadioButton rdbtnFemale = new JRadioButton("Female");		rdbtnFemale.setBounds(307, 86, 84, 23);		contentPane.add(rdbtnFemale);				textField = new JTextField();		textField.setBounds(206, 37, 185, 20);		contentPane.add(textField);		textField.setColumns(10);				textField_1 = new JTextField();		textField_1.setBounds(206, 62, 185, 20);		contentPane.add(textField_1);		textField_1.setColumns(10);				JLabel lblEmail = new JLabel("Email:");		lblEmail.setBounds(167, 115, 46, 14);		contentPane.add(lblEmail);				JLabel lblPreference = new JLabel("Preference:");		lblPreference.setBounds(167, 143, 59, 14);		contentPane.add(lblPreference);				JRadioButton prefmale = new JRadioButton("Male");		prefmale.setBounds(245, 139, 54, 23);		contentPane.add(prefmale);				JRadioButton preffemale = new JRadioButton("Female");		preffemale.setBounds(307, 139, 84, 23);		contentPane.add(preffemale);				ButtonGroup group = new ButtonGroup();		group.add(rdbtnMale);		group.add(rdbtnFemale);				textField_2 = new JTextField();		textField_2.setBounds(206, 112, 185, 20);		contentPane.add(textField_2);		textField_2.setColumns(10);				final JLabel lblSearchingForYour = new JLabel("Searching for your match...");		lblSearchingForYour.setBounds(167, 181, 220, 14);		contentPane.add(lblSearchingForYour);		lblSearchingForYour.setVisible(false);				final JLabel lblMatchFound = new JLabel("Match found!");		lblMatchFound.setBounds(167, 202, 132, 14);		contentPane.add(lblMatchFound);		lblMatchFound.setVisible(false);				JButton btnProceedToChat = new JButton("Proceed to chat >");		btnProceedToChat.setBounds(245, 198, 146, 23);		contentPane.add(btnProceedToChat);		btnProceedToChat.setVisible(false);				JButton btnUploadPicture = new JButton("Upload Picture");		btnUploadPicture.setBounds(14, 130, 116, 23);		contentPane.add(btnUploadPicture);				ImageIcon image = new ImageIcon("Images/245.GIF");		final JLabel imagelabel = new JLabel(image);		imagelabel.setBounds(167, 202, 224, 14);		contentPane.add(imagelabel);		imagelabel.setVisible(false);				btnClear.addActionListener(new ActionListener() {			public void actionPerformed(ActionEvent e) {				textField.setText("");				textField_1.setText("");				textField_2.setText("");				group.clearSelection();				prefmale.setSelected(false);				preffemale.setSelected(false);				lblSearchingForYour.setVisible(false);				imagelabel.setVisible(false);				lblMatchFound.setVisible(false);				btnProceedToChat.setVisible(false);			}		});				btnSubmit.addActionListener(new ActionListener() {			public void actionPerformed(ActionEvent e) {				lblSearchingForYour.setVisible(true);				imagelabel.setVisible(true);				btnClear.setEnabled(false);				btnSubmit.setEnabled(false);				btnUploadPicture.setEnabled(false);							}		});				ActionListener taskPerformer = new ActionListener() {            public void actionPerformed(ActionEvent evt) {            	lblSearchingForYour.setVisible(false);				imagelabel.setVisible(false);				lblMatchFound.setVisible(true);				btnProceedToChat.setVisible(true);            }        };        Timer timer = new Timer(5000, taskPerformer);        timer.start();	}}

The above code should hide SearchingForYour and imagelabel and show MatchFound and ProceedToChat when I click on the Search JButton but whenever I run the program and idle, both MatchFound and ProceedToChat appears without me pressing any buttons at all. I think it has to do with my implementation of the delay timer in the actionlistener. What did I do wrong?

~~~SnapDragon~~~

| CPU: AMD Ryzen 9 9950X3D | CPU Cooler: Gigabyte Aorus Waterforce X II 360mm |RAM: 2x32GB G.Skill Trident Z5 Neo RGB 6000MHz | Mobo: Gigabyte X870E Aorus Xtreme X3D AI Top  | Storage: Samsung 9100 Pro 4TB + Samsung 990 Pro 4TB + Samsung 870 Evo 4TB + Samsung 870 Evo 2TB | Graphics Card: Gigabyte RTX 5090 Aorus Master 32G | Case: Lian Li Lancool 216 | PSU: Seasonic Vertex GX-1200 |

 

Link to comment
https://linustechtips.com/topic/502553-java-swing-timer-to-hide-and-show-components/
Share on other sites

Link to post
Share on other sites

Thanks for using code tags, but please fix your code indentation too. It's impossible to read in its current state.

 

Oh damn my editing on my phone messed it up.

 

Lemme fix that.

 

Edit: Done. I think I need to clean up some imports tho

~~~SnapDragon~~~

| CPU: AMD Ryzen 9 9950X3D | CPU Cooler: Gigabyte Aorus Waterforce X II 360mm |RAM: 2x32GB G.Skill Trident Z5 Neo RGB 6000MHz | Mobo: Gigabyte X870E Aorus Xtreme X3D AI Top  | Storage: Samsung 9100 Pro 4TB + Samsung 990 Pro 4TB + Samsung 870 Evo 4TB + Samsung 870 Evo 2TB | Graphics Card: Gigabyte RTX 5090 Aorus Master 32G | Case: Lian Li Lancool 216 | PSU: Seasonic Vertex GX-1200 |

 

Link to post
Share on other sites

I've not used Java Swing (or Java at all) since Uni but I'll see what I can figure out.

You seem to have set MatchFound and ProceedToChat to set to Visible after a 5 second timer. So the behaviour you're describing sounds exactly like what the code should be doing.

Now sure what the problem is?

Also, dat monolithic constructor... I would factor some of that out.

And perhaps move the main() function into another class "Program", or "Application". I mean, it works but personally I don't like the idea of having the main function being part of a functional class within the program itself...

 

Link to post
Share on other sites

I've not used Java Swing (or Java at all) since Uni but I'll see what I can figure out.

You seem to have set MatchFound and ProceedToChat to set to Visible after a 5 second timer. So the behaviour you're describing sounds exactly like what the code should be doing.

Now sure what the problem is?

Also, dat monolithic constructor... I would factor some of that out.

And perhaps move the main() function into another class "Program", or "Application". I mean, it works but personally I don't like the idea of having the main function being part of a functional class within the program itself...

 

 

Yeah if I had more time, I could clean up some logic but the project that I'm working on at school has a few weeks to design the GUI and get the logic working. Hell, I'm just using setVisible to navigate between the frames. I know I should use the cardlayout but I haven't got time to implement it.

 

I actually wanted for SearchingForYour and Imagelabel to be visible on clicking submit and disappear after 5 seconds and at the same time have MatchFound and ProceedToChat be visible.

 

Anyway, after playing around with the ActionListeners, I managed to get it working. MatchFound and ProceedToChat has to be in a different ActionListener than the components that I'm hiding.

ActionListener taskPerformer = new ActionListener() {            public void actionPerformed(ActionEvent evt) {            	lblSearchingForYour.setVisible(false);				imagelabel.setVisible(false);            }        };        Timer timer = new Timer(5000, taskPerformer);                ActionListener resultDisplay = new ActionListener() {        	public void actionPerformed(ActionEvent evt) {				lblMatchFound.setVisible(true);				btnProceedToChat.setVisible(true);        	}        };        Timer displaytimer = new Timer(5000, resultDisplay);                btnSubmit.addActionListener(new ActionListener() {			public void actionPerformed(ActionEvent e) {				lblSearchingForYour.setVisible(true);				imagelabel.setVisible(true);				btnClear.setEnabled(false);				btnSubmit.setEnabled(false);				btnUploadPicture.setEnabled(false);				timer.start();				displaytimer.start();			}		});

~~~SnapDragon~~~

| CPU: AMD Ryzen 9 9950X3D | CPU Cooler: Gigabyte Aorus Waterforce X II 360mm |RAM: 2x32GB G.Skill Trident Z5 Neo RGB 6000MHz | Mobo: Gigabyte X870E Aorus Xtreme X3D AI Top  | Storage: Samsung 9100 Pro 4TB + Samsung 990 Pro 4TB + Samsung 870 Evo 4TB + Samsung 870 Evo 2TB | Graphics Card: Gigabyte RTX 5090 Aorus Master 32G | Case: Lian Li Lancool 216 | PSU: Seasonic Vertex GX-1200 |

 

Link to post
Share on other sites

 

Yeah if I had more time, I could clean up some logic but the project that I'm working on at school has a few weeks to design the GUI and get the logic working. Hell, I'm just using setVisible to navigate between the frames. I know I should use the cardlayout but I haven't got time to implement it.

 

I actually wanted for SearchingForYour and Imagelabel to be visible on clicking submit and disappear after 5 seconds and at the same time have MatchFound and ProceedToChat be visible.

 

Anyway, after playing around with the ActionListeners, I managed to get it working. MatchFound and ProceedToChat has to be in a different ActionListener than the components that I'm hiding.

ActionListener taskPerformer = new ActionListener() {            public void actionPerformed(ActionEvent evt) {            	lblSearchingForYour.setVisible(false);				imagelabel.setVisible(false);            }        };        Timer timer = new Timer(5000, taskPerformer);                ActionListener resultDisplay = new ActionListener() {        	public void actionPerformed(ActionEvent evt) {				lblMatchFound.setVisible(true);				btnProceedToChat.setVisible(true);        	}        };        Timer displaytimer = new Timer(5000, resultDisplay);                btnSubmit.addActionListener(new ActionListener() {			public void actionPerformed(ActionEvent e) {				lblSearchingForYour.setVisible(true);				imagelabel.setVisible(true);				btnClear.setEnabled(false);				btnSubmit.setEnabled(false);				btnUploadPicture.setEnabled(false);				timer.start();				displaytimer.start();			}		});

 

 

It was putting the timer.start() calls in the button submit action listener that has fixed it for you. Before, you were starting the timer at the end of your constructor. Hence, 5 seconds after starting the application the timer fired and they showed up. There wasn't really a need to split them up into two separate timers.

Link to post
Share on other sites

It was putting the timer.start() calls in the button submit action listener that has fixed it for you. Before, you were starting the timer at the end of your constructor. Hence, 5 seconds after starting the application the timer fired and they showed up. There wasn't really a need to split them up into two separate timers.

 

Omg you're right!

 

Ugh programming at 1AM isn't good for my mind.

 

>.<

~~~SnapDragon~~~

| CPU: AMD Ryzen 9 9950X3D | CPU Cooler: Gigabyte Aorus Waterforce X II 360mm |RAM: 2x32GB G.Skill Trident Z5 Neo RGB 6000MHz | Mobo: Gigabyte X870E Aorus Xtreme X3D AI Top  | Storage: Samsung 9100 Pro 4TB + Samsung 990 Pro 4TB + Samsung 870 Evo 4TB + Samsung 870 Evo 2TB | Graphics Card: Gigabyte RTX 5090 Aorus Master 32G | Case: Lian Li Lancool 216 | PSU: Seasonic Vertex GX-1200 |

 

Link to post
Share on other sites

Me neither. I know people who code almost exclusively in the night, but I just can't do it.

 

Yeah I wouldn't do it either but my whole team's behind schedule. I still have to design the images for my buttons as well as change some fonts.

 

Busy weekend ahead for me. >.<

~~~SnapDragon~~~

| CPU: AMD Ryzen 9 9950X3D | CPU Cooler: Gigabyte Aorus Waterforce X II 360mm |RAM: 2x32GB G.Skill Trident Z5 Neo RGB 6000MHz | Mobo: Gigabyte X870E Aorus Xtreme X3D AI Top  | Storage: Samsung 9100 Pro 4TB + Samsung 990 Pro 4TB + Samsung 870 Evo 4TB + Samsung 870 Evo 2TB | Graphics Card: Gigabyte RTX 5090 Aorus Master 32G | Case: Lian Li Lancool 216 | PSU: Seasonic Vertex GX-1200 |

 

Link to post
Share on other sites

Yeah I wouldn't do it either but my whole team's behind schedule. I still have to design the images for my buttons as well as change some fonts.

 

Busy weekend ahead for me. >.<

Well, we're here to help if you need it. :)

Good luck!

Link to post
Share on other sites

Well, we're here to help if you need it. :)

Good luck!

 

Asking you guys here is wayyy better than posting on stackoverflow where they fault you for everything. I got an infraction for posting a duplicate question once lol

~~~SnapDragon~~~

| CPU: AMD Ryzen 9 9950X3D | CPU Cooler: Gigabyte Aorus Waterforce X II 360mm |RAM: 2x32GB G.Skill Trident Z5 Neo RGB 6000MHz | Mobo: Gigabyte X870E Aorus Xtreme X3D AI Top  | Storage: Samsung 9100 Pro 4TB + Samsung 990 Pro 4TB + Samsung 870 Evo 4TB + Samsung 870 Evo 2TB | Graphics Card: Gigabyte RTX 5090 Aorus Master 32G | Case: Lian Li Lancool 216 | PSU: Seasonic Vertex GX-1200 |

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×