0

I have the following code (in Scala, but there's nothing specific to Scala here):

new JFrame {
  this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
  this.setLocation(100, 100)
  this.setSize(1000, 1000)
  val mainPanel = new JPanel()
  myFoos.foreach {
    myFoo =>
      val jpanel = fooPanel(myFoo)
      mainPanel.add(jpanel)
  }
  val scrollPane = new JScrollPane(mainPanel)
  this.add(scrollPane)
  this.setVisible(true)
}

The result of running this is a blank JFrame, but when I resize the window, the innermost JPanels render as expected. Also, if I initialize scrollPane with one of the fooPanels directly, skipping mainPanel, it renders without having to resize the outer JFrame. What am I missing?

jonderry
  • 23,013
  • 32
  • 104
  • 171
  • Change the layout manager of `mainPanel` to something other than `Flowlayout` and see if it makes a difference – MadProgrammer Mar 03 '16 at 02:25
  • This works, but why? I actually liked `FlowLayout`, but `BoxLayout` seems also good. – jonderry Mar 03 '16 at 02:34
  • Well, I don't have the code for `fooPanel` is it's hard to know exactly what's going – MadProgrammer Mar 03 '16 at 02:36
  • Its nothing interesting, just draws and fills some rectangles and ovals. – jonderry Mar 03 '16 at 02:38
  • Does it override the `getPreferred/Minimum/MaximumSize` methods (one or any)? – MadProgrammer Mar 03 '16 at 02:40
  • The preferred size of each `fooPanel` is set at the end of its overridden `paintComponent` method. – jonderry Mar 03 '16 at 02:45
  • 1
    [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) and never ever do from within the paint method. A component is laid out before it's painted (and updating the component property from the paint method could have unwanted side effects, like you CPU ramping up to 100% and your UI become unresponsive) – MadProgrammer Mar 03 '16 at 02:47
  • Shoot, I guess that's the problem, but I don't know the size I want it to be until I render it (there is also some text, for which I use the graphics to compute the size, so I know how big it needs to be). – jonderry Mar 03 '16 at 02:59
  • `JPanel` can return [`FontMetrics`](https://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#getFontMetrics-java.awt.Font-) value which you can use to do "pre-calculations" – MadProgrammer Mar 03 '16 at 03:05
  • Nice, I didn't know that was invariant between all `Graphics2D` objects that might be injected into the `paintComponent` method. I was getting it from the `Graphics2D`, not the `JPanel`. – jonderry Mar 03 '16 at 03:13
  • You get `FontMetrics` from both, but it depends on your context – MadProgrammer Mar 03 '16 at 04:06

0 Answers0