19、Java Swing JToolBar:工具栏组件
生活随笔
收集整理的這篇文章主要介紹了
19、Java Swing JToolBar:工具栏组件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
工具欄提供了一個用來顯示常用按鈕和操作的組件。
它可以把任意類型的組件附加到工具條上,但是通常是增加按鈕。
工具欄 JToolBar 類的常用構造方法:
- JToolBar() ----創建新的工具欄,默認的方向為 HORIZONTAL(水平方向)
- JToolBar(int orientation) ----創建具有指定 orientation(定位) 的新工具欄
- JToolBar(String name)---- 創建一個具有指定 name 的新工具欄
- JToolBar(String name,int orientation) ----創建一個具有指定 name 和 orientation
的新工具欄
與 JMenuBar 不一樣,JToolBar 對象可以直接被添加到容器中, JToolBar類的常用方法:
- add(Action a) ----添加一個指派動作的新的 JButton
- addSeparator()---- 將默認大小的分隔符添加到工具欄的末尾
- addSeparator(Dimension size)---- 將指定大小的分隔符添加到工具欄的末尾
- getComponentAtIndex(int i)---- 返回指定索引位置的組件
- getComponentIndex(Component c) ----返回指定組件的索引
- getMargin() ----返回工具欄邊框和它的按鈕之間的空白
- getOrientation()---- 返回工具欄的當前方向
- isFloatable()---- 獲取 floatable 屬性
- isRollover() ----返回 rollover 狀態
- setBorderPainted(boolean b) ----設置 borderPainted 屬性,如果需要繪制邊框,則此屬性為 true
- setFloatable(boolean b)---- 設置 floatable 屬性,如果要移動工具欄,此屬性必須設置為 true
- setLayout(LayoutManager mgr)---- 設置此容器的布局管理器
- setMargin(Insets m)---- 設置工具欄邊框和它的按鈕之間的空白
- setOrientation(int o) ----設置工具欄的方向
- setRollover(boolean rollover) ----設置此工具欄的 rollover 狀態
例 1
下面通過實例來說明如何使用 JToolBar 創建工具欄,在該實例中給工具欄上的按鈕添加了圖片,當圖片不存在時使用文字代替。主要實現步驟如下所示。
(2) 在構造方法中對工具欄進行設置,主要代碼如下所示。
public ToolBarDemo() {super(new BorderLayout());//創建工具欄JToolBar toolBar=new JToolBar();addButtons(toolBar);//創建一個文本域,用來輸出一些信息textArea=new JTextArea(15, 30);textArea.setEditable(false);JScrollPane scrollPane=new JScrollPane(textArea);//把組件添加到面板中setPreferredSize(new Dimension(450, 110));add(toolBar,BorderLayout.PAGE_START);add(scrollPane,BorderLayout.CENTER); }(3) 構造方法中創建了一個工具欄 toolBar,然后調用 addButtons() 方法為工具欄設置按鈕。
addButtons() 方法的代碼如下: protected void addButtons(JToolBar toolBar) {JButton button=null;button=makeNavigationButton("new1",NEW,"新建一個文件","新建");toolBar.add(button);button=makeNavigationButton("open1",OPEN,"打開一個文件","打開");toolBar.add(button);button=makeNavigationButton("save1",SAVE,"保存當前文件","保存");toolBar.add(button); }(4) 在 addButtons() 方法中調用 makeNavigationButton() 方法,實現對工具欄上的按鈕指定圖片、動作指令、提示信息和無圖片時的文本。具體實現代碼如下:
protected JButton makeNavigationButton(String imageName,String actionCommand,String toolTipText,String altText) {//搜索圖片String imgLocation=imageName+".jpg";URL imageURL=ToolBarDemo.class.getResource(imgLocation);//初始化工具按鈕JButton button=new JButton();//設置按鈕的命令button.setActionCommand(actionCommand);//設置提示信息button.setToolTipText(toolTipText);button.addActionListener(this);if(imageURL!=null){//找到圖像button.setIcon(new ImageIcon(imageURL));}else{//沒有圖像button.setText(altText);System.err.println("Resource not found: "+imgLocation);}return button; }(5) 運行程序,在窗口的頂部會看到包含 3 個按鈕的工具欄。當鼠標指針放在工具按鈕上時出現提示信息,如圖 1 所示。
總結
以上是生活随笔為你收集整理的19、Java Swing JToolBar:工具栏组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 18、Java Swing JMenu和
- 下一篇: 21、Java Swing JOptio