今天,简单总结一下关于小字典界面的设计。最终成品图如下:
鉴于本界面的布局并非使用常规布局,建议尝试使用Windowbuilder下的null布局来自由设置布局。本篇主要使用代码设计的思路创建以上界面。
功能实现
- 键入不等英文单词和释义,实现添加
- 针对某英文的中文释义进行修改,实现修改
- 针对某英文查找到中文释义并呈现,实现查找
- 对文本框的清空,实现清空
设计重点:
- 字典类的设计--TreeMap
- 嵌套盒式布局容器和中间容器JPanel的使用
- FlowLayout布局和BorderLayout布局的使用
- 事件响应的处理--添加不同情形下的提示对话框
字典类的设计
package work2;
import javax.swing.*;
import java.awt.*;
import java.util.TreeMap;
public class Dictionary {
TreeMap<String,String> words;
public Dictionary(){
words = new TreeMap<>();
}
//添加映射元素
public void addword(String en,String cn) {
words.put(en,cn);
}
//返回释义
public String findByEn(String en) {
if(words.get(en)!=null) {
return words.get(en); //由英文得到中文
}else {
return "nothing";
}
//由英文得到中文
}
//修改 释义
public void modify(String en,String cn) {
words.replace(en,cn); //用新cn替换en对应的cn;
}
}
窗口类代码设计
package work2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame implements ActionListener{
//Dictionary dic = new Dictionary();//实例化字典对象
JButton find,revise,add,clear;
JTextField En;
JTextField Cn;
Box boxH;
Box boxV1,boxV2;
JPanel panelfir,panelsec;
Dictionary dic;
Window(){
init();
setBounds(100,100,450,450);
setTitle("我的词典");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//界面实现
public void init() {
find = new JButton("查找");
revise = new JButton("修改");
add = new JButton("添加");
clear = new JButton("清空");
panelfir = new JPanel();
panelsec = new JPanel();
dic = new Dictionary();
En = new JTextField(10);
Cn = new JTextField(10);
boxH = Box.createHorizontalBox();
boxV1 = Box.createVerticalBox();
boxV2 = Box.createVerticalBox();
boxV1.add(new JLabel("英文"));
boxV1.add(new JLabel("释义"));
boxV2.add(En);
boxV2.add(Cn);
boxH.add(boxV1);
boxH.add(Box.createHorizontalStrut(10));
boxH.add(boxV2);
panelfir.add(boxH);
panelfir.add(find);
panelsec.add(revise);
panelsec.add(add);
panelsec.add(clear);
setLayout(new BorderLayout());
add(panelsec,BorderLayout.CENTER);
add(panelfir,BorderLayout.NORTH);
clear.addActionListener(this);
find.addActionListener(this);
add.addActionListener(this);
revise.addActionListener(this);
}
//内部类
public void actionPerformed(ActionEvent e) {
if((JButton)e.getSource()==add) {
dic.addword(En.getText(),Cn.getText() );
//添加响应对话框;
JOptionPane.showMessageDialog(null, "添加成功");
}else if((JButton)e.getSource()==find) {
String cn = dic.findByEn(En.getText());
if (cn=="nothing") {
JOptionPane.showMessageDialog(null, "查无此词");
}else {
Cn.setText(cn);
}
}else if((JButton)e.getSource()==revise) {
dic.modify(En.getText(), Cn.getText());
JOptionPane.showMessageDialog(null, "修改成功");
}else if((JButton)e.getSource() == clear) {
En.setText("");
Cn.setText("");
}
}
}
核心代码如上,有兴趣的可以尝试敲敲!希望你的字典可以有你的世界在:)