4

I have a problem. In the JScrollPane I use inheritor of the JPanel as viewPort. The inheritor can contain labels, radio buttons, check boxes and other elements (depending on the implementation). In the JScrollPane set HORIZONTAL_SCROLLBAR_NEVER. It is necessary that contents in the inheritor of the JPanel scrolling in the vertical and horizontal words wrap. When displaying long texts in the labels (special in html tags) there is no word wrap, despite HORIZONTAL_SCROLLBAR_NEVER. If don't use JScrollPane (inheritor of the JPanel has concrete size) words to be wrapped, but I need a vertical scrolling.

Tried set listeners for resize JScrollPane and set necessary size for internal JPanel. Did not work. Set listeners for resize internal JPanel yet. After setting the width is happening another change back to (obviously of great importance).

How can I solve this problem? Requires scrolling in the vertical and horizontal words wrap. Thanks in advance. Sorry, for my English).

Example (bad, after is better)

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;

public class Test extends JFrame
{

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    Test frame = new Test();


                    JScrollPane scrollPane =  new JScrollPane();
                    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                    JPanel panel = new JPanel();
                    panel.add(new JLabel("<html>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</html>"));
                    scrollPane.setViewportView(panel);
                    frame.add(scrollPane);
                    frame.setVisible(true);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Test()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
    }

}

Good example

Screen link: http://s44.radikal.ru/i104/1204/4d/72ea56d685ee.png

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;

public class Test extends JFrame
{

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args)
{
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                Test frame = new Test();
                frame.setVisible(true);

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Test()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    GridBagLayout gbl_contentPane = new GridBagLayout();
    gbl_contentPane.columnWidths = new int[] { 0, 0 };
    gbl_contentPane.rowHeights = new int[] { 0, 0 };
    gbl_contentPane.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gbl_contentPane.rowWeights = new double[] { 1.0, Double.MIN_VALUE };
    contentPane.setLayout(gbl_contentPane);

    JScrollPane scrollPane = new JScrollPane();
    GridBagConstraints gbc_scrollPane = new GridBagConstraints();
    gbc_scrollPane.fill = GridBagConstraints.BOTH;
    gbc_scrollPane.gridx = 0;
    gbc_scrollPane.gridy = 0;
    contentPane.add(scrollPane, gbc_scrollPane);

    JPanel panel = new JPanel();
    scrollPane.setViewportView(panel);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);        
    GridBagLayout gbl_panel = new GridBagLayout();
    gbl_panel.columnWidths = new int[]{0, 0};
    gbl_panel.rowHeights = new int[]{0, 0};
    gbl_panel.columnWeights = new double[]{0.0, Double.MIN_VALUE};
    gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
    panel.setLayout(gbl_panel);

    JLabel lblNewLabel = new JLabel("<html>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</html>");
    GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
    gbc_lblNewLabel.gridx = 0;
    gbc_lblNewLabel.gridy = 0;
    panel.add(lblNewLabel, gbc_lblNewLabel);
}

 }

Example word wrap in JLabel with `tag html`:

screen link: http://s019.radikal.ru/i628/1204/75/d14b8fa81f15.png

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class Test extends JFrame
{

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args)
{
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                Test frame = new Test();
                frame.setVisible(true);

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Test()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    GridBagLayout gbl_contentPane = new GridBagLayout();
    gbl_contentPane.columnWidths = new int[] { 0, 0 };
    gbl_contentPane.rowHeights = new int[] { 0, 0 };
    gbl_contentPane.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
    gbl_contentPane.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
    contentPane.setLayout(gbl_contentPane);

    JLabel lblNewLabel = new JLabel(
            "<html>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</html>");
    GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
    gbc_lblNewLabel.weightx = 1.0;
    gbc_lblNewLabel.fill = GridBagConstraints.BOTH;
    gbc_lblNewLabel.gridx = 0;
    gbc_lblNewLabel.gridy = 0;
    contentPane.add(lblNewLabel, gbc_lblNewLabel);
}

  }
