Java Swing程序设计实战攻略
Java Swing程序设计实战是Java界面开发的重要书籍,其中讲解了Swing界面组件的使用、事件处理、布局管理器等内容,并有大量的编程实例。攻略分为以下几个部分:
程序设计实践
- 掌握Swing组件的使用,如JLabel、JTextField、JComboBox等;
- 学会处理Swing组件的事件,如ActionEvent、ItemEvent等;
- 了解布局管理器的使用,如Flowlayout、Borderlayout、Gridlayout等;
- 学习如何创建对话框,并利用对话框完成用户输入;
- 学会使用JFileChooser创建文件选择对话框;
- 掌握Swing多线程的编程方法。
案例实例一
需求说明:
实现一个简单的计算器应用,支持整数四则运算和求幂操作,带有可视化界面。
解决方案:
- 创建一个JFrame并设置程序标题;
- 使用GridLayout布局管理器创建按钮面板;
- 创建计算器文本框和按钮,并将它们添加到面板中;
- 为按钮添加事件侦听器,处理按钮事件,计算运算结果,并将结果显示在计算器文本框中;
- 运行程序,测试功能是否正常。
下面是代码示例:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField;
public static void main(String[] args) {
Calculator calculator = new Calculator();
calculator.setVisible(true);
}
public Calculator() {
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
// 计算器文本框
textField = new JTextField();
textField.setHorizontalAlignment(JTextField.RIGHT);
textField.setEditable(false);
// 按钮面板
JPanel buttonPanel = new JPanel(new GridLayout(5, 4));
// 创建按钮
String[] buttonNames = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"};
for (String buttonName : buttonNames) {
JButton button = new JButton(buttonName);
button.addActionListener(this);
buttonPanel.add(button);
}
// 添加文本框和按钮面板
add(textField, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
// 设置窗口大小
pack();
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("=")) {
String expression = textField.getText();
try {
Double result = CalculatorUtils.evaluate(expression);
textField.setText(result.toString());
} catch (Exception ex) {
textField.setText("Error");
}
} else {
textField.setText(textField.getText() + command);
}
}
}
class CalculatorUtils {
private static final String OPERATORS = "+-*/^";
public static double evaluate(String expression) {
String[] tokens = expression.split(" ");
// 记录上一个运算符和操作数
String operator = "";
double operand = 0.0;
double result = 0.0;
for (String token : tokens) {
if (token.length() == 0) {
continue;
}
if (OPERATORS.contains(token)) {
operator = token;
} else {
double value = Double.parseDouble(token);
if (operator.equals("+")) {
result += value;
} else if (operator.equals("-")) {
result -= value;
} else if (operator.equals("*")) {
result *= value;
} else if (operator.equals("/")) {
result /= value;
} else if (operator.equals("^")) {
result = Math.pow(result, value);
} else {
result = value;
}
operator = "";
}
}
return result;
}
}
案例实例二
需求说明:
实现一个简单的文件管理器应用,支持浏览文件夹、创建文件夹、新建文件、删除文件等操作,并带有可视化界面。
解决方案:
- 创建一个JFrame并设置程序标题;
- 创建一个JFileChooser组件并设置为只浏览文件夹;
- 创建一个JTree组件并显示当前文件夹中的所有文件和文件夹;
- 为JTree组件添加事件侦听器,处理节点选择事件,并更新当前文件夹的内容;
- 创建一个菜单栏和菜单项,实现创建文件夹、新建文件、删除文件等操作;
- 运行程序,测试功能是否正常。
下面是代码示例:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class FileManager extends JFrame implements ActionListener {
private JTree tree;
private DefaultTreeModel treeModel;
private JFileChooser fileChooser;
private File currentFolder;
public static void main(String[] args) {
FileManager fileManager = new FileManager();
fileManager.setVisible(true);
}
public FileManager() {
setTitle("File Manager");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
// JFileChooser
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
// 右键菜单
JPopupMenu popupMenu = new JPopupMenu();
JMenuItem createFolderMenu = new JMenuItem("Create Folder");
JMenuItem createFileMenu = new JMenuItem("Create File");
JMenuItem deleteMenu = new JMenuItem("Delete");
createFolderMenu.addActionListener(this);
createFileMenu.addActionListener(this);
deleteMenu.addActionListener(this);
popupMenu.add(createFolderMenu);
popupMenu.add(createFileMenu);
popupMenu.add(deleteMenu);
tree = new JTree(new DefaultMutableTreeNode("My Computer"));
tree.setComponentPopupMenu(popupMenu);
// 开始选择文件夹
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
currentFolder = fileChooser.getSelectedFile();
updateTree();
} else {
System.exit(0);
}
// 布局
JScrollPane scrollPane = new JScrollPane(tree);
scrollPane.setPreferredSize(new Dimension(400, 500));
add(scrollPane, BorderLayout.CENTER);
pack();
}
private void updateTree() {
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(currentFolder.getAbsolutePath());
addChildren(rootNode, currentFolder);
treeModel = new DefaultTreeModel(rootNode);
tree.setModel(treeModel);
}
private void addChildren(DefaultMutableTreeNode parentNode, File parentFile) {
if (parentFile.isDirectory() && parentFile.listFiles() != null) {
for (File file : parentFile.listFiles()) {
if (file.isDirectory()) {
DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(file.getName());
parentNode.add(folderNode);
addChildren(folderNode, file);
} else {
DefaultMutableTreeNode fileNode = new DefaultMutableTreeNode(file.getName());
parentNode.add(fileNode);
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
TreePath selectedPath = tree.getSelectionPath();
if (command.equals("Create Folder")) {
String folderName = JOptionPane.showInputDialog(this, "请输入文件夹名称:");
if (folderName != null && folderName.length() > 0) {
File folder = new File(currentFolder.getAbsolutePath() + File.separator + folderName);
if (folder.mkdir()) {
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(folder.getName());
parentNode.add(folderNode);
treeModel.reload(parentNode);
}
}
} else if (command.equals("Create File")) {
String fileName = JOptionPane.showInputDialog(this, "请输入文件名称:");
if (fileName != null && fileName.length() > 0) {
File file = new File(currentFolder.getAbsolutePath() + File.separator + fileName);
try {
if (file.createNewFile()) {
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
DefaultMutableTreeNode fileNode = new DefaultMutableTreeNode(file.getName());
parentNode.add(fileNode);
treeModel.reload(parentNode);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
} else if (command.equals("Delete")) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
File file = new File(currentFolder.getAbsolutePath() + File.separator + node.getUserObject().toString());
if (node.isLeaf() && file.delete()) {
DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent();
parentNode.remove(node);
treeModel.reload(parentNode);
}
}
}
}
以上即为Java Swing程序设计实战的攻略,包含了实践和案例实例,希望对Java界面开发工程师们有所启发。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java Swing程序设计实战 - Python技术站