phatmanace
phatmanace

Reputation: 5021

Custom Swing component: questions on approach

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

many thanks in advance.

-Ace

Upvotes: 3

Views: 850

Answers (2)

Kirill
Kirill

Reputation: 425

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).

Upvotes: 10

Eugene Ryzhikov
Eugene Ryzhikov

Reputation: 17359

  • 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.

Upvotes: 4

Related Questions