gshadrin
  • 1
  • 1
  • 3
  • 1
    Please include an [sscce](http://www.sscce.org) the demonstrates the problem. – user1329572 Apr 18 '12 at 15:55
  • Briefly. I need to scroll content in the JScrollPane of verticals and horizontal words wrap. I use HORIZONTAL_SCROLLBAR_NEVER, but words not wrap. I use html tag in the label. – gshadrin Apr 18 '12 at 16:09
  • Are you saying you have `JLabel`s with word wrapping when you do not use a `JScrollPane` ... I would like to see that as I am unaware of any word wrapping functionality in a `JLabel`. I only know the ... (3 dots at the end) behavior where a part of the word is replaced by ... – Robin Apr 18 '12 at 16:15
  • If a long text in the `JLabel` enclosed in a tag `html`, than words to be wrap. `new JLabel("Long text");` – gshadrin Apr 18 '12 at 16:22
  • 1
    @gshadrin, As I said before, please include an [sscce](http://www.sscce.org) – user1329572 Apr 18 '12 at 16:27
  • @user1329572, I include example. – gshadrin Apr 18 '12 at 16:40
  • 1
    @gshadrin Pleases ***read*** the SSCCE document and post an SSCCE rather than code snippets! – Andrew Thompson Apr 18 '12 at 16:43
  • 1
    @AndrewThompson, I posted example. – gshadrin Apr 18 '12 at 16:59

3 Answers3

10

Text area with scroll-bar

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class Test extends JFrame {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Test frame = new Test();

                    JTextArea message = new JTextArea("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
                        ,6,40);
                    // make it look & act like a label
                    message.setWrapStyleWord(true);
                    message.setLineWrap(true);
                    message.setEditable(false);
                    message.setFocusable(false);
                    message.setOpaque(false);

                    JScrollPane scrollPane =  new JScrollPane(message,
                        ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
                        );
                    frame.add(scrollPane);
                    frame.pack();
                    frame.setVisible(true);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationByPlatform(true);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Thank you. I understand you example. You limit numbers of columns. In the question I add example, in which JLabel also work word wrap if use `html tag`, but without scrolling. Can I use JLAbel? And if I use JRadioButton with long text and need word wrap? – gshadrin Apr 18 '12 at 17:42
  • Although `JLabel` can be wrapped using HTML, using HTML produces some odd results, like what you observed. As to the `JRadioButton` - a 'is this the choice?' should *not have* a long text. – Andrew Thompson Apr 18 '12 at 17:45
  • I think what odd results caused by size internal JPanel (my 2 example "Good example") when it is a viewport for the JScrollPane. This size obviously a big although the use HORIZONTAL_SCROLLBAR_NEVER. Obviously a big size reason when use scrolling. I want to limit the size of the internal JPanel of actual value (as 3 example). This is my main question. Content of the internal JPanel can be any (not only long text). – gshadrin Apr 18 '12 at 19:28
  • If use the JTextArea, then size limits numbers of a columns – gshadrin Apr 18 '12 at 19:33
2

I think you need to implement the interface Scrollable. Actually JTextArea also implements Scrollable.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Rectangle;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.Scrollable;
import javax.swing.border.EmptyBorder;

public class TestScrollLabel extends JFrame
{

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args)
{
    EventQueue.invokeLater(new Runnable()
    {
        public void run()
        {
            try
            {
                TestScrollLabel frame = new TestScrollLabel();
                JScrollPane scrollPane =  new JScrollPane();
                scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                JPanel panel = new MyPanel();
                //BorderLayout is a good choice here
                panel.setLayout(new BorderLayout());
                panel.add(new JLabel("<html>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</html>"));
                scrollPane.setViewportView(panel);
                frame.add(scrollPane);
                frame.setVisible(true);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    });
}

static class MyPanel extends JPanel implements Scrollable{

    @Override
    public Dimension getPreferredScrollableViewportSize() {

        return this.getPreferredSize();
    }

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect,
            int orientation, int direction) {
        return 50;
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect,
            int orientation, int direction) {
        return 80;
    }

    /*
     * (non-Javadoc)
     * @see javax.swing.Scrollable#getScrollableTracksViewportWidth()
     */
    @Override
    public boolean getScrollableTracksViewportWidth() {
        return true;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }

}

/**
 * Create the frame.
 */
public TestScrollLabel()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);
}

}
hulala666
  • 1
  • 1
0

JLabel has no word wrap functionality. You can simulate this effect by creating a JTextArea, making it read-only using setEditable(false) and then calling setWrapStyleWord(true) to enable word-wrapping.

I think you can also play around with setBorder() to make it look flatter and more like a plain label, but this may give different effects on different platforms depending on look and feel.

Michał Kosmulski
  • 9,855
  • 1
  • 32
  • 51