Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an editable text box in JPanel

Tags:

java

text

swing

I am looking to add a text-box onto my JPanel. This text box will be similar to something like in Microsoft PowerPoint: one that you can resize, move around, etc. I have looked into JTextField but I don't think this is what I need. I do not need a popup box like this:

enter image description here

I have a program that allows the user to add, resize and move shapes. I now want to be able to place a text box into these shapes. Here is an example of what I am looking for:

enter image description here

Is there anyway I can do this? Thanks.

like image 592
nick Avatar asked Jan 21 '26 04:01

nick


1 Answers

The ComponentResizer class takes care of the resizing. Here is a working example for a resizeable JTextArea:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            buildGUI();
        }
    });
}

private static void buildGUI() {
    JFrame f = new JFrame("Test");
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    ComponentResizer cr = new ComponentResizer();
    JPanel mainPanel = new JPanel(null);
    f.add(mainPanel);

    JTextArea textArea = new JTextArea("Some text\nSome other text");
    cr.registerComponent(textArea);

    mainPanel.add(textArea);
    textArea.setBounds(50, 50, 150, 150);

    f.setSize(400, 400);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

If you also want to move the JTextArea, you can use in addition ComponentMover and add the following code:

    ComponentMover cm = new ComponentMover();
    cm.registerComponent(textArea);
    cm.setDragInsets( cr.getDragInsets() );
like image 155
lbalazscs Avatar answered Jan 22 '26 16:01

lbalazscs