Handling IllegalComponentStateException in java.


It is the sub class of IllegalStateException, This indicates that AWT component is not in an appropriate state i.e. if you are working with components but, not using them properly leads to this exception. There are several scenarios where this exception occurs

Example

In the following example we are trying to build a sample login form here after setting the visibility of the window to true, we are trying to set the location by platform true which is inappropriate.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LoginDemo extends JFrame implements ActionListener {
   JPanel panel;
   JLabel user_label, password_label, message;
   JTextField userName_text;
   JPasswordField password_text;
   JButton submit, cancel;
   LoginDemo() {
      // Username Label
      user_label = new JLabel();
      user_label.setText("User Name :");
      userName_text = new JTextField();
      // Password Label
      password_label = new JLabel();
      password_label.setText("Password :");
      password_text = new JPasswordField();
      // Submit
      submit = new JButton("SUBMIT");
      panel = new JPanel(new GridLayout(3, 1));
      panel.add(user_label);
      panel.add(userName_text);
      panel.add(password_label);
      panel.add(password_text);
      message = new JLabel();
      panel.add(message);
      panel.add(submit);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      // Adding the listeners to components..
      submit.addActionListener(this);
      add(panel, BorderLayout.CENTER);
      setTitle("Please Login Here !");
      setLocationRelativeTo(null);
      setSize(375,250);
      setVisible(true);
      setLocationByPlatform(true);
   }
   public static void main(String[] args) {
      new LoginDemo();
   }
   @Override
   public void actionPerformed(ActionEvent ae) {
      String userName = userName_text.getText();
      char[] password = password_text.getPassword();
      if (userName.trim().equals("admin") && new String(password).trim().equals("admin")) {
         message.setText(" Hello " + userName + "");
      } else {
         message.setText(" Invalid user.. ");
      }
   }
}

Output

Exception in thread "main" java.awt.IllegalComponentStateException: The window is showing on screen.
   at java.awt.Window.setLocationByPlatform(Unknown Source)
   at myPackage.LoginDemo.<init>(LoginDemo.java:51)
   at myPackage.LoginDemo.main(LoginDemo.java:55)

Solution

In this scenario you can resolve the exception either by passing false to the setLocationByPlatform() or, by removing it completely.

Updated on: 06-Aug-2019

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements