I have following code to add panels dynamically to container with GridBagLayout. It should grow and display vertical scrollbar, not horizontal.
But when I add too long text in JLabel in parent JPanel, it displays horizontal scrollbar, I want JLabel to break text as container shrinks, and also grows as the container grows. I've tried setting maximum width but the GridBagLayout not using it.
I've also tried using something like but it makes the label's 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);
}
}
JTextArea
, but you'll need to make some adjustments to the border and font and make it read only and make it non-focusable, for (a simple) example – Hydrangea