1

I'm currently learning more about Java. I'm working on creating a GUI which is able to 'translate' amino-acid characters into their 3-letter codes.

I've got everything working as intended, but I'm still struggling to understand how I can resize the text inside my JScrollpane to not exceed the width. (Example in picture)

Do I just need to change some settings or maybe add '\n's to fit the JTextArea? Here's the code:

Thanks in advance!

private void createGUI() {
    Container window = this.getContentPane();
    window.setLayout(new FlowLayout());

    panel = new JPanel();
    inputField = new JTextField();
    startButton = new JButton("Convert to 3-letter code");
    display = new JTextPane();
    scroll = new JScrollPane(display);

    //CUSTOMIZE GUI OBJECTS
    inputField.setPreferredSize(new Dimension(200, 20));
    display.setPreferredSize(new Dimension(400, 300));
    startButton.addActionListener(this);

    //SETTING UP TEXTAREA
    display.setEditable(false);

    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    
    panel.setLayout(new BorderLayout());
    panel.add(scroll, BorderLayout.CENTER);
    //

    window.add(inputField);
    window.add(startButton);
    window.add(panel);
}

Current working gui

3 Answers3

3

Better use a JTextArea instead of a JScrollPane since the best that the JScrollPane can do is to dynamically resize (Dynamically Resize a JScrollPane?)

3

I changed JTextPane display to a JTextArea object and changed 'display.setLineWrap(true);'

This fixed the issue I was having with JTextPane.

enter image description here

1

To answer the question in the title: How do I resize the text inside my JScrollpane

Inside your scrollpane you have some JComponent. Either that JComponent is fully visible since it is smaller or equal to the JScrollpane's viewport. Or it is bigger, in which case the JScrollpane will start displaying scrollbars and the relevant part.

To resize the text you will just have to tell the JComponent inside the JScrollpane to display the text differently. Depending on the JComponent you use this method may vary. Here some examples:

Queeg
  • 7,748
  • 1
  • 16
  • 42