English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Come gestire l'eccezione IllegalComponentStateException in Java?

It is a subclass of IllegalStateException, indicating that the AWT component is not in the appropriate state, that is, if you are using the component but not using it correctly, it will cause this exception. Several situations may occur when this exception occurs

Example

In the following example, we try to build an example login form here after setting the visibility of the window to true, and we try to set the position to true according to the platform, which is not appropriate.

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);
      //将侦听器添加到组件中。
      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 + ");
      }
         message.setText("Invalid user.");
      }
   }
}

Risultato di 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)

Soluzione

In questo caso, è possibile risolvere l'eccezione passando false a setLocationByPlatform() o rimuovendolo completamente.

Ti potrebbe interessare