4

I am learning some GUI stuff on Java and I think Im missing something here. I have some components vertically listed using BoxLayout, such as some JButtons one above other. Now I want to separate them drawing a line between them. Do I have to use the Graphics library or is there some Swing way to separate the components with a line?

Going straight to the question: How to draw a line to separate components (such as JButtons) and which is the recommended way of doing it?

Thanks!

johnsmith
  • 3,009
  • 2
  • 15
  • 8
  • *"a line to separate components"* DYM a [LineBorder](http://download.oracle.com/javase/7/docs/api/javax/swing/border/LineBorder.html), or do you mean a line that joins between one component and the next, like a flowchart? – Andrew Thompson Oct 13 '11 at 01:11
  • Its really the JSeparator as stated below, but is there a way to make LineBorder has full width but 1 or 2px height just as line? – johnsmith Oct 13 '11 at 01:13

2 Answers2

10

JSeparator, shown here, is commonly used in this context. It works well with most layouts. Also, consider How to Use Borders.

Addendum: The JSeparator UI delegate for a given Look & Feel, often modeled on BasicSeparatorUI, is particularly simple. It's paint() implementation draws a one pixel line in the foreground color and an adjacent one pixel line in the background color. The lines are as wide (or high) as the component's bounds, depending on orientation. The layout manager determines the spacing, so you'll want to review A Visual Guide to Layout Managers.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Its exactly what Im looking for. Thanks! However, there is a BIG space between the separator and the other components. I suppose the layout is giving the same height to all components including the separator. – johnsmith Oct 13 '11 at 01:12
  • 2
    +1, for the JSeparator and for the Borders. We don't know what the layout is doing because we don't know what layout you are using. Post your [SSCCE](http://www.sscce.org) that demonstrates the problem. Then maybe we can offer more help. – camickr Oct 13 '11 at 01:23
  • just for the record: problem with borders is that - by definition - they are around containers, implying more than one container in a somehow compounded form. The disadvantage is loss of cross-container alignment of child components – kleopatra Oct 13 '11 at 06:14
3

JSeparator returns weird sizing hints, the most problematic bit for a max respecting LayoutManager like BoxLayout is its unbounded max, see also a recent discussion (which was about vertical separators, same for horizontal, though)

Community
  • 1
  • 1
kleopatra
  • 51,061
  • 28
  • 99
  • 211