简体   繁体   中英

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

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. If anyone has any suggestions I'd be very thankful.

Read the section from the Swing tutorial on How to Use Text Areas . 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. Making all static is poor design. Also swing is event based, so you should append text to the textArea when an event happens. 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()

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

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