Reliable object not resizing java JScrollPane

Viewed 27

I'm trying to make a file view(JScrollPane) resizable for an ide, but when I try to resize it, It wont update unless I resize the window. I try looking it up but I could not find anything usefull. If you help me on this thank you so much.

Take a look fore yourself

public MainWindow(String title) {
        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new BorderLayout());
        this.setResizable(true);
        this.setSize(windowSize);
        this.setLocationRelativeTo(null);

        // ....

        JPanel fileView = new JPanel();
        fileView.setBackground(Color.WHITE.darker());

        JScrollPane fileScrollView = new JScrollPane(fileView);
        fileScrollView.setPreferredSize(new Dimension(100, 0));

        fileScrollView.addMouseMotionListener(new MouseMotionListener() {
            private int offset = 0;
            private boolean start = false;

            @Override
            public void mouseDragged(MouseEvent e) {
                int mouseX = e.getX() ;
                int left = fileScrollView.getX() + fileScrollView.getWidth();
                boolean resize = setCursor(left, mouseX);

                if (start) {
                    offset = left - mouseX;
                }

                if (resize) {
                    LOGGER.logInfo("OFFSET: " + offset);
                    fileScrollView.setPreferredSize(new Dimension(mouseX + offset, fileScrollView.getHeight()));

                    repaint();
                    doLayout();
                }
                start = false;
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                start = true;
                setCursor(fileScrollView.getX() + fileScrollView.getWidth(), e.getX());
            }

            public boolean setCursor(int right, int mx) {
                if (mx > right - 20 && mx < right){
                    fileScrollView.setCursor(new Cursor(Cursor.E_RESIZE_CURSOR));
                    return true;
                } else {
                    fileScrollView.setCursor(Cursor.getDefaultCursor());
                    return false;
                }
            }
        });



        this.add(fileScrollView, BorderLayout.WEST);
    }
1 Answers

It wont update unless I resize the window.

repaint();
doLayout();

First of all, the order of the statements is wrong. You should not attempt to repaint something if you haven't redone the layout.

However, you should not invoke doLayout() directly. Instead, you can use:

fileScrollView.revalidate();
fileScrollView.repaint(); // sometimes needed

The revalidate() will invoke the layout manager. Sometime repaint() is also needed to make sure the panel is repainted.

Related