Creating custom components in Java AWT
I am trying to create a custom component using Java AWT or Swing which will be a rectangle with a number of components inside of it, including other rectangles. Something like this:
╔══════╗
║ ┌┐ ║
║ ├┘ ║
║ ║
╚══════╝
And this needs to开发者_运维百科 be a component that I can preferably draw with one instruction. Something like myFrame.add(new MyComponent())
.
What would you say is the best way to do this? Is there a way I can do this using Rectangle
, or should I go with JPanel
or something from Swing?
"a number of components" -> JPanel with a layout manager to place each component
"draw" -> override paint on component
Check the Java Tutorial Swing section.
I would recomend extending a JPanel
and overriding it's paintComponent()
method. See another answer of mine for some help on that.
Basically, when a rectangle is 'drawn' on your panel, you will want to save it as a member of the Jpanel
. Then, in the paintComponent
method, you will just draw all of the rectangles you have saved in your JPanel
.
This is how I would implement a 'draw' method:
List<Rectangle> recs;
List<Stroke> strokes;
List<Color> colors;
public void drawRectangle(Rectangle newR, Stroke stroke, Color c){
recs.add(newR);
strokes.add(stroke);
colors.add(c);
}
And, the paint component will look similar to:
protected void paintComponent(Graphics g){
super.paintComponent(g);
for (int i = 0; i < recs.size(); i ++) {
g.setColor(colors.get(i));
g.setStroke(strokes.get(i));
g.drawRectangle(recs);
}
}
精彩评论