Make JLabel text breaks in gridbaglayout

I have the following code to dynamically add panels to a container with a GridBagLayout. It should grow and display a vertical scrollbar, not horizontal.

But when I add text too long in JLabel in the parent JPanel, it displays a horizontal scroll bar, I want JLabel to interrupt the text when the container is compressed, and also grows as the container grows. I tried to set the maximum width, but GridBagLayout did not use it.

I also tried using something like this, but it makes the shortcut not growing when I resize the parent.

import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.UIManager; import javax.swing.border.MatteBorder; /** * * @author MethoD */ public class DynamicPanelList extends JPanel { private JPanel mainList; public DynamicPanelList() { setLayout(new BorderLayout()); mainList = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.weighty = 1; mainList.add(new JPanel(), gbc); add(new JScrollPane(mainList)); JButton add = new JButton("Add"); add.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JLabel lbl = new JLabel("<html>Hello world items lorem ipsum dolor sit amei blast it"); //lbl.setMaximumSize(new Dimension(100, 100)); panel.add(lbl, BorderLayout.CENTER); panel.setBorder(new MatteBorder(0, 0, 1, 0, Color.GRAY)); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.fill = GridBagConstraints.HORIZONTAL; mainList.add(panel, gbc, 0); validate(); repaint(); } }); add(add, BorderLayout.SOUTH); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); DynamicPanelList tp = new DynamicPanelList(); frame.add(tp); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } 

enter image description here

0
source share

All Articles