开发者

Can a single java.awt.Rectangle be painted with two different boundary colors?

开发者 https://www.devze.com 2022-12-21 06:39 出处:网络
I have a simple Java program that allows a user to draw rectangles on a JPanel, then move them around, resize them, and delete them.

I have a simple Java program that allows a user to draw rectangles on a JPanel, then move them around, resize them, and delete them.

The drawing panel implements MouseListener and MouseMotionListener. When an event is triggered, it开发者_开发百科 checks which menu option is selected (new rectangle, move, resize, or delete), and reacts accordingly.

When the 'resize' option is selected, the listener's methods do the following:

  • MouseMoved calls boolean detectBoundary(). When that returns true, the rectangle to which the boundary belongs is set as the active rectangle.

  • MouseDragged calls void moveBoundary, which moves the detected boundary in the direction of the dragging gesture.

Now what I am looking for is a way to make the boundary that is going to be moved stand out. I can re-paint the whole rectangle in thicker lines or a different color, which is what I do now when I set a given rectangle as the active one, but that's not what I want. I'd like to re-color just the one boundary.

A setBorder method that can handle BorderFactory's createMatteBorder method would seem to be ideal for these purposes, but I haven't been able to find a way to make that work.

Does anyone here have an idea how I could accomplish this?

All suggestions will be greatly appreciated.


Could you call the setColor(Color color) method on java.awt.Graphics?

It sounds like you might be asking for something more complicated, but I'm not sure exactly what. If you want two different boundary colors on the same rectangle, I think you would have to use two rectangle objects to do this. The top rectangle would have a transparent fill. The two rectangles would need to move together, and the second rectangle would need to be removed from the view when the move is complete.

I'm not sure if it is possible to change the color of just one edge of a simple rectangle, but you could build a more complex shape out of multiple shapes, or alternatively you could draw your rectangle into a BufferedImage and draw a line over the top in a different color.


The BorderFactory class is usually used for creating borders for Swing components, so I am not sure if this works also in your case. Have you tried to create a new panel with border

JPanel panel = new JPanel(); 
Border mb = (BorderFactory.createMatteBorder (0, 5, 0, 0, Color.red); 
panel.add(mb);

and then add your Rectangle to the panel and add it to the existing panel where you are actually drawing?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号