Java swing菜單欄實(shí)現(xiàn)打開(kāi)、保存文件操作

首先,我們用Java swing中JMenu創(chuàng)建菜單欄、菜單項(xiàng),如下圖所示:


1.png

文件下下拉菜單項(xiàng):打開(kāi)、保存、打印、退出。


2.png

點(diǎn)擊打開(kāi)按鈕(item1),可實(shí)現(xiàn)文件的打開(kāi)操作。
從目錄中選擇目標(biāo)文件(txt),確定打開(kāi)。

Txt文件即可顯示在窗口的文檔區(qū)域。如下圖:


3.png

重新輸入一些內(nèi)容,點(diǎn)擊文件下拉下的保存文件(item2),選擇另存為的目錄。
例存在桌面,則在桌面中可看到該txt文件夾。
4.png

打開(kāi)該文件即可看到輸入的內(nèi)容。
5.png

退出操作(item4)
6.png

具體代碼如下:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.management.RuntimeErrorException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


import javafx.scene.control.Tab;


public class Newcaidan {

    JFrame f;
    JLabel label;
    JTextArea textArea;
    JFileChooser fileChooser;
    FileInputStream fileInStream;

    public Newcaidan() {
        // TODO Auto-generated constructor stub
        f=new JFrame("測(cè)試窗口");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane=f.getContentPane();
        textArea=new JTextArea();
        JScrollPane scrollPane=new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(350, 300));
        JTextArea textArea = new JTextArea(10, 10);
        JPanel panel=new JPanel();
        JMenuBar menuBar1=new JMenuBar();  //添加菜單條組件
        f.setJMenuBar(menuBar1);          //將菜單欄添加到頂層容器中
        JMenu menu1=new JMenu("文件");
        JMenu menu2=new JMenu("編輯");
        JMenu menu3=new JMenu("視圖");
        JMenu menu4=new JMenu("運(yùn)行");
        JMenu menu5=new JMenu("工具");
        JMenu menu6=new JMenu("幫助");
        
        //將菜單組件添加到菜單條組件中
        menuBar1.add(menu1);
        menuBar1.add(menu2);
        menuBar1.add(menu3);
        menuBar1.add(menu4);
        menuBar1.add(menu5);
        menuBar1.add(menu6);
        
        //創(chuàng)建菜單項(xiàng)組件
        JMenuItem item1=new JMenuItem("打開(kāi)");
        JMenuItem item2=new JMenuItem("保存");
        JMenuItem item3=new JMenuItem("打印");
        JMenuItem item4=new JMenuItem("退出");
        menu1.add(item1);
        menu1.add(item2);
        menu1.addSeparator();           //菜單項(xiàng)之間的分隔線組件
        menu1.add(item3);
        menu1.addSeparator();
        menu1.add(item4);
        
        //設(shè)置頂層容器類的可見(jiàn)性
        f.setVisible(true);
        label=new JLabel("",JLabel.CENTER);
        contentPane.add(label, BorderLayout.NORTH);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        contentPane.add(panel, BorderLayout.SOUTH);
        f.pack();
        //處理退出菜單項(xiàng)的動(dòng)作事件
        item4.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed( ActionEvent e) {
                // TODO Auto-generated method stub
                int i=JOptionPane.showConfirmDialog(null, "是否真的退出系統(tǒng)",
                        "退出確認(rèn)對(duì)話框",JOptionPane.YES_NO_CANCEL_OPTION);
                //通過(guò)對(duì)話框中按鈕的選擇來(lái)決定結(jié)果,單機(jī)yes時(shí),窗口直接消失
                if(i==0)
                    f.dispose();
                
            }
        });
        item1.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                JFileChooser chooser = new JFileChooser();
                if (chooser.showOpenDialog(item1)==JFileChooser.APPROVE_OPTION) {//
                    File file = chooser.getSelectedFile();
                    textArea.setText(file.getName()+":"+file.getPath()+"\n"+file.length());
                    readFile(file);
                };
                  
            }       
        });
        item2.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                JFileChooser chooser = new JFileChooser();
                if (chooser.showSaveDialog(item2)==JFileChooser.APPROVE_OPTION) {
                    File file = chooser.getSelectedFile();
                    writeFile(file.getPath());
            }
            }
        });
    }
        public void copyFile(File file){//復(fù)制文件
            File to=new File(file.getAbsolutePath()+"_copy");
            if (file.isFile()) {
                byte[] buf = new byte[1024];//字節(jié)流
                int length=0;
                try {
                    FileInputStream in=new FileInputStream(file);
                    FileOutputStream out=new FileOutputStream(to);
                    while((length=in.read(buf))>0){
                        out.write(buf,0,length);
                    }
                    out.flush();
                    in.close();
                    out.close();
                } catch (Exception e) {
                    // TODO Auto-generated catchblock
                    e.printStackTrace();
                }

            }
        }
        
    public void readFile(File file){//讀文件
        BufferedReader bReader;
        try {
            bReader=new BufferedReader(new FileReader(file));
            StringBuffer sBuffer=new StringBuffer();
            String str;
            while((str=bReader.readLine())!=null){
                sBuffer.append(str+'\n');
                System.out.println(str);
            }
            textArea.setText(sBuffer.toString());
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    public void writeFile(String savepath){//寫(xiě)文件
        FileOutputStream fos= null;
        try {
            fos=new FileOutputStream(savepath);
            fos.write(textArea.getText().getBytes());
            fos.close();
            System.out.println("已保存");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       textArea.getText();
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new Newcaidan();

    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過(guò)CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫(kù)組件 SD...
    陽(yáng)明AI閱讀 16,228評(píng)論 3 119
  • 現(xiàn)在回過(guò)頭來(lái)想想都覺(jué)得有些夸張,也覺(jué)得有些慶幸。16年的12月很偶然的一個(gè)機(jī)會(huì)看到了@萬(wàn)能的大熊 建立的大熊會(huì)的納...
    嗨丨小丑閱讀 993評(píng)論 0 5
  • 泉眼無(wú)聲惜細(xì)流,樹(shù)陰照水愛(ài)晴柔。 小荷才露尖尖角,早有蜻蜓立上頭。 那一年,一切剛好。 8月底的天氣,依然讓人不舒...
    散步的青蛙閱讀 204評(píng)論 0 1
  • 1.我怎麼如此幸運(yùn),昨天晚上翻看微信朋友圈的信息,看到沈琴老師畫(huà)的柿子惟妙惟俏,心中羨慕不已; 2.我怎麼如此幸運(yùn)...
    獨(dú)一無(wú)二的小茶葉閱讀 452評(píng)論 1 3

友情鏈接更多精彩內(nèi)容