Java菜單和工具欄學習教程
引導語:工具欄是顯示位圖式按鈕行的控制條,位圖式按鈕用來執行命令。以下是本站小編分享給大家的Java菜單和工具欄學習教程,歡迎閲讀!
1.1 菜單和工具欄
菜單和工具欄可提供簡單明瞭的指示説明,讓用户非常方便的完成軟件操作。利用菜單可以將程序功能模塊化。
1.1.1 JMenuBar 菜單
菜單的組織方式為:一個菜單條 (JMenuBar)中可以包含多個菜單(JMenu),一個菜單中可以包含多個菜單項(JMenuItem及其子類)。有一些支持菜單的組件,如JFrame、JDialog以及JApplet,都有一個setMenuBar(JMenuBar bar)方法,可以利用這個方法來設置菜單條。
菜單項是菜單系統中最基本的組件,用户與菜單的交互主要是菜單項的交互,因此事件處理也是針對菜單項的。當用户選擇了某個菜單項,就會觸發一個ActionEvent事件,可以編寫相應的類實現ActionListener接口對該事件進行處理。
例1-1演示瞭如何創建一個完整的菜單系統,可以通過點擊菜單項讓菜單項做出反應。
import .*;
import g.*;
import t.*;
class JMenuBarTest extends JFrame{
private JMenuBar bar = new JMenuBar();
private JMenu menuFile = new JMenu("文件");
private JMenuItem itemFile1 = new JMenuItem("新建");
private JMenuItem itemFile2 = new JMenuItem("打開");
private JMenuItem itemFile3 = new JMenuItem("保存");
private JMenuItem itemFile4 = new JMenuItem("退出");
private JMenu menuHelp = new JMenu("幫助");
private JMenuItem itemHelp1 = new JMenuItem("幫助主題");
private JMenuItem itemHelp2 = new JMenuItem("關於記事本");
private JTextArea ta = new JTextArea(10,30);
public JMenuBarTest(String title){
super(title);
//設置快捷鍵
ccelerator(eyStroke('N',_MASK));
ccelerator(eyStroke('O',_MASK));
ccelerator(eyStroke('S',_MASK));
ccelerator(eyStroke('E',_MASK));
//添加JMenuItem到JMenu
(itemFile1);
(itemFile2);
(itemFile3);
eparator();//加分割線
(itemFile4);
(itemHelp1);
eparator();//加分割線
(itemHelp2);
//添加JMenu到JBar
MenuBar(bar);
(menuFile);
(menuHelp);
Container contentPane = ontentPane();
(ta);
pack();
isible(true);
//註冊監測器
ctionListener(new MyActionListener());
ctionListener(new MyActionListener());
ctionListener(new MyActionListener());
ctionListener(new MyActionListener());
ctionListener(new MyActionListener());
ctionListener(new MyActionListener());
efaultCloseOperation(_ON_CLOSE);
}
private class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
ext("您按下了菜單項:"+ctionCommand());
}
}
}
public class Test1_1 {
public static void main(String[] args) {
new JMenuBarTest("記事本");
}
}
1.1.2 JToolBar 工具欄
JToolBar(工具欄)是提供快速訪問常用菜單命令的一個按鈕欄,一般和菜單欄一起出現,當然也可獨立出現。
JToolBar提供了四個構造方法用於創建JToolBar對象。
表1-13 JToolBar構造方法
構造方法説明
JToolBar()創建新的工具欄;默認的方向為 HORIZONTAL
JToolBar(int orientation)創建具有指定 orientation 的.新工具欄
JToolBar(String name)創建一個具有指定 name 的新工具
JToolBar(String name,
int orientation)
創建一個具有指定 name 和 orientation 的新工具欄各參數意義:
name - 工具欄的名稱
orientation - 初始方向,值可為 HORIZONTAL(水平方向) 或 VERTICAL (垂直方向)
工具欄的添加很簡單,直接使用JFrame的add方法即可完成添加,工具欄內可添加按鈕等組件。
例1-9演示了單獨的一個工具欄,該程序未添加事件處理,若要添加事件處理,實際上是對添加到工具欄內的組件的事件處理,如添加JButton則可處理ActionEvent事件。