4
votes

I'm changing a program from AWT to Swing, as proposed on the second chapter of Java Swing's book, and the panel just disappears when I do the change from Panel to JPanel. The same doesn't happen when I change from Button to JButton.

It seems to be a bug, since it appears to be trivially simple to do so - just adding an extra J to the name - but I'm not sure where the problem is - with my VM (Sun JDK), with my WM (xmonad) or with the way I'm programming (Clojure's Java Support). Any idea?

As previously stated, I'm writing it in Clojure (a lisp-like language for the JDK). Here is my code:

(defn main []
  (let [toolbar-frame (Frame. "Toolbar Example (Swing)")
        cut-button (JButton. "Cut")
        copy-button (JButton. "Copy")
        paste-button (JButton. "Paste")
        java-button (JButton. "Java")
        windows-button (JButton. "Windows")
        mac-button (JButton. "Mac")
        motif-button (JButton. "Motif")
        lnf-panel (JPanel.)
        toolbar-panel (Panel.)
        print-listener (proxy [ActionListener] []
          (actionPerformed [evt]
            (.getActionCommand evt)))
        ]
      (.addWindowListener toolbar-frame
        (proxy [WindowAdapter] []
          (windowClosing [e]
            (System/exit 0))))
    ;(doto windows-button (.addActionListener lnf-listener))
    ;(doto motif-button (.addActionListener lnf-listener))
    ;(doto mac-button (.addActionListener lnf-listener))
    ;(doto java-button (.addActionListener lnf-listener))
    (doto cut-button (.addActionListener print-listener))
    (doto copy-button (.addActionListener print-listener))
    (doto paste-button (.addActionListener print-listener))
    (doto lnf-panel
      (.add windows-button)
      (.add java-button)
      (.add mac-button)
      (.add motif-button)
      (.setLayout (FlowLayout. FlowLayout/LEFT)))
    (doto toolbar-panel
      (.add cut-button)
      (.add copy-button)
      (.add paste-button)
      (.setLayout (FlowLayout. FlowLayout/LEFT)))
    (doto toolbar-frame
      (.add toolbar-panel BorderLayout/NORTH)
      (.add lnf-panel BorderLayout/SOUTH)
      (.setSize 450 250)
      (.setVisible true))))

Thanks

1

1 Answers

4
votes

I notice you are adding the child components before setting the layout. Try setting the layout first. The problem may be that the default constraint information is lost when you change the layout. If the JPanel is invisible it may be because it has not been auto-sized to fit its child elements.

Also try (.pack) instead of (.setSize 450 250) on the frame.