简体   繁体   English

简单的Java编辑器GUI

[英]Simple Java editor GUI

Hello i create the GUI code for simple Java editor 您好,我为简单的Java编辑器创建了GUI代码

i create the menu but i need to match File: New: Create a new file. 我创建菜单,但是我需要匹配文件:新建:创建一个新文件。 asking for the name of the file (and therefore the public class) and the directory in which it will be stored. 询问文件的名称(以及公共类),以及文件的存储目录。 With the creation of the file is inserted into the structure of the public class, for example public class MyClass{ }. 随着文件的创建,将插入到公共类的结构中,例如,公共类MyClass {}。

Open: opens files with source code java ( .java). 打开:使用源代码Java(.java)打开文件。 Save : saves the current snippet on the same file with this established during the creation of. 保存:将当前代码段与创建过程中建立的代码段保存在同一文件中。 Save as : displays the dialog box where you requested the name of the file, the format of the directory in which it will be stored. 另存为:显示一个对话框,您在其中请求文件名,文件的存储目录格式。 The format will be java file ( .java). 格式为Java文件(.java)。 The main part of the window will have the editor to be used by the user to edit a file source Java. 窗口的主要部分将具有供用户用来编辑文件源Java的编辑器。

The main part of the window will have the editor to be used by the user to edit a file source Java. 窗口的主要部分将具有供用户用来编辑文件源Java的编辑器。 information which will be renewed during the processing of a snippet: Number lines Number reserved words in java source code 在代码段处理过程中将更新的信息:数字行Java源代码中的保留字数

Formatting Text 格式化文字


Each file will open formatted and will formatted when processed in the following rules: The reserved words of java will appear with color blue. 每个文件都将打开格式,并按照以下规则进行处理时将进行格式化:java的保留字将显示为蓝色。 The comments will appear in green The String Literals with orange All other with black The Font will be Courier Font size 12pt 注释将显示为绿色The String Literals with orange其他所有黑色的字体将为Courier字体大小12pt

i will provide the GUI code can anyone help me with the above ? 我将提供GUI代码,任何人都可以通过上述帮助我吗?

Regards Antonis 问候安东尼

// ClassEEFrame

package editor.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
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.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class EEFrame extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = -1709009137090877913L;
    private GridBagLayout layout;
    private GridBagConstraints constraints;
    private EEMenuBar menuBar;
    private EETextPane editor;
    private EEConsole console;
    private EEStatusBar statusBar;
    private File file;

    public EEFrame() throws HeadlessException {
        super("Elearn Editor");

        JScrollPane scrollPane;

        layout = new GridBagLayout();
        setLayout(layout);

        constraints = new GridBagConstraints();

        menuBar = new EEMenuBar();
        setJMenuBar(menuBar);

        editor = new EETextPane();

        scrollPane = new JScrollPane(editor);
        scrollPane.setBorder(new TitledBorder("Editor"));

        setConstraints(1, 100, GridBagConstraints.BOTH);
        addComponent(scrollPane, 0, 0, 1, 1);

        console = new EEConsole();

        scrollPane = new JScrollPane(console);
        scrollPane.setBorder(new TitledBorder("Console"));

        setConstraints(1, 40, GridBagConstraints.BOTH);
        addComponent(scrollPane, 1 ,0 ,1, 1);

        statusBar = new EEStatusBar();
        setConstraints(1, 0, GridBagConstraints.BOTH);
        addComponent(statusBar, 2, 0, 1, 1);

        file = null;
    }

    public JTextPane getTextPane() {
        return this.editor;
    }

    public void setLines(int lines) {
        this.statusBar.setLines(lines);
    }

    public void setWords(int words) {
        this.statusBar.setJavaWords(words);
    }

    private void setConstraints(int weightx, int weighty, int fill) {
        constraints.weightx = weightx;
        constraints.weighty = weighty;
        constraints.fill = fill;
    }

    private void addComponent(Component component, int row, int column, int width, int height) {
        constraints.gridx = column;
        constraints.gridy = row;
        constraints.gridwidth = width;
        constraints.gridheight = height;
        layout.setConstraints(component, constraints);
        add(component);
    }

    private class EEMenuBar extends JMenuBar {

        /**
         * 
         */
        private static final long serialVersionUID = -2176624051362992835L;
        private JMenu fileMenu, compilationMenu;
        private JMenuItem newItem, openItem, saveItem, saveAsItem, exportItem, compileProcessItem, compileClassItem;

        public EEMenuBar() {
            super();

            fileMenu = new JMenu("File");

            newItem = new JMenuItem("New");

            newItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    /* TODO Dispay dialog with inputs class name and file path */
                }

            });

            fileMenu.add(newItem);

            openItem = new JMenuItem("Open");

            openItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    /*TODO Open existing java source file*/

                }

            });

            fileMenu.add(openItem);

            saveItem = new JMenuItem("Save");
            saveItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    /*TODO save changes to file*/                                       
                }

            });

            fileMenu.add(saveItem);

            saveAsItem = new JMenuItem("Save As");

            saveAsItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    /*TODO Save as new java source file*/
                }               
            });

            fileMenu.add(saveAsItem);

            exportItem = new JMenuItem("Export to pdf");

            exportItem.addActionListener(new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    // TODO save as pdf(formatted)

                }
            });

            fileMenu.add(exportItem);           

            add(fileMenu);

            compilationMenu = new JMenu("Compilation");

            compileProcessItem = new JMenuItem("Compile with system jdk");

            compileProcessItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    /*TODO Compile java source code and show results in teminal(inside editor)*/
                }

            });

            compilationMenu.add(compileProcessItem);

            compileClassItem = new JMenuItem("Compile with JavaCompiler Class");

            compileClassItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    /*TODO Call system compiler for file*/
                }
            });

            compilationMenu.add(compileClassItem);

            add(compilationMenu);

        }
    }

    private class EETextPane extends JTextPane {

        /**
         * 
         */
        private static final long serialVersionUID = -7437561302249475096L;

        public EETextPane() {
            super();

            //add styles to document
            Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
            StyleConstants.setForeground(def, Color.BLACK);
            StyleConstants.setFontFamily(def, "Courier");
            StyleConstants.setFontSize(def, 12);

            Style keyword = addStyle("keyword", def);
            StyleConstants.setForeground(keyword, Color.BLUE);

            Style literal = addStyle("literal", def);
            StyleConstants.setForeground(literal, Color.ORANGE);

            Style comment = addStyle("comment", def);
            StyleConstants.setForeground(comment, Color.GREEN);
        }
    }

    private class EEConsole extends JTextPane {

        /**
         * 
         */
        private static final long serialVersionUID = -5968199559991291905L;

        public EEConsole() {
            super();

            //add styles to document
            Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE );
            StyleConstants.setForeground(def, Color.BLACK);
            StyleConstants.setFontFamily(def, "Courier");
            StyleConstants.setFontSize(def, 12);

            Style keyword = addStyle("error", def);
            StyleConstants.setForeground(keyword, Color.RED);

            Style literal = addStyle("success", def);
            StyleConstants.setForeground(literal, Color.GREEN);
        }

    }

    private class EEStatusBar extends JPanel {

        /**
         * 
         */
        private static final long serialVersionUID = 185007911993347696L;
        private BoxLayout layout;
        private JLabel linesLabel, lines, wordsLabel, words;

        public EEStatusBar() {
            super();

            layout = new BoxLayout(this, BoxLayout.X_AXIS);
            setLayout(layout);

            linesLabel = new JLabel("Lines : ");
            linesLabel.setAlignmentX(LEFT_ALIGNMENT);
            add(linesLabel);

            lines = new JLabel("");
            lines.setAlignmentX(LEFT_ALIGNMENT);
            add(lines);

            add(Box.createRigidArea(new Dimension(10,10)));

            wordsLabel = new JLabel("Java Words : ");
            wordsLabel.setAlignmentX(LEFT_ALIGNMENT);
            add(wordsLabel);

            words = new JLabel("");
            words.setAlignmentX(LEFT_ALIGNMENT);
            add(words);
        }

        public void setLines(int lines) {
            /*TODO set line numbers */
        }

        public void setJavaWords(int words) {
            /*TODO set java keyword numbers*/
        }
    }

} }


//class Main 

package editor.app;

import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import elearning.editor.gui.EEFrame;
import elearning.editor.util.EECodeFormater;
import elearning.editor.util.EEJavaWordCounter;
import elearning.editor.util.EELineCounter;

public class EEditor {

    /**
     * @param args
     */
    public static void main(String[] args) {

        try {
            // Set cross-platform Java L&F (also called "Metal")
            //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

            //Set Motif L&F
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

            //Set Nimbus L&F
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

            //Set System L&F
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

            //Set GTK L&F --> Same as System L&F on Linux and Solaris\
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");

            //Set Windows L&F --> Same as System L&F on Windows
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } 
        catch (UnsupportedLookAndFeelException e) {
            // handle exception
        }
        catch (ClassNotFoundException e) {
            // handle exception
        }
        catch (InstantiationException e) {
            // handle exception
        }
        catch (IllegalAccessException e) {
            // handle exception
        }

        EEFrame frame = new EEFrame();

        frame.setSize(500, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);


        /* TODO Instatiate Threads */


        /*TODO Start Threads */

    }

}

Also i provide a mockup of it: 我也提供一个样机:

Mockup 小样

First you should have a look at the File class. 首先,您应该看一下File类。 It provides you methods to create, open, modify and save files. 它为您提供创建,打开,修改和保存文件的方法。 To read files you also might want to give BufferedReader or any other Reader a shot. 要读取文件,您可能还想给BufferedReader或任何其他Reader拍照。

  • Creating a file: File has the method createNewFile() , use it in combination with exists() . 创建文件: File有方法createNewFile()结合使用它exists()
  • To open and read a file use a try-with-resource (There's actually a nice tutorial about it in the Java Manuals). 要打开和读取文件,请使用try-with-resource(Java手册中实际上有一个不错的教程 )。
  • To save a file you should check out the FileWriter , it can write strings or append them to files. 要保存文件,您应该检出FileWriter ,它可以编写字符串或将它们附加到文件中。
  • For your editor you might want to replace the before mentioned BufferedReader with a LineReader , which also provides methods to get the line number. 对于您的编辑器,您可能想用LineReader替换前面提到的BufferedReader ,该方法还提供了获取行号的方法。 Other than that you have to figure out yourself how to number the lines. 除此之外,您还必须弄清楚如何对行进行编号。 (Actually it's just googling around a lot, there will be some ideas like this one - which I didn't check in detail but it might help). (其实这只是谷歌搜索周围很多,会有一些想法像这一个 -我没有详细检查,但它可能会帮助)。
  • Of course for the editor you should first read the file into a string, use a formatter for it and then you can present it and reformat it when needed. 当然,对于编辑器,您应该首先将文件读取为字符串,使用格式化程序,然后可以显示它并在需要时重新格式化。

Apart from these hints I can not provide you with more detailed answers, as you can also read in the comments it would be easier if you would provide more detailed questions. 除了这些提示之外,我无法为您提供更详细的答案,因为您还可以阅读评论,所以如果您提供更详细的问题会更容易。 You now just gave us a GUI which has almost nothing to do with your actual problems. 您现在只给了我们一个GUI,它几乎与您的实际问题无关。
Show us some of your (problematic) work and we can help you, but otherwise we can not do much more than giving you some hints as I just did. 向我们展示您的一些(有问题的)工作,我们可以为您提供帮助,但是除此之外,我们只能做一些提示,就像我刚才所做的那样。 So try to think about your problems, try how to ask for more precise answers and open some new questions if you want. 因此,请尝试考虑您的问题,尝试如何寻求更精确的答案,并在需要时提出一些新问题。
But don't forget to check out the site for answers, for me almost all of my questions I'd like to ask are already asked somewhere in a similar manner. 但是不要忘了在网站上找到答案,对我来说,我想问的几乎所有问题都已经以类似的方式被问到了某个地方。

Hello again lets split work into steps , 再次问好,我们将工作分为几步,

firstly i would like to create the new,open,save ,save as , export into pdf menu and event 首先,我想创建新的,打开,保存,另存为,导出到PDF菜单和事件

below is the code that i used ,the GUI frame open correctly with new ,open,save, save as ,export into pdf labels but as action nothing happened. 下面是我使用的代码,GUI框架可以正确打开,包括新的,打开,保存,另存为,导出为pdf标签,但操作没有任何反应。

Could someone write to me the correct code for that? 有人可以给我写正确的代码吗? be in mind i am very java beginner. 请记住,我非常java初学者。

public EEMenuBar() {
        super();

        fileMenu = new JMenu("File");
        //Create the New menu item
        newItem = new JMenuItem("New");
        newItem.setMnemonic(KeyEvent.VK_N);
        newItem.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {

            }

        });

        fileMenu.add(newItem);

        openItem = new JMenuItem("Open");
        openItem.setMnemonic(KeyEvent.VK_0);
        openItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                /*TODO Open existing java source file*/

            }

        });

        fileMenu.add(openItem);

        saveItem = new JMenuItem("Save");
        saveItem.setMnemonic(KeyEvent.VK_S);
        saveItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                /*TODO save changes to file*/                                       
            }

        });

        fileMenu.add(saveItem);

        saveAsItem = new JMenuItem("Save As");
        saveAsItem.setMnemonic(KeyEvent.VK_A);
        saveAsItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                /*TODO Save as new java source file*/
            }               
        });

        fileMenu.add(saveAsItem);

        exportItem = new JMenuItem("Export to pdf");
        exportItem.setMnemonic(KeyEvent.VK_E);
        exportItem.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO save as pdf(formatted)

            }
        });

        fileMenu.add(exportItem);           

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM