Search code examples
javauser-interfacejtextfieldjcomponent

How to place two text-fields as one viewport in java?


How could I set 2 textfields as one viewport and set each textfield to expand as more text is typed in, rather than adding a scroll bar to each textfield.

I find it hard to describe it with words so I have uploaded a sketch.

enter image description here


Solution

  • You could do something like this, everytime you type something in, it gets bigger:

    field.addKeyListener(this);
    

    And in your KeyListener implementation this:

    @Override
    public void keyReleased(KeyEvent arg0) {
        field.setSize(field.getWidth() + 10, field.getHeight());
        repaint();
    }