views:

84

answers:

2

Hi Folks,

I'm trying to build a new java swing component, I realise that I might be able to find one that does what I need on the web, but this is partly an exercise for me to learn ow to do this.

I want to build a swing component that represents a Gantt chart. it would be good (though not essential for people to be able to interact with it (e.g slide the the tasks around to adjust timings)

it feels like the best approach for this is to subclass JComponent, and override PaintComponent() to 'draw a picture' of what the chart should look like, as opposed to doing something like trying to jam everything into a custom JTable.

I've read a couple of books on the subject, and also looked at a few examples (most notably things like JXGraph) - but I'm curious about a few things

  • When do I have to switch to using UI delegates, and when can I stick to just fiddling around in paintcomponent() to render what I want?

  • if I want other swing components as sub-elements of my component (e.g I wanted a text box on my gantt chart)

    • can I no longer use paintComponent()?
    • can I arbitrarily position them within my Gantt chart, or do I have to use a normal swing layout manager

many thanks in advance.

-Ace

+2  A: 
  • Using UI delegates is a good idea if you think that your component should look different for different Look And Feels. Also it is generally a good idea from design point of view to separate you presentation from your component

  • Even when overrding paintComponent you can still put any sub components on it.

  • Using null layout you arbitrarey position your components. Alternatively you can use layouts too.

Here is a very good starting point for you.

eugener
+1 Same article! :-)
trashgod
Yea...only 2 hours before Kirill posted his answer :)
eugener
+6  A: 

I think that the article i wrote a few years ago for java.net is still correct today. Doing everything in one monolithic class gets you going faster in the beginning, but becomes a mess quite fast. I highly recommend doing the separation between the model (in your main class) and the view (UI delegate). The view is responsible for:

  • interaction with the user - mouse, keyboard etc.
  • painting
  • creating "worker" subcomponents as necessary

In the medium and long run this is the approach that has been validated over and over again in the Flamingo component suite, which you can use as an extra reference point (in addition to how core Swing components are implemented).

Kirill
+1 I've relied on and cited this article frequently.
trashgod