Placing a button on panel`s border
Is ther开发者_开发问答e any way to create border class with buttons on it? Like this: example
One important condition - buttons have to be aligned to border position, because panel can change its size. So imho LayeredPane don`t fit for this - there is no any aligment on it.
Have one idea - to imitate buttons:
- create my class for panel
- override paintComponent() and paint image of button over border
- override mouse event for it and use it like button
But. Maybe there is way to put real buttons on border?
I don't believe this is possible with standard borders, mainly because a Border
is not a Container
, and so can't have other components added to it.
But, if you're willing to go for a custom border implementation, it's possible to fake a border, for example:
private class BorderFaker extends JPanel
{
public BorderFaker()
{
add( new JButton( "Faked!" ) );
}
@Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
drawFauxBorder( g );
}
private void drawFauxBorder( Graphics g )
{
g.setColor( UIManager.getColor( "border" ) );
g.drawRect( 15, 15, getWidth() - 30, getHeight() - 30 );
}
}
This shows how you could do it, but it introduces a lot of problems, such as distinguishing between components you want inside the border versus on the border (I've only hardcoded the "Faked!" button for demonstration). And you still have to organise the layout of the components relative to the "border". It would need some careful handling of components and some handy layout work - as @trashgod originally suggested.
Still, I dunno, I'd rather do something like this and fake the border than fake drawing a button. If you draw your own button, you lose compliance with the current look and feel, and unless you do all the stuff the button UI does (handle rollovers, armed state, etc), it's unlikely to look good.
The Component Border class was designed to allow you to add a component as a Border to any component.
The default behaviour is to add the component inside the existing border. I didn't do a complete test, but it looks like the class can be customized to add the component on top of the existing border by doing:
// component.setLocation((int)x2, (int)y2);
component.setLocation(10, 0);
You should definitely look at Using Layout Managers. The second example in How to Use BoxLayout looks a lot like your example.
Addendum: It may be possible to extend AbstractBorder
, as described in Creating Custom Borders, to achieve the desired effect. You could pass in the button's listener, as discussed here, or maintain your own listener list.
精彩评论