简体   繁体   中英

Simple Java editor GUI

Hello i create the GUI code for simple Java editor

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{ }.

Open: opens files with source code 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). The main part of the window will have the editor to be used by the user to edit a file source Java.

The main part of the window will have the editor to be used by the user to edit a file source Java. information which will be renewed during the processing of a snippet: Number lines Number reserved words in java source code

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. The comments will appear in green The String Literals with orange All other with black The Font will be Courier Font size 12pt

i will provide the GUI code can anyone help me with the above ?

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. 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.

  • Creating a file: File has the method createNewFile() , use it in combination with exists() .
  • To open and read a file use a try-with-resource (There's actually a nice tutorial about it in the Java Manuals).
  • To save a file you should check out the FileWriter , it can write strings or append them to files.
  • For your editor you might want to replace the before mentioned BufferedReader with a LineReader , which also provides methods to get the line number. 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.
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

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.

Could someone write to me the correct code for that? be in mind i am very java beginner.

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);           

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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