1

I've got this little notifications JPanel: The idea being you can scroll through the notifications, each notification has its own white box.

The green border is the JPanel wrapped in a JScrollPane, the orange border boxes are JTextAreas wrapped in JScrollPanes. I'm trying to loop through the code below and create each box the right size, but the boxes are expanding like in the image even with a horizontal glue (I'm using boxLayout on the JPanel (green box)).

The code:

for (int i = 1; i <= notifications.size(); i++)
    {
        ArrayList s = notifications.get(i); // Gets the text data
        Dashboard.notificationsArea.add(new JScrollPane(new JTextArea((s.get(1).toString() + "\n" + s.get(0).toString())))); // Creates the white boxes
        Dashboard.notificationsArea.add(Box.createVerticalStrut(5));
        s.clear();
    }
    Dashboard.notificationsArea.add(Box.createVerticalGlue()); // Adds glue to fill up space (not working?)
    for (int ii = 0; ii < Dashboard.notificationsArea.getComponents().length; ii++)
    {
        if (Dashboard.notificationsArea.getComponent(ii) instanceof JScrollPane)
        { // Style white box
            ((JScrollPane)Dashboard.notificationsArea.getComponent(ii)).setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Settings.SITE_ORANGE));
            ((JTextArea) ((JScrollPane)Dashboard.notificationsArea.getComponent(ii)).getViewport().getView()).setLineWrap(true);
            ((JTextArea) ((JScrollPane)Dashboard.notificationsArea.getComponent(ii)).getViewport().getView()).setEditable(false);
            ((JTextArea) ((JScrollPane)Dashboard.notificationsArea.getComponent(ii)).getViewport().getView()).setWrapStyleWord(true);
        }
    }
    Dashboard.notificationsArea.revalidate();
}

How can I make the white boxes snap to the correct size?

Crizly
  • 971
  • 1
  • 12
  • 33

1 Answers1

1

As shown in this complete example, you can override getPreferredSize() to enforce a specific size for the nested scroll pane(s). You may be able to further refine the preferred size as shown by @camickr in TextPanePerfectSize.

image

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    Nice link for calculating the size of the component while rendering. Added that to my favourites :-) – nIcE cOw Jun 26 '14 at 17:51