11.4 AWT常用組件
11.4.1 AWT常用組件
1.Button: 按鈕,可接受單擊操作。
2.Canvas:用於繪圖的畫布。
3.Checkbox:複選項框組件‘
4.CheckboxGroup:用於將多個Checkbox組件組合在一起。
5.Choice:下拉式 選擇框組件。
6.Frame:窗口,在GUI程序裏通過該類創建窗口。
7.Label:標籤類,用於旋轉提示性文本。
8.List:列表框組件,可以添加多頂條目。
9.Panel:不能單獨存在的基本容器類,必須放到其他容器中。
10.Scrollbar:滑動條組件。
11.ScrollPane:帶水平、垂直的滾動條的容器組件。
12.TextArea:多行文本域。
13.TextField:單行文本框。
11.4.2 對話框
對話框是Window類的子類,是一個容器類,屬於特殊組件.對話框是可以獨立存在的頂級窗口,用法跟窗口幾乎完全一樣.使用對話框注意兩點:
1.對話框通常依賴其他窗口,就是通常有一個parent窗口.
2.對話框有非模式和模式兩種.
對話框有多個重載構造器,構造器可能有如下三個參數:
owner:指定對話框所依賴 窗口.
title:指定對話框的窗口標題.
modal:指定該對話框是否是模式的,可以是true 可以是false
下面給出對話框使用示例:
import java.awt.*;
import java.awt.event.*;
public class TestDialog
{
Frame f = new Frame("測試");
Dialog d1 = new Dialog(f, "模式對話框" , true);
Dialog d2 = new Dialog(f, "非模式對話框" , false);
Button b1 = new Button("打開模式對話框");
Button b2 = new Button("打開非模式對話框");
Button b3 = new Button("測試");
public void init()
{
f.setBounds(300, 300 , 800, 600);
d1.setBounds(20 , 30 , 300, 400);
d2.setBounds(20 , 30 , 300, 400);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d1.setLayout(new BorderLayout());
d1.add(b3,BorderLayout.SOUTH);
d1.setVisible(true);
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d2.setVisible(true);
}
});
f.add(b1);
f.add(b2 , BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() //窗口關閉
{
public void windowClosing(WindowEvent arg0)
{
System.exit(1);
}
});
}
public static void main(String[] args)
{
new TestDialog().init();
}
}
Dialog類還有一個子類:FileDialog,它代表一個文件對話框,用於打開和保存文件,FileDialog也提供了幾個構造器,分別可支持parent、title、mode三個構造參數,其中 parent、title用於指定對話框所屬父窗口跟標題,mode用於指定該窗口用於打開和保存文件,支持如下兩個參數:FileDialog.LOAD、FileDialog.SAVE。
FileDialog提供瞭如下兩個方法來獲取被打開/保存的文件路徑。
1.getDirectory():獲取被打開的/保存文件的絕對路徑。
2.getFile();獲取被打開的/保存文件的文件名。
給出示例如下:
import java.awt.*;
import java.awt.event.*;
public class TestFileDialog
{
Frame f = new Frame("測試");
FileDialog d1 = new FileDialog(f, "選擇需要打開文件" , FileDialog.LOAD);
FileDialog d2 = new FileDialog(f, "選擇保存文件的路徑" , FileDialog.SAVE);
Button b1 = new Button("打開文件");
Button b2 = new Button("保存文件");
public void init()
{
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d1.setVisible(true);
System.out.println(d1.getDirectory() + d1.getFile());
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
d2.setVisible(true);
System.out.println(d2.getDirectory() + d2.getFile());
}
});
f.add(b1);
f.add(b2 , BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
public static void main(String[] args)
{
new TestFileDialog().init();
}
}