Clojure + Swing absolute positioning problems
I'm writing a small app where I want absolute positioning - I can get what I want with seemingly an ugly workaround, however I would like to know how I can make this code cleaner maintaining the same functionality.
The problem is if I omit either (.setBounds ..) s-exprs then the JPanel fills the entire JFrame. Thanks in advance, here is working sample code:
...
(:import [javax.swing JFrame JPanel]
[javax.swing.border LineBorder]
[java.awt Color])
(defn frame []
(let [top-panel (doto (JPanel.)
(.setOpaque true)
(.setVisible true)
(.setBounds 25 25 250 75)
(.setBorder (LineBorder. (Color. 255 0 0 255))))
frame (doto (JFrame.)
(.setLayout nil)
(.setResizable false)
(.setSize 300 625)
(.开发者_JS百科setVisible true)
(.setContentPane top-panel))]
(.setBounds top-panel 25 25 250 75)))
This code gives me the functionality I was looking for, replacing .contentPane with .add
(defn frame []
(let [top-panel (doto (JPanel.)
(.setBounds 25 25 250 75)
(.setVisible true)
(.setBorder (LineBorder. (Color. 255 0 0 255))))]
(doto (JFrame.)
(.setLayout nil)
(.setSize 300 625)
(.setVisible true)
(.add top-panel)))
Hmmm... I could not get your code to work. When I made mods to get it to run I got the panel tightly wrapped by the frame.
I'm assuming you want the top-panel in the middle of the larger frame with empty space on all sides. The usual way to do this would be to create a main panel with the size of the frame you want. Then, using a layout manager like BorderLayout, add additional JPanels to the main panel. The top-panel would be given the dimensions you want and surrounding panels would provide the "padding". If the surrounding panels are created with empty borders, it should look like the top-panel is surrounded by empty area.
EDIT:
Here's something that may be a bit closer to your intention. The BorderLayout probably does not give the panel sizing priority you want. Maybe GridBagLayout?
(ns com.so.abspos
(:import (javax.swing JFrame JPanel)
(java.awt BorderLayout))
(:gen-class true))
(defn frame []
(let [
center-panel (doto (JPanel.)
(.setOpaque true)
(.setVisible true)
(.setSize 225 50)
;(.setBounds 25 25 250 75)
(.setBorder (javax.swing.border.LineBorder. (java.awt.Color. 255 0 0 255))))
top-panel (doto (JPanel.)
(.setSize 625 25))
left-panel (doto (JPanel.)
(.setSize 25 75))
bottom-panel (doto (JPanel.)
(.setSize 625 300))
right-panel (doto (JPanel.)
(.setSize 250 75))
main-panel (doto (JPanel.)
(.setLayout (new BorderLayout))
(.add left-panel BorderLayout/WEST)
(.add top-panel BorderLayout/NORTH)
(.add center-panel BorderLayout/CENTER)
(.add right-panel BorderLayout/EAST)
(.add bottom-panel BorderLayout/SOUTH))
aframe (doto (JFrame.)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setResizable false)
(.setSize 300 625)
(.setVisible true)
(.setContentPane main-panel))]))
(defn -main
"Just create the frame and show it."
[]
(frame))
精彩评论