Bill
Bill

Reputation: 519

A better swing gui design?

I am working on a project for an online class I made the mistake of taking this summer and I need to build a gui to show how the huffman code algorithm works. The algorithm part is easy, its not very complicated. However im unsure what the best way to draw the tree(forrest) at each step. It would have to start out as just n nodes (with chars in them) on the screen and then you would press a "next" button and it would pick the two lowest nodes weighted (based on character frequency) characters and make them children of a new node (with just a weight - no char) and then update the screen/panel.

I have made swing gui before, my skills are nothing special but I know my way around. However im stuck on this implementation. I have a couple hundred lines of code written right now, but it doesnt work and I think its bad anyway, so I want to "start over" and plan it out better. So Id just like some advice on the data structure to keep track of the nodes and how to draw them on the screen.

I was using an ArrayList of JPanels as nodes and trying to draw them to a null layout. Im sure this is awful and id like to know a better way. Possibly GridBagLayout?

NOTE: don't say JTree.

Upvotes: 3

Views: 625

Answers (4)

Kristof
Kristof

Reputation: 11

We all had that what you have once ;-)

First of all, never use Null layout because then you make sizes static and your application will not work on other resolutions like desired.

Best layoutmanager to use: GridBagLayout !

Why ? very flexible and you can get all components exactly on the place you want, discarding the resolution. Its harder to set up but better result eventually.

Upvotes: 0

Jay Askren
Jay Askren

Reputation: 10444

A good option is to just use a library for drawing trees/graphs. I've had good success with Visual Library in the past.

Another possibility is Prefuse

Upvotes: 2

rtheunissen
rtheunissen

Reputation: 7435

Use an image of a tree (only one instance) and an array or other data structure to contain the "data" that the algorithm uses. Think about how you can use the data to determine where the image should be painted. Use the repaint() after the algorithm runs.

[Next] --> Algorithm runs --> Update using repaint();

So you have a single frame, a single panel and a single BufferedImage object. The trick will come in when you have to get slightly mathematical to know at what co-ordinates a node should be painted.

The layout of your components are insignificant, as you're not adding any components to the container, just painting image data onto it.

Upvotes: 1

Paul Sasik
Paul Sasik

Reputation: 81479

Instead of wrestling with the different Swing layouts you could just do custom 2D drawing. See for a simple enter link description hereexample here on how to get started.

Upvotes: 1

Related Questions