Java 里,关于JToolBar被拖放的事件!

来源:百度知道 编辑:UC知道 时间:2024/05/25 14:32:26
问题如下:
我做了个JToolBar,往里面添加了几个JButton,一开始JToolBar是横放的,所以我设置这些JButton: this.setHorizontalTextPosition(CENTER); this.setVerticalTextPosition(BOTTOM);
这样,文字就在图片的下方了,显得比较好看。
可是当我拖动JToolBar后,把JToolBar拖出来成了一个竖立的窗口,这时那些JButton就显得很难看了,
请问,如何才能随时根据JToolBar的横放或竖放,及时的设置JButton的文字于图片的相对位置?

JToolBar 里有个getOrientation()的方法,可以返回一个整数值为HORIZONTAL 或 VERTICAL,你可以由此获取当前JToolBar的位置状态。

至于怎么捕获用户对JToolBar位置的更改,你可以通过对JToolbar添加ComponentListener,并捕获其中的componentMoved(ComponentEvent e)方法。

下面是简单的例子:

toolBar.addComponentListener(new ComponentListener(){
public void componentResized(ComponentEvent e)
{}
public void componentMoved(ComponentEvent e)
{
if (toolBar.getOrientation() == SwingConstants.VERTICAL)//toolBar为垂直状态
{
//这里对Button的布局进行更改
}
if (toolBar.getOrientation() == SwingConstants.HORIZONTAL)//toolBar为水平状态
{
//这里对Button的布局进行更改
}
}
public void componentShown(ComponentEvent e)
{}
public void componentHidden(ComponentEvent e)
{}
});