8.5.2 JToolBar 工具欄
JToolBar(工具欄)是提供快速訪問常用菜單命令的一個按鈕欄,一般和菜單欄一起出現(xiàn),當(dāng)然也可獨(dú)立出現(xiàn)。
JToolBar提供了四個構(gòu)造方法用于創(chuàng)建JToolBar對象。
表8-13 JToolBar構(gòu)造方法
構(gòu)造方法 |
說明 |
JToolBar() |
創(chuàng)建新的工具欄;默認(rèn)的方向?yàn)?HORIZONTAL |
JToolBar(intorientation) |
創(chuàng)建具有指定 orientation 的新工具欄 |
JToolBar(Stringname) |
創(chuàng)建一個具有指定 name 的新工具 |
JToolBar(Stringname, intorientation) |
創(chuàng)建一個具有指定 name 和 orientation 的新工具欄 |
各參數(shù)意義:
name - 工具欄的名稱
orientation - 初始方向,值可為 HORIZONTAL(水平方向) 或 VERTICAL (垂直方向)
工具欄的添加很簡單,直接使用JFrame的add方法即可完成添加,工具欄內(nèi)可添加按鈕等組件。
例8-9演示了單獨(dú)的一個工具欄,該程序未添加事件處理,若要添加事件處理,實(shí)際上是對添加到工具欄內(nèi)的組件的事件處理,如添加JButton則可處理ActionEvent事件。
[例8-9]
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class JToolBarTest extends JFrame{
private JToolBar tb = new JToolBar();
private JButton[] tbButtons;
public JToolBarTest(){
String[] images = {"1.jpg","2.jpg"};
//創(chuàng)建ImageIcon數(shù)組
ImageIcon[] toolImage = new ImageIcon[images.length];
tbButtons = new JButton[images.length];
for(int i=0;i
toolImage[i] = new ImageIcon("bin\\"+images[i]);
//創(chuàng)建帶有圖標(biāo)的JButton
tbButtons[i] = new JButton(toolImage[i]);
//將帶有圖標(biāo)的JButton添加到工具欄
tb.add(tbButtons[i]);
}
this.add(tb);//添加工具欄到JFrame
pack();
setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public class Test8_9 {
public static void main(String[] args) {
new JToolBarTest();
}
}