• Demo


    Electron Dictionary电子词典程序
    界面设计使用选项卡的设计方式,有查单词和生词本这两个示例功能选项。查单词功能选项页面可以输入单词查询,并返回查到的结果,还可以选择将查询结果添加到生词本。生词本功能选项页面,能将添加过的生词以表格的形式展示出来,添加单词到生词本后生词本中的数据能自动同步刷新。
    ·增加新功能只需要添加item就可以了方便扩展

    Main启动类

    public class Main {
    
        public static void main(String[] args) {
            Window window = new Window("词典小程序");
        }
    }
    

    UI窗口类

    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class Window extends JFrame implements ActionListener {
        public OperationWordList op = new OperationWordList();
    
        private JTabbedPane tabs = new JTabbedPane(JTabbedPane.LEFT,JTabbedPane.SCROLL_TAB_LAYOUT);
    
        private ImageIcon imageIconTr = new ImageIcon(System.getProperty("user.dir")+"\src\love\icon\translate.png");
        private ImageIcon imageIconWL = new ImageIcon(System.getProperty("user.dir")+"\src\love\icon\wordList.png");
    
        //第一个item中控件
        private JTextField txtInput = new JTextField();
        private JTextField txtResult = new JTextField();
        private JLabel lblInfo = new JLabel( "Translation Demo", JLabel.CENTER );
        private JLabel lblinput = new JLabel( "翻译内容:", JLabel.LEFT );
        private JLabel lblresult = new JLabel( "结果", JLabel.LEFT );
        private JButton btnTrans = new JButton( "翻译" );
        private JButton btnAddBook = new JButton( "加入生词本" );
    
    
        private JPanel panel1 = new JPanel(new GridLayout(3,0));
        private JPanel panel2 = new JPanel(new BorderLayout());
        private void setPanel1(){
            //提示panel
            JPanel lblPanel = new JPanel(new GridLayout( 2, 1 ,10,10));
            lblPanel.add(lblinput);
            lblPanel.add(lblresult);
            //输入输入panel
            JPanel txtPanel = new JPanel( new GridLayout( 2, 1,10,10 ) );
            txtPanel.add(new JScrollPane(txtInput));    //加入滚动条
            txtPanel.add(new JScrollPane(txtResult));
            //将提示panle和输入输出panel加入布局
            JPanel panelLT = new JPanel(new BorderLayout());
            panelLT.add( lblPanel, BorderLayout.WEST );
            panelLT.add( txtPanel, BorderLayout.CENTER );
    
            JPanel panelBtn = new JPanel();
            panelBtn.add(btnTrans);
            panelBtn.add(btnAddBook);
    
            btnTrans.addActionListener(this);   //注册监听
            btnTrans.setActionCommand("Translate");     //添加按钮识别码
            btnAddBook.addActionListener(this);
            btnAddBook.setActionCommand("AddBook");
    
            panel1.add(lblInfo);
            panel1.add(panelLT);
            panel1.add(panelBtn);
        }
    
        // 默认表格模型
        private DefaultTableModel model = null;
        private JTable table = null;
    
        private void setPanel2(){
            String[][] datas = {};
            String[] titles = { "English", "翻译" };
            model = new DefaultTableModel(datas, titles);
            table = new JTable(model);
            panel2.add(new JScrollPane(table));
            refreshMyWord();
        }
        //刷新我的生词表
        private void refreshMyWord(){
            model.setRowCount(0);
            String key;
            String value;
            for (int i=0;i<op.myWords.size();i++){
                key = op.myWords.get(i);
                value = op.wordMap.get(op.myWords.get(i));
                model.addRow(new String[] { key, value });
            }
        }
    
        public Window(String title) {
            super(title);
            MyTabPanel myTabPanel = new MyTabPanel();
            tabs.setUI(myTabPanel);     //使用自定义的选项卡UI
    
            imageIconTr.setImage(imageIconTr.getImage().getScaledInstance(25, 25,Image.SCALE_DEFAULT));
            imageIconWL.setImage(imageIconWL.getImage().getScaledInstance(25, 25,Image.SCALE_DEFAULT));
    
            setPanel1();
            setPanel2();
    
    
            tabs.addTab("找单词", imageIconTr, panel1);//
            tabs.addTab("生词本", imageIconWL, panel2);//
    
            Container contentPane = getContentPane();
            contentPane.add(tabs);
    
            setSize(600,450);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
        }
    
        public void actionPerformed(ActionEvent e) {
            //判断按钮click
            if (e.getActionCommand().equals("Translate")) {
                if(txtInput.getText().equals(""))
                    txtResult.setText("请输入内容");
                else
                    txtResult.setText(op.getTranslate(txtInput.getText()));
            }
            if (e.getActionCommand().equals("AddBook")) {
                if (op.isInMyWord(txtInput.getText()))
                    JOptionPane.showMessageDialog(this,"您已经添加过该单词!");
                else if(txtInput.getText().equals(""))
                    txtResult.setText("请输入内容");
                else if (op.isGetWord)
                {
                    if(op.addWordToList(txtInput.getText()))
                    {
                        JOptionPane.showMessageDialog(this,"添加成功!");
                        op.getMyWordList();
                        refreshMyWord();
                    }
                }
                else
                    JOptionPane.showMessageDialog(this,"遇到问题!写入失败!");
            }
        }
    
    }
    

    OperationWordList文件操作类

    import java.io.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;
    
    public class OperationWordList {
        public Map<String, String> wordMap = new HashMap<String, String>();
        ArrayList<String> myWords = new ArrayList<String>();
        public boolean isGetWord=false;     //是否查到单词
    
        public OperationWordList(){
            readWordList();
            getMyWordList();
        }
    
        //读取单词表数据添加到HashMap
        public void readWordList() {
            /* 向wordMap内添加英语翻译 */
            try {
                //替换单词表文件路径
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File
                        (System.getProperty("user.dir")+"\src\love\data\wordList.txt")), "UTF-8"));
                String lineTxt = null;
                while ((lineTxt = br.readLine()) != null) {
                    String[] words = lineTxt.split("   ");
                    wordMap.put(words[0], words[1]);
                }
            } catch (Exception e) {
                System.err.println("read errors :" + e);
            }
        }
        //获取我的生词表
        public void getMyWordList(){
            /* 向wordMap内添加英语翻译 */
            try {
                //替换单词表文件路径
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File
                        (System.getProperty("user.dir")+"\src\love\data\myWordList.txt")), "UTF-8"));
                String lineTxt = null;
                myWords.clear();
                while ((lineTxt = br.readLine()) != null) {
                    myWords.add(lineTxt);
                }
            } catch (Exception e) {
                System.err.println("read errors :" + e);
            }
        }
    
        //翻译
        public String getTranslate(String str){
            if (wordMap.containsKey(str)){
                isGetWord = true;
                return wordMap.get(str);
            }
            else{
                isGetWord = false;
                return "!单词表中未找到该单词!";
            }
        }
    
        //判断单词是否已经加入我的生词表
        public boolean isInMyWord(String str1){
            if (myWords.contains(str1))
                return true;
            else
                return false;
        }
    
        //添加生词并返回写入 成功/失败
        public boolean addWordToList(String str1){
            FileWriter fw = null;
            try {
                File f=new File(System.getProperty("user.dir")+"\src\love\data\myWordList.txt");
                fw = new FileWriter(f, true);
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            PrintWriter pw = new PrintWriter(fw);
            pw.println(str1);
            pw.flush();
    
            try {
                fw.flush();
                pw.close();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    }
    

    MyTabPanel 自定义选项卡UI类

    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import java.awt.*;
    
    public class MyTabPanel extends BasicTabbedPaneUI {
        //自定义选项卡宽度和高度
        protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
            return super.calculateTabWidth(tabPlacement, tabIndex, metrics)+50;
        }
    
        protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight)
        {
            return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight)+20;
        }
    
        //标签颜色
        protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex,
                                          int x, int y, int w, int h, boolean isSelected) {
            Color defaultColor = new Color(193, 210, 240);
            Color selectedColor = new Color(102,204,255);
            //设置选中时和未被选中时的颜色
            g.setColor(!isSelected ? defaultColor : selectedColor);
            //填充图形,即选项卡为矩形
            g.fillRect(x + 5, y + 5, w, h);
        }
    
    }
    

    单词表数据如下,单词和翻译中间3个空格

    abandon   v.抛弃,放弃
    abandonment   n.放弃
    abbreviation   n.缩写
    abeyance   n.缓办,中止
    abide   v.遵守
    ability   n.能力
    able   adj.有能力的,能干的
    abnormal   adj.反常的,变态的
    aboard   adv.船(车)上
    abolish   v.废除,取消
    abolition   n.废除,取消
    abortion   n.流产
    abortive   adj.无效果的,失败的
    about   prep.关于,大约
    above   prep.在...之上,高于
    above-mentioned   adj.上述的
    abreast   adv.并肩,并列
    abridge   v.省略,摘要
    

    生词本文件只存英语数据

    文件目录如下

    里面icon图标和data单词表文件换一下就可以了

    ^_^

  • 相关阅读:
    docker实战总结01
    springboot项目发布docker
    TKmybatis VS mybatisplus对比
    xshell工具连接不上虚拟机问题解决
    微信提现功能测试点【杭州多测师】【杭州多测师_王sir】
    微信发表情包测试点【杭州多测师】【杭州多测师_王sir】
    python:使用任意语言,递归地将某个磁盘目录下的 jpeg 文件的扩展名修改为 jpg【杭州多测师_王sir】【杭州多测师】
    余额宝提现测试点【杭州多测师】【杭州多测师_王sir】
    python题目:斐波那契数列【杭州多测师】【杭州多测师_王sir】
    微信发视频测试点【面试题】【杭州多测师_王sir】
  • 原文地址:https://www.cnblogs.com/kongw/p/13070804.html
Copyright © 2020-2023  润新知