Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用JMenu在文本窗格中显示相同的内容?_Java_Swing_Jframe_Jmenu_Jmenubar - Fatal编程技术网

Java 如何使用JMenu在文本窗格中显示相同的内容?

Java 如何使用JMenu在文本窗格中显示相同的内容?,java,swing,jframe,jmenu,jmenubar,Java,Swing,Jframe,Jmenu,Jmenubar,我试图使用FileWriter和PrintWriter保存文本窗格中的内容 // Save file fileItem2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Pressed menu item! Save"); jStyledTextPane.setT

我试图使用FileWriter和PrintWriter保存文本窗格中的内容

// Save file
    fileItem2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Pressed menu item! Save");
            jStyledTextPane.setText("Pressed menu item! Save");
        }
    });
我已经有了一个openfile方法,我正在尝试与textpane上显示的文本相同。 这是我的完整代码:

public class CSC9V4TextEditor implements ActionListener {

private JStyledTextPane jStyledTextPane;

private JMenuBar menubar() {

    // Initialising JMenu.
    JMenuBar menubar = new JMenuBar();

    // Creating the Menus.
    JMenu filemenu = new JMenu("File");
    filemenu.add(new JSeparator());

    // Creating the sub Menus.
    JMenuItem fileItem1 = new JMenuItem("Open");
    JMenuItem fileItem2 = new JMenuItem("Save");
    JMenuItem fileItem3 = new JMenuItem("Exit");
    fileItem3.add(new JSeparator());

    // Adding the sub Menus to the File menu.
    filemenu.add(fileItem1);
    filemenu.add(fileItem2);
    filemenu.add(fileItem3);

    // Adding the sub Menus to the Edit menu.
    menubar.add(filemenu);

    // Exit action
    fileItem3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Exit");
            System.exit(0);
        }
    });

    // open file
    fileItem1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            Component parent = null;
            int returnVal = chooser.showOpenDialog(parent);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                System.out.println("You chose to open this file: "
                        + chooser.getSelectedFile().getName());
                File file = chooser.getSelectedFile();
                try {
                    BufferedReader br = null;
                    String sCurrentLine;
                    br = new BufferedReader(new FileReader(file
                            .getAbsoluteFile()));
                    while ((sCurrentLine = br.readLine()) != null) {
                        jStyledTextPane.read(br, null);
                    }
                } catch (IOException e1) {
                    System.out.println("problem accessing file"
                            + file.getAbsolutePath());
                }
            }
            // jStyledTextPane.setText("You chose to open this file: "
            // + chooser.getSelectedFile().getName());
        }
    });

    // Save file
    fileItem2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("Pressed menu item! Save");
            jStyledTextPane.setText("Pressed menu item! Save");
        }
    });

    return menubar;
}

private void initialiseGUI() {

    // Create the frame.
    JFrame frame = new JFrame("CSC9V4 Text Editor");

    // Set the exit button.
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Adding the menu bar to the frame.
    frame.setJMenuBar(menubar());

    // Size the frame.
    frame.setSize(600, 600);

    // Show the frame.
    frame.setVisible(true);

    jStyledTextPane = new JStyledTextPane();

    // Adding the JStyledTextPane to the frame.
    frame.add(jStyledTextPane);
}

@SuppressWarnings("unused")
public static void main(String[] args) {
    CSC9V4TextEditor TextEditor = new CSC9V4TextEditor();
}

public CSC9V4TextEditor() {
    initialiseGUI();
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}

}

要保存
JTextPane
的内容,可以使用正确的序列化方式将
JTextPane
DefaultStyledDocument
序列化到文件中。当您想再次加载内容时,您可以
反序列化该内容,并将其显示在
JTextPane
上。考虑下面给出的代码:

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class SaveEditor extends JFrame implements ActionListener{
     public static final String text = "As told by Wikipedia\n"
    +"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
    + "It is specifically designed to have as few implementation "
    + "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
    + "meaning that code that runs on one platform does not need to be recompiled to run on another. "
    + "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
    + "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
    + "languages in use, particularly for client-server web applications, with a reported 10 million users.";
    JTextPane pane ;
    DefaultStyledDocument doc ;
    StyleContext sc;
    JButton save;
    JButton load;
    public static void main(String[] args) 
    {
        try 
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    SaveEditor se = new SaveEditor();
                    se.createAndShowGUI();
                }
            });
        } catch (Exception evt) {}
    }
    public void createAndShowGUI()
    {
        setTitle("TextPane");
        sc = new StyleContext();
        doc = new DefaultStyledDocument(sc);
        pane = new JTextPane(doc);
        save = new JButton("Save");
        load = new JButton("Load");
        JPanel panel = new JPanel();
        panel.add(save);panel.add(load);
        save.addActionListener(this);load.addActionListener(this);
        final Style heading2Style = sc.addStyle("Heading2", null);
        heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
        heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
        heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
        heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
        try 
        {
            doc.insertString(0, text, null);
            doc.setParagraphAttributes(0, 1, heading2Style, false);
        } catch (Exception e) 
        {
            System.out.println("Exception when constructing document: " + e);
            System.exit(1);
        }
        getContentPane().add(new JScrollPane(pane));
        getContentPane().add(panel,BorderLayout.SOUTH);
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public void actionPerformed(ActionEvent evt)
    {
        if (evt.getSource() == save)
        {
            save();
        }
        else if (evt.getSource() == load)
        {
            load();
        }
    }
    private void save()//Saving the contents .
    {
        JFileChooser chooser = new JFileChooser(".");
        chooser.setDialogTitle("Save");
        int returnVal = chooser.showSaveDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = chooser.getSelectedFile();
            if (file != null)
            {
                FileOutputStream fos = null;
                ObjectOutputStream os = null;
                try
                {
                    fos = new FileOutputStream(file);
                    os = new ObjectOutputStream(fos);
                    os.writeObject(doc);
                    JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
                finally
                {
                    if (fos != null)
                    {
                        try
                        {
                            fos.close();
                        }
                        catch (Exception ex){}

                    }
                    if (os != null)
                    {
                        try
                        {
                            os.close();
                        }
                        catch (Exception ex){}

                    }
                }
            }
            else 
            {
                JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    private void load()//Loading the contents
    {
        JFileChooser chooser = new JFileChooser(".");
        chooser.setDialogTitle("Open");
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = chooser.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION) 
        {
            File file = chooser.getSelectedFile();
            if (file!= null)
            {
                FileInputStream fin = null;
                ObjectInputStream ins = null;
                try
                {
                    fin = new FileInputStream(file);
                    ins = new ObjectInputStream(fin);
                    doc = (DefaultStyledDocument)ins.readObject();
                    pane.setStyledDocument(doc);
                    JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }
                finally
                {
                    if (fin != null)
                    {
                        try
                        {
                            fin.close();
                        }
                        catch (Exception ex){}

                    }
                    if (ins != null)
                    {
                        try
                        {
                            ins.close();
                        }
                        catch (Exception ex){}

                    }
                }
            }
            else 
            {
                JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    }

}

您的意思是“保存”而不是“相同”?您的代码正在读取文件。你的问题是你想写这个文件。1-是的,那是个打字错误。2-我的代码是说打开一个我仍然可以编辑的文本文件,然后我试图让我的JMenu按钮“保存”保存该jframe中所写的内容请发布所有代码。e、 例如,我看不到
jStyledTextPane
的声明,很快您的整个应用程序将由SO用户编写。祝贺