Home > Software design >  java.awt.IllegalComponentStateException: component must be showing on the screen to determine its lo
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its lo

Time:10-14

I have the following code to move a undecorated swing frame but whenever i press my mouse button the following exception appears:

java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location

Here is my Code

   class Gui extends Frame

{

    JFrame frame;
    JLabel label;
    Gui()
    {
        frame = new JFrame();
        label = new JLabel("...");
        label.setForeground(Color.white);
        //label.setBounds(300,300, 100,30);  
        frame.add(label);
        frame.setSize(30, 30);
        frame.setUndecorated(true);
        frame.setLocation(1550, 1045);
        frame.setBackground(new Color(0,0,0,0));       
        frame.setAlwaysOnTop(true);
        frame.setVisible(true);
        listenMouse();



       
        



    }

    public void listenMouse()
    {
        MouseAdapter ma = new MouseAdapter() {
            int lastX, lastY;
            @Override
            public void mousePressed(MouseEvent e) {
                lastX = e.getXOnScreen();
                lastY = e.getYOnScreen();
            }
            @Override
            public void mouseDragged(MouseEvent e) {
                int x = e.getXOnScreen();
                int y = e.getYOnScreen();
                // Move frame by the mouse delta
                frame.setLocation(getLocationOnScreen().x   x - lastX,
                        frame.getLocationOnScreen().y   y - lastY);
                lastX = x;
                lastY = y;
            }
        };
        frame.addMouseListener(ma);
        frame.addMouseMotionListener(ma);


    }

Could it be that the window is too small or the position where it is is problematic? Is on taskbar already off screen?

CodePudding user response:

Remove extend Frame - you have two window based classes, Gui, which extends from Frame, not a good idea on multiple accounts*, and frame which is an instance of JFrame.

frame.setLocation(getLocationOnScreen().x   x - lastX,
        frame.getLocationOnScreen().y   y - lastY);

is then trying to set the location of the JFrame based on the location of the Frame, which hasn't been realised on the screen.

So, the short answer is, you're confusing yourself.

Frame is an AWT based component and in this context, would not be a good starting point. Extending from top level containers, like Frame is generally discouraged, as you are not adding any new functionality to the class, it locks you into a single use case (reduces re-use) and top level containers tend to be much more complex structures and can really mess with you in ways you might not be expecting

  • Related