Java Swing高级组件对话框、菜单和工具栏组件
- 1 对话框
- 1.1 JDialog对话框
- JDialog对话框案例
- 1.2 JOptionPane标准对话框
- JOptionPane标准对话框案例
- 1.3 JFileChooser文件对话框
- JFileChooser文件对话框案例
- 1.4 JColorChooser颜色对话框
- JColorChooser颜色对话框案例
- 2 菜单
- 2.1 下拉式菜单
- 下拉式三级菜单案例
- 2.2 弹出式菜单
- 弹出式菜单案例
- 3 工具栏
- 工具栏案例
1 对话框
1.1 JDialog对话框
自定义一个对话框的步骤:
①定义-个类继承JDialog类
②创建用户界面组件,并添加到对话框中
③添加用户界面的事件处理
③设置对话框大小并显示
JDialog对话框案例
创建三个对话框,模式对话框、非模式对话框和自定义对话框
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JDialogDemo extends JFrame {
JPanel p;
JButton btnMod, btnNon, btnMy;
//声明两个对话框组件
JDialog modDialog, nonDialog;
//声明自定义的对话框组件
MyDialog myDialog;
public JDialogDemo() {
super("测试对话框");
p = new JPanel();
btnMod = new JButton("模式对话框");
btnNon = new JButton("非模式对话框");
btnMy = new JButton("自定义对话框");
//创建模式对话框
modDialog = new JDialog(this, "模式对话框", true);
//设置对话框的坐标和大小
modDialog.setBounds(250, 200, 200, 100);
//创建非模式对话框
nonDialog = new JDialog(this, "非模式对话框", false);
//设置对话框的坐标和大小
nonDialog.setBounds(250, 200, 200, 100);
//创建自定义对话框
myDialog = new MyDialog(this);
//模式对话框绑定事件
btnMod.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//显示模式对话框
modDialog.setVisible(true);
}
});
//非模式对话框绑定事件
btnNon.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//显示非模式对话框
nonDialog.setVisible(true);
}
});
//自定义对话框绑定事件
btnMy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//显示自定义对话框
myDialog.setVisible(true);
}
});
p.add(btnMod);
p.add(btnNon);
p.add(btnMy);
this.add(p);
//设置窗口大小
this.setSize(400, 300);
//设置窗口左上角坐标
this.setLocation(200, 100);
//设置窗口关闭方式
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置窗口可见
this.setVisible(true);
}
public static void main(String[] args) {
new JDialogDemo();
}
}
//创建一个对话框类,继承JDialog类
class MyDialog extends JDialog {
//声明对话框中的组件
JPanel p;
JLabel lblNum;
JTextField txtNum;
JButton btnOK;
public MyDialog(JFrame f) {
super(f, "我的对话框", true);
//创建对话框中的组件
p = new JPanel();
lblNum = new JLabel("请输入一个数");
txtNum = new JTextField(10);
btnOK = new JButton("确定");
//注册监听
btnOK.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int num = Integer.parseInt(txtNum.getText().trim());
System.out.println(num + "*" + num + "=" + (num * num));
} catch (NumberFormatException e1) {
System.out.println(txtNum.getText() + "不是数字,请重新输入!");
//清空文本框
txtNum.setText("");
}
}
});
//将组件添加到面板上
p.add(lblNum);
p.add(txtNum);
p.add(btnOK);
//将面板添加到对话框
this.add(p);
//设置对话框大小
this.pack();
//设置对话框坐标
this.setLocation(250, 200);
}
}
1.2 JOptionPane标准对话框
1、消息对话框
JOptionPane.showMessageDialog()静态方法用于显示消息对话框,该方法有以下重载方式
void showMessageDialog(Component parentComponent,Object message)
void showMessageDialog(Component parentComponent,Object message,String title,int messageType)
showMessageDialog(Component parentComponent, Object message, String title, int messageType,Icon icon)
//第二个重载方式示例
JOptionPane.showMessageDialog (null,
"您输入的数据不正确,请重新输入!",
"错误提示",
JOptionPane.ERROR_ MESSAGE);
2、输入对话框
JOptionPane.showInputDialog()静态方法用于显示输入对话框,该方法有以下重载方式
String showInputDialog(Object message)
String showInputDialog(Component parentComponent,Object message)
String showInputDialog(Component parentComponent,Object message,String title,int messageType)
//示例
JOptionPane.showInputDialog(null,"请输入一个数字:")
3、确认对话框
JOptionPane.showConfirmDialog()静态方法用于显示确认对话框,该方法有以下重载方式
int showConfirmDialog(Component component,Object message)
int showConfirmDialog(Component component,Object message,String title,int optionType)
showConfirmDialog(Component component, Object message, String title, int optionType, int messageType)
optionType参数代表选项类型
在JOptionPane类中提供了四种选项类型的静态变量
DEFAULT_ OPTION:默认选项
YES_ NO_ OPTION: Yes和No选项
YES_ NO_ CANCEL_OPTION: Yes、 No和CANCEL选项
OK_CANCEL_OPTION: Ok和Cancel选项
//示例
JOptionPane.showConfirmDialog(null,
"您确定要删除吗?",
"删除",
JOptionPane.YES_ NO_OPTION);
4、选项对话框
JOptionPane.showOptionDialog()静态方法用于显示选项对话框
int showOptionDialog(Component parentComponent,Object message,String title,int optionType, int messageType,Icon icon,Object[ ] options,Object initialValue)
//示例
ObjectI[] options = { "Red","Green","Blue" };
JOptionPane.showoptionDialog(null,
"选择颜色:",
"选择",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[0]) ;
JOptionPane标准对话框案例
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class JOptionPaneDemo extends JFrame {
private JPanel p;
private JTextArea txtContent;
private JButton btnInput, btnMsg, btnConfirm, btnOption;
public JOptionPaneDemo() {
super("JOptionPane标准对话框");
p = new JPanel();
btnInput = new JButton("输入");
btnMsg = new JButton("消息");
btnConfirm = new JButton("确认");
btnOption = new JButton("选项");
txtContent = new JTextArea(20, 10);
// 注册监听
btnInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 显示输入对话框,并返回用户输入的字符串
String strIn = JOptionPane.showInputDialog(btnInput, "请输入一个数字:");
try {
int num = Integer.parseInt(strIn.trim());
// 在文本域中追加内容
txtContent.append(num + " * " + num + " = " + (num * num)
+ "\n");
} catch (NumberFormatException e1) {
txtContent.append(strIn + "不是数字,请重新输入!\n");
}
}
});
btnMsg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 显示消息对话框
JOptionPane.showMessageDialog(btnMsg, "下午两点开QST员工大会!", "消息",
JOptionPane.INFORMATION_MESSAGE);
txtContent.append("显示消息对话框!\n");
}
});
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 显示确认对话框
int r = JOptionPane.showConfirmDialog(btnConfirm, "您确定要删除吗?",
"确认", JOptionPane.YES_NO_OPTION);
if (r == JOptionPane.YES_OPTION) {
txtContent.append("显示确认对话框!您选择了'是'\n");
} else {
txtContent.append("显示确认对话框!您选择了'否'\n");
}
}
});
btnOption.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = {"Red", "Green", "Blue"};
// 显示选择对话框
int sel = JOptionPane.showOptionDialog(btnOption, "选择颜色:",
"选择", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (sel != JOptionPane.CLOSED_OPTION) {
txtContent.append("显示选择对话框!颜色: " + options[sel] + "\n");
}
}
});
// 将按钮添加到面板中
p.add(btnInput);
p.add(btnMsg);
p.add(btnConfirm);
p.add(btnOption);
// 将文本域添加到窗口中央
this.add(txtContent);
// 将面板添加到窗体南面
this.add(p, BorderLayout.SOUTH);
// 设定窗口大小(宽度400像素,高度300像素)
this.setSize(400, 300);
// 设定窗口左上角坐标(X轴200像素,Y轴100像素)
this.setLocation(200, 100);
// 设定窗口默认关闭方式为退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视(显示)
this.setVisible(true);
}
public static void main(String[] args) {
new JOptionPaneDemo();
}
}
1.3 JFileChooser文件对话框
其常用构造方法为:
JFileChooser文件对话框案例
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JFileChooserDemo extends JFrame {
private JPanel p;
private JScrollPane sp;
private JTextArea txtContent;
private JButton btnOpen, btnSave, btnClear;
public JFileChooserDemo() {
super("JFileChooser文件对话框");
p = new JPanel();
btnOpen = new JButton("打开");
btnSave = new JButton("保存");
btnClear = new JButton("清空");
txtContent = new JTextArea(20, 10);
// 创建加载文本域的滚动面板
sp = new JScrollPane(txtContent);
// 注册监听
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openFile();
}
});
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saveFile();
}
});
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 清空文本域
txtContent.setText("");
}
});
// 将按钮添加到面板中
p.add(btnOpen);
p.add(btnSave);
p.add(btnClear);
// 将滚动面板添加到窗口中央
this.add(sp);
// 将面板添加到窗体南面
this.add(p, BorderLayout.SOUTH);
// 设定窗口大小
this.setSize(600, 500);
// 设定窗口左上角坐标(X轴200像素,Y轴100像素)
this.setLocation(200, 100);
// 设定窗口默认关闭方式为退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视(显示)
this.setVisible(true);
}
// 打开文件的方法
private void openFile() {
// 实例化一个文件对话框对象
JFileChooser fc = new JFileChooser();
// 显示文件打开对话框
int rVal = fc.showOpenDialog(this);
// 如果点击确定(Yes/OK)
if (rVal == JFileChooser.APPROVE_OPTION) {
// 获取文件对话框中用户选中的文件名
String fileName = fc.getSelectedFile().getName();
// 获取文件对话框中用户选中的文件所在的路径
String path = fc.getCurrentDirectory().toString();
try {
// 创建一个文件输入流,用于读文件
FileReader fread = new FileReader(path + "/" + fileName);
// 创建一个缓冲流
BufferedReader bread = new BufferedReader(fread);
// 从文件中读一行信息
String line = bread.readLine();
// 循环读文件中的内容,并显示到文本域中
while (line != null) {
txtContent.append(line + "\n");
// 读下一行
line = bread.readLine();
}
bread.close();
fread.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 保存文件的方法
private void saveFile() {
// 实例化一个文件对话框对象
JFileChooser fc = new JFileChooser();
// 显示文件保存对话框
int rVal = fc.showSaveDialog(this);
// 如果点击确定(Yes/OK)
if (rVal == JFileChooser.APPROVE_OPTION) {
// 获取文件对话框中用户选中的文件名
String fileName = fc.getSelectedFile().getName();
// 获取文件对话框中用户选中的文件所在的路径
String path = fc.getCurrentDirectory().toString();
try {
// 创建一个文件输出流,用于写文件
FileWriter fwriter = new FileWriter(path + "/" + fileName);
// 将文本域中的信息写入文件中
fwriter.write(txtContent.getText());
fwriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new JFileChooserDemo();
}
}
1.4 JColorChooser颜色对话框
其基本语法为:
JColorChooser颜色对话框案例
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JColorChooserDemo extends JFrame {
private JPanel p;
// 声明颜色选取器
private JColorChooser ch;
// 声明一个存放颜色的对话框
private JDialog colorDialog;
private JButton btnChange;
public JColorChooserDemo() {
super("颜色对话框");
p = new JPanel();
// 实例化颜色选取器对象
ch = new JColorChooser();
// 创建一个颜色对话框,颜色选取器对象作为其中的一个参数
colorDialog = JColorChooser.createDialog(this, "选取颜色", true, ch, null,
null);
btnChange = new JButton("改变面板背景颜色");
btnChange.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 显示颜色对话框
colorDialog.setVisible(true);
// 设置面板背景颜色为用户选取的颜色
p.setBackground(ch.getColor());
}
});
p.add(btnChange);
// 将面板添加到窗体
this.add(p);
// 设定窗口大小
this.setSize(800, 600);
// 设定窗口左上角坐标(X轴200像素,Y轴100像素)
this.setLocation(200, 100);
// 设定窗口默认关闭方式为退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视(显示)
this.setVisible(true);
}
public static void main(String[] args) {
new JColorChooserDemo();
}
}
2 菜单
2.1 下拉式菜单
1、JMenuBar菜单栏
菜单栏是个水平栏,用来管理菜单
Swing中的菜单栏是通过使用JMenuBar类来创建
//创建菜单栏对象
JMenuBar menuBar = new JMenuBar();
//添加菜单栏到窗口顶部
frame.setJMenuBar(munuBar);
2、JMenu菜单
//创建菜单
//菜单的文本为 开始
JMenu menuFile = new JMenu("开始");
3、JMenuItem菜单项
//创建菜单项
JMenuItem menuFile = new JMenuItem("推出");
下拉式三级菜单案例
import javax.swing.*;
public class JMenuDemo extends JFrame {
private JPanel p;
//声明菜单栏
private JMenuBar menuBar;
//声明菜单
private JMenu menuFile, menuEdit, menuHelp, menuNew;
//声明菜单项
private JMenuItem miSave, miExit, miCopy, miPost, miAbout, miC, miJava, miOther;
public JMenuDemo() {
super("下拉菜单");
p = new JPanel();
//创建菜单栏对象
menuBar = new JMenuBar();
//将菜单栏设置到窗体中
this.setJMenuBar(menuBar);
// 创建菜单
menuFile = new JMenu("File");
menuEdit = new JMenu("Edit");
menuHelp = new JMenu("Help");
menuNew = new JMenu("New");
// 将菜单添加到菜单栏
menuBar.add(menuFile);
menuBar.add(menuEdit);
menuBar.add(menuHelp);
// 将新建菜单添加到文件菜单中
menuFile.add(menuNew);
// 在菜单中添加分隔线
menuFile.addSeparator();
// 创建菜单选项
miSave = new JMenuItem("Save");
miExit = new JMenuItem("Exit");
miCopy = new JMenuItem("Copy");
miPost = new JMenuItem("Post");
miAbout = new JMenuItem("About");
miC = new JMenuItem("Class");
miJava = new JMenuItem("Java Project");
miOther = new JMenuItem("Other...");
// 将菜单项添加到菜单中
menuFile.add(miSave);
menuFile.add(miExit);
menuEdit.add(miCopy);
menuEdit.add(miPost);
menuHelp.add(miAbout);
menuNew.add(miC);
menuNew.add(miJava);
menuNew.add(miOther);
// 将面板添加到窗体
this.add(p);
// 设定窗口大小
this.setSize(400, 300);
// 设定窗口左上角坐标(X轴200像素,Y轴100像素)
this.setLocation(200, 100);
// 设定窗口默认关闭方式为退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视(显示)
this.setVisible(true);
}
public static void main(String[] args) {
new JMenuDemo();
}
}
2.2 弹出式菜单
弹出式菜单案例
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
public class JPopupMenuDemo extends JFrame {
private JPanel p;
// 声明弹出菜单
private JPopupMenu popMenu;
// 声明菜单选项
private JMenuItem miUndo, miCopy, miPost, miCut;
public JPopupMenuDemo() {
super("JPopupMenu弹出菜单");
p = new JPanel();
// 创建弹出菜单对象
popMenu = new JPopupMenu();
// 创建菜单选项
miUndo = new JMenuItem("Undo");
miCopy = new JMenuItem("Copy");
miPost = new JMenuItem("Post");
miCut = new JMenuItem("Cut");
// 将菜单选项添加到菜单中
popMenu.add(miUndo);
popMenu.addSeparator();
popMenu.add(miCopy);
popMenu.add(miPost);
popMenu.add(miCut);
// 注册鼠标监听
p.addMouseListener(new MouseAdapter() {
// 重写鼠标点击事件处理方法
public void mouseClicked(MouseEvent e) {
// 如果点击鼠标右键
if (e.getButton() == MouseEvent.BUTTON3) {
int x = e.getX();
int y = e.getY();
// 在面板鼠标所在位置显示弹出菜单
popMenu.show(p, x, y);
}
}
});
// 将面板添加到窗体
this.add(p);
// 设定窗口大小
this.setSize(400, 300);
// 设定窗口左上角坐标
this.setLocation(200, 100);
// 设定窗口默认关闭方式为退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视(显示)
this.setVisible(true);
}
public static void main(String[] args) {
new JPopupMenuDemo();
}
}
3 工具栏
工具栏案例
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
public class JToolBarDemo extends JFrame {
private JPanel p;
// 声明工具栏
private JToolBar toolBar;
private JButton btnSave, btnPreview, btnDown, btnSearch, btnDelete;
public JToolBarDemo() {
super("JToolBar工具栏");
p = new JPanel();
// 创建工具栏
toolBar = new JToolBar();
// 将工具栏对象添加到窗体的北部(上方)
this.add(toolBar, BorderLayout.NORTH);
// 创建按钮对象,按钮上有文字和图片
btnSave = new JButton("保存", new ImageIcon("images\\save.png"));
btnPreview = new JButton("预览", new ImageIcon("images\\preview.png"));
btnDown = new JButton("下载", new ImageIcon("images\\down.png"));
btnSearch = new JButton("查询", new ImageIcon("images\\search.png"));
btnDelete = new JButton("删除", new ImageIcon("images\\delete.png"));
// 设置按钮的工具提示文本
btnSave.setToolTipText("保存");
btnPreview.setToolTipText("预览");
btnDown.setToolTipText("下载");
btnSearch.setToolTipText("查询");
btnDelete.setToolTipText("删除");
// 将按钮添加到工具栏中
toolBar.add(btnSave);
toolBar.add(btnPreview);
toolBar.add(btnDown);
toolBar.add(btnSearch);
toolBar.add(btnDelete);
// 将面板添加到窗体
this.add(p);
// 设定窗口大小
this.setSize(400, 300);
// 设定窗口左上角坐标(X轴200像素,Y轴100像素)
this.setLocation(200, 100);
// 设定窗口默认关闭方式为退出应用程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 设置窗口可视(显示)
this.setVisible(true);
}
public static void main(String[] args) {
new JToolBarDemo();
}
}