简体   繁体   English

为什么 JScrollpane 没有添加到我的 TextEditor 中的 JTextArea?

[英]Why is JScrollpane not added to JTextArea in my TextEditor?

I can't understand why the JScrollpane won't be added to JTextArea, is this because of some sort of layout problem?我不明白为什么 JScrollpane 不会被添加到 JTextArea,这是因为某种布局问题吗?

This is a text editor made by my friend, he initially made it with only AWT but I then replaced AWT TextArea with swing's JTextArea to wrap text.这是我朋友制作的文本编辑器,他最初只用 AWT 制作,但后来我用 Swing 的 JTextArea 替换了 AWT TextArea 来包装文本。

Output:输出:在此处输入图片说明

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

//---------------------------------------
class MyFrame extends JFrame { // creating class name is 'Myframe' extending from 'JFrame' class
    MenuBar bar;
    Menu menu1, menu2, format_menu, font_size, theme;
    MenuItem new_item1, item2, item3, item4, item5, item6, item7, item8;
    MenuItem dracula, queen, dawn, light;
    MenuItem size_8, size_12, size_16, size_20, size_24, size_28;

    JTextArea jTextArea;
    String text;

    MyFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Untitled - CodePad");

        // this is for shortcut keys
        MenuShortcut menuShortcut_new_item1 = new MenuShortcut(KeyEvent.VK_N);
        MenuShortcut menuShortcut_item2 = new MenuShortcut(KeyEvent.VK_O);
        MenuShortcut menuShortcut_item3 = new MenuShortcut(KeyEvent.VK_S);
        MenuShortcut menuShortcut_item4 = new MenuShortcut(KeyEvent.VK_X);

        MenuShortcut menuShortcut_item5 = new MenuShortcut(KeyEvent.VK_C);
        MenuShortcut menuShortcut_item6 = new MenuShortcut(KeyEvent.VK_V);
        MenuShortcut menuShortcut_item7 = new MenuShortcut(KeyEvent.VK_T);
        MenuShortcut menuShortcut_item8 = new MenuShortcut(KeyEvent.VK_A);
        // -------------------------------------------
        // setting icon
        Image icon = Toolkit.getDefaultToolkit().getImage(".//res//icon.png");
        setIconImage(icon);

        //

        bar = new MenuBar(); // creating object of menubar and giving it reference

        menu1 = new Menu("File");// creating object of menu as 'File' and giving it reference
        menu2 = new Menu("Edit");// creating object of menu as 'Edit' and giving it reference

        format_menu = new Menu("Format");// creating object of menu as 'Format' and giving it reference
        font_size = new Menu("Font Size");// creating object of menu as 'Font Size' and giving it reference
        theme = new Menu("Theme");// creating object of menu as 'Theme' and giving it reference

        //// creating object of MenuItem and giving it reference,and Passing arguments
        //// 'label','menushortcut'
        new_item1 = new MenuItem("New", menuShortcut_new_item1);
        item2 = new MenuItem("Open", menuShortcut_item2);
        item3 = new MenuItem("Save", menuShortcut_item3);
        item4 = new MenuItem("Exit", menuShortcut_item4);

        item5 = new MenuItem("Copy", menuShortcut_item5);
        item6 = new MenuItem("Paste", menuShortcut_item6);
        item7 = new MenuItem("Cut", menuShortcut_item7);
        item8 = new MenuItem("Select All", menuShortcut_item8);

        // ------------------done--------------

        // creating menuItem for font size menu
        size_8 = new MenuItem("8");
        size_12 = new MenuItem("12");
        size_16 = new MenuItem("16");
        size_20 = new MenuItem("20");
        size_24 = new MenuItem("24");
        size_28 = new MenuItem("28");
        // -------------------done-------------------
        // creating menuItem for theme menu
        dracula = new MenuItem("Dracula");
        queen = new MenuItem("Queen");
        dawn = new MenuItem("Dawn");
        light = new MenuItem("Light");

        // creating menuItem for theme menu

        // adding new_item1,2,3,4 to menu1 ,that is new,open,save,exit
        menu1.add(new_item1);
        menu1.add(item2);
        menu1.add(item3);
        menu1.add(item4);

        // ------------------Done-------------------

        // adding item5,6,7,8 to menu2 ,that is copy,paste,cut,and select all
        menu2.add(item5);
        menu2.add(item6);
        menu2.add(item7);
        menu2.add(item8);
        // -------done---------------------------------------------------------

        format_menu.add(font_size);// adding font_size menu to format menu so it becomes submenu

        // adding MenuItems to font_size menu
        font_size.add(size_8);
        font_size.add(size_12);
        font_size.add(size_16);
        font_size.add(size_20);
        font_size.add(size_24);
        font_size.add(size_28);
        // ---------done------------------------

        // adding MenuItem to theme Menu-------
        theme.add(dracula);
        theme.add(queen);
        theme.add(dawn);
        theme.add(light);
        // ---------done------------------------

        jTextArea = new JTextArea();// adding jTextArea
        jTextArea.setLineWrap(true);
        JScrollPane scroll = new JScrollPane(jTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        add(scroll);

        // adding menus to bar
        bar.add(menu1);
        bar.add(menu2);
        bar.add(format_menu);
        bar.add(theme);

        setMenuBar(bar); // settingmenubar as bar
        add(jTextArea);// adding text area

        // declaring some colors using rgb

        Color dracula_Color = new Color(39, 40, 34);
        Color green_Color = new Color(166, 226, 41);
        Color orange_Color = new Color(219, 84, 34);
        Color queen_Color = new Color(174, 129, 219);

        // setting default foreground color of jTextArea and setting font
        jTextArea.setForeground(Color.BLUE);
        jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));

        // setting size and location and visibility
        setSize(1000, 600);
        setLocationRelativeTo(null);
        setVisible(true);

        item2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                FileDialog dialog = new FileDialog(new Frame(), "Open", FileDialog.LOAD); // this will load the
                                                                                          // fileDialog
                dialog.setVisible(true);// this will make dialog visible
                String path = dialog.getDirectory() + dialog.getFile(); // this will select the path of selected file
                                                                        // and put it into 'path'
                setTitle(dialog.getFile() + " - CodePad");// this will set Title to selected file name and -CodePad

                try {
                    FileInputStream fi = new FileInputStream(path);
                    byte b[] = new byte[fi.available()];
                    fi.read(b);
                    String str = new String(b); // this will store b in str
                    jTextArea.setText(str);// this will display text in 'str' in jTextArea
                    fi.close();// this will close fi

                } catch (Exception e) {

                    System.out.println("Something went Wrong :(");
                }
            }
        });

        new_item1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                setTitle("Untitled - CodePad");
                jTextArea.setText(" ");
            }
        });

        item3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                FileDialog dialog = new FileDialog(new Frame(), "Save ", FileDialog.SAVE);
                dialog.setVisible(true);
                String path = dialog.getDirectory() + dialog.getFile();
                setTitle(dialog.getFile() + "- CodePad");

                try {

                    FileWriter fw = new FileWriter(path);
                    fw.write(jTextArea.getText());
                    fw.close();

                } catch (Exception e) {

                    System.out.println("Something went Wrong :(");
                }
            }
        });
        item4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // setVisible(false);//this will make frame invisible
                System.exit(0);
            }
        });

        item5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                text = jTextArea.getSelectedText();// this will store selected text in to variable 'text'
            }
        });

        item6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.insert(text, jTextArea.getCaretPosition()); // this will insert the text present in 'text'
                                                                      // variable at the carret position
            }
        });

        item7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                text = jTextArea.getSelectedText(); // this will copy the selected text
                jTextArea.replaceRange("", jTextArea.getSelectionStart(), jTextArea.getSelectionEnd()); // this will put
                                                                                                        // ""
                                                                                                        // to selected
                                                                                                        // text
            }
        });

        item8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.selectAll(); // this will select all the text in jTextArea
            }
        });

        // ------------------------------------------------------------------------

        // --------------------------------------------------------------------------

        size_8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 8)); // this will change the size of text in
                                                                            // jTextArea to 8
            }
        });
        size_12.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 12));// this will change the size of text in
                                                                            // jTextArea to 12
            }
        });
        size_16.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 16));// this will change the size of text in
                                                                            // jTextArea to 16
            }
        });
        size_20.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));// this will change the size of text in
                                                                            // jTextArea to 20
            }
        });
        size_24.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 24));// this will change the size of text in
                                                                            // jTextArea to 24
            }
        });
        size_28.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 28));// this will change the size of text in
                                                                            // jTextArea to 28
            }
        });

        // --------------------------------------------------------------------------
        dracula.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {

                jTextArea.setBackground(dracula_Color);// this will backgound to dracula
                jTextArea.setForeground(green_Color);// this will set foregrounf to green
            }
        });
        queen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {

                jTextArea.setBackground(dracula_Color);
                jTextArea.setForeground(queen_Color);
            }
        });
        dawn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setBackground(Color.WHITE);
                jTextArea.setForeground(orange_Color);
            }
        });
        light.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                jTextArea.setBackground(Color.WHITE);
                jTextArea.setForeground(Color.BLUE);
            }
        });
        // --------------------------------------------------------------------------
    }

}

// ---------------------------------------

public class CodePad_updated {
    public static void main(String[] args) {
        new MyFrame();// object
    }
}

Are you new to Swing?你是 Swing 的新手吗? I dont see you setting a contentpane.我没有看到您设置内容窗格。 I also do not see you use the @Override command in your actionListeners.我也没有看到您在 actionListeners 中使用 @Override 命令。

Just as a few things I find suspicious.就像我觉得可疑的几件事一样。 I normally create a new JFrame instead of extending it.我通常创建一个新的 JFrame 而不是扩展它。 And I consider extending JFrame a bad practice.我认为扩展 JFrame 是一种不好的做法。 But that is no universal opinion.但这并不是普遍的看法。 Then you would add a panel to the frame and set it as contentPane.然后,您将向框架添加一个面板并将其设置为 contentPane。 And then you can start adding everything to your panel, including other panels to help with UI Layout.然后您可以开始将所有内容添加到您的面板中,包括其他面板以帮助进行 UI 布局。 Does the Textfield even show?文本字段甚至显示吗? Because I suspect it does not.因为我怀疑它没有。 Also you need to add the ScrollPane to your contentPane, not your Frame.您还需要将 ScrollPane 添加到您的 contentPane,而不是您的 Frame。 I suggest to delete everything from your code in the post that is not relevant to your question, ie everything not related to the topic at hand.我建议删除帖子中与您的问题无关的代码中的所有内容,即与手头主题无关的所有内容。

Edit: have you tried adding the textArea to the Scrollpane?编辑:您是否尝试将 textArea 添加到 Scrollpane? it would look something like this.它看起来像这样。

JTextArea text = new JTextArea();
JScrollPane newScroll = new JScrollPane(text);

Does that help you?这对你有帮助吗?

Summarizing the points made here and elaborating:总结这里提出的观点并详细说明:

  • As shown here , the default content pane will have a BorderLayout , and the default constraint is BoderLayout.CENTER ;如图所示这里,默认的内容窗格中会产生BorderLayout ,默认约束BoderLayout.CENTER ; only one component may occupy the position.只有一个组件可以占据该位置。

  • Give your JTextArea an initial preferred size and pack() the frame;给你的JTextArea一个初始的首选大小和pack()框架; type some text or resize the fame to see the scrollbars appear as needed.键入一些文本或调整声望大小以查看滚动条是否根据需要出现。

  • As shown here for Swing, use javax.swing.JMenuBar , JMenu , JMenuItem , etc.如图所示这里的摇摆,用javax.swing.JMenuBarJMenuJMenuItem ,等等。

  • Construct and manipulate Swing GUI objects only on the event dispatch thread .事件分派线程上构造和操作 Swing GUI 对象。

图片

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class CodePad {

    public static void main(String[] args) {
        EventQueue.invokeLater(new CodeEditor()::create);
    }

    private static final class CodeEditor {

        JMenuBar bar = new JMenuBar();
        JMenu file = new JMenu("File");
        JMenu edit = new JMenu("Edit");
        JTextArea textArea = new JTextArea("Some text…", 8, 36);

        public void create() {
            JFrame f = new JFrame("CodePad");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            bar.add(file);
            bar.add(edit);
            f.setJMenuBar(bar);

            textArea.setForeground(Color.BLUE);
            textArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 16));
            textArea.setLineWrap(true);
            JScrollPane scrollArea = new JScrollPane(textArea);
            f.add(scrollArea); // default BoderLayout.CENTER

            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    }
}

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

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