简体   繁体   English

如何从不包含JTextArea的方法追加JTextArea?

[英]How can I append a JTextArea from a method that doesn't contain the JTextArea?

I'm making some test code to practice OOP, and I want to append a JTextArea from the "writeToArea" to the "initialize" method where the JTextArea is defined and initialized. 我正在编写一些测试代码来练习OOP,并且我想将“ writeToArea”中的JTextArea附加到定义和初始化JTextArea的“ initialize”方法中。 I already tried to directly call the "output" variable, but this returns an "output cannot be resolved" error. 我已经尝试直接调用“输出”变量,但这会返回“无法解析输出”错误。 I want so that whenever I call the "writeToArea" method in the main class, I'll be able to add lines to the "output" JTextArea in the "initialize" method. 我希望这样,每当我在主类中调用“ writeToArea”方法时,就可以在“ initialize”方法中向“输出” JTextArea添加行。

Here's the main class: 这是主要的课程:

public class Pangea {

    public static void main(String[] args) {

        UI.initialize();
        UI.writeToArea();
    }
}

Here's the initialize class: 这是初始化类:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class UI {

    static void initialize() {
        System.out.println("Initializing GUI.");
        JFrame frame = new JFrame();
        Font myFont = new Font("Courier", Font.BOLD, 14);
        JTextField input = new JTextField("");
        JTextArea output = new JTextArea("Initiated Succesfully.");
        output.setWrapStyleWord(true);
        output.setLineWrap(true);
        input.setFont(myFont);
        output.setFont(myFont);
        input.setForeground(Color.WHITE);
        output.setForeground(Color.WHITE);
        input.setBackground(Color.BLACK);
        input.setCaretColor(Color.WHITE);
        output.setBackground(Color.BLACK);
        output.setEditable(false);
        JScrollPane jp = new JScrollPane(output);
        frame.setTitle("PANGEA RPG [0.01 ALPHA][WIP]");
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(input, BorderLayout.SOUTH);
        frame.add(jp, BorderLayout.CENTER);
        frame.pack();
        frame.setSize(800, 500);
        frame.setVisible(true);
        System.out.println("GUI Initialized.");
    }

    static void writeToArea() {
        System.out.println("\"writeToArea\" running.");
        output.append("Hello!");
        System.out.println("\"writeToArea\" finished.");
    }
}

I've tried to do something similar to this: Updating jtextarea from another class but it didn't work. 我试图做类似的事情: 从另一个类更新jtextarea,但是没有用。 If anyone has any suggestions I'd be very thankful. 如果有人有任何建议,我将非常感谢。

Read the section from the Swing tutorial on How to Use Text Areas . 阅读Swing教程中有关如何使用文本区域的部分 It will show you how to better structure your code so that you don't use static methods and variables everywhere. 它将向您展示如何更好地构造代码,以免在所有地方都使用静态方法和变量。

Once you have a panel that has a reference to the text area you can add methods that allow you to update the text area on the panel. 一旦有了引用文本区域的面板,就可以添加允许您更新面板上文本区域的方法。

The main error in your code is the lack of OOP design. 代码中的主要错误是缺少OOP设计。 Making all static is poor design. 使所有静态都是糟糕的设计。 Also swing is event based, so you should append text to the textArea when an event happens. 摆动也是基于事件的,因此,当事件发生时,您应该将文本追加到textArea。 See the example i write for you. 请参阅我为您编写的示例。

public class UI {

   private JPanel panel;
   private JTextArea output;

    public UI(){
       initialize();
    }


    private void initialize() {
        panel = new JPanel();
        Font myFont = new Font("Courier", Font.BOLD, 14);
        final JTextField input = new JTextField(""); // must be declared final cause you use it in anonymous class, you can make it instance variable if you want to as textArea

        //add an actionListener then when you press enter this will write to textArea
        input.addActionListener(new ActionListener(){
              @Override             
              public void actionPerformed(ActionEvent evt){
                     writeToArea(input.getText());
              }

        });


        output = new JTextArea("Initiated Succesfully",50,100);// let the component determinate its preferred size.
        output.setWrapStyleWord(true);
        output.setLineWrap(true);
        input.setFont(myFont);
        output.setFont(myFont);
        input.setForeground(Color.WHITE);
        output.setForeground(Color.WHITE);
        input.setBackground(Color.BLACK);
        input.setCaretColor(Color.WHITE);
        output.setBackground(Color.BLACK);
        output.setEditable(false);
        JScrollPane jp = new JScrollPane(output);
        panel.setLayout(new BorderLayout());
        panel.add(input, BorderLayout.SOUTH);
        panel.add(jp, BorderLayout.CENTER);

    }

    private void writeToArea(String something) {
        System.out.println("\"writeToArea\" running.");
        output.append(something);
        System.out.println("\"writeToArea\" finished.");
    }


    public JPanel getPanel(){
        return panel;
    }
}

And in your client code 并在您的客户代码中

    public class Pangea {

        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                   createAndShowGUI();
                }
            });

        }

     /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        System.out.println("Initializing GUI.");
        JFrame frame = new JFrame();
        frame.setTitle("PANGEA RPG [0.01 ALPHA][WIP]");
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add contents to the window.
        frame.add(new UI().getPanel());


        frame.pack();//sizes the frame
        frame.setVisible(true);
        System.out.println("GUI Initialized.");
    }
}

Here you have a tutorial with better examples than this How to Use Text Areas 在这里,您有一个教程,其中包含比本“ 如何使用文本区域”更好的示例。

I remove your setSize and use pack() 我删除您的setSize并使用pack()

The pack method sizes the frame so that all its contents are at or above their preferred sizes. 打包方法调整框架的大小,以便其所有内容均等于或大于其首选大小。 An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). 打包的另一种方法是通过调用setSize或setBounds(也设置帧位置)显式建立帧大小。 In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size. 通常,使用pack优于调用setSize,因为pack让框架布局管理器负责框架大小,并且布局管理器擅长适应平台依赖性和其他影响组件大小的因素。

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

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