简体   繁体   中英

How do I change the text in a JTextArea when I press a button?

I'm trying to make a Choose Your Own Adventure Game, where when I press a button, the text changes to the right scene. However, on Line 71, when I try to set the text of the TextArea, it says "Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: adventureArea cannot be resolved". Help, Please?!

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.Border;

public class TheGame extends JPanel implements ActionListener{

/**
 * @param args
 */
private int numClicks1 = 0;
private int numClicks2 = 0;
String gameText = "You wake up in the morning feeling like a sir. As is tradition, you need electronics of any kind to keep your mind running (going outside is out of the question. Nothing exciting in the real world). There are many options available to you, but the internet and games are the ones that appeal the most. Do you want to surf the web or use an app?";

private static final long serialVersionUID = 1L;
 JButton option1;
 JButton option2;

    public TheGame(){
        JPanel buttonPane = new JPanel(new BorderLayout(1,1));
        JPanel textPane = new JPanel(new BorderLayout(1,1));

        option1 = new JButton("Click here for teh interwebs");
         option1.addActionListener(this);
        option1.setPreferredSize(new Dimension(300, 50));
         option1.setVisible(true);

        option2 = new JButton("Click here for teh entertainments");
        option2.addActionListener(this);
         option2.setPreferredSize(new Dimension(300, 50));
         option2.setVisible(true);


        JTextArea adventureArea = new JTextArea();
        adventureArea.setFont(new Font("Serif", Font.PLAIN, 16));
        adventureArea.setLineWrap(true);
        adventureArea.setWrapStyleWord(true);
        adventureArea.setEditable(true);
        adventureArea.setText(gameText);

        JScrollPane adventureScroll = new JScrollPane(adventureArea);
        adventureScroll.setPreferredSize(new Dimension(350, 350));
        adventureScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        Border adventureSpace = BorderFactory.createEmptyBorder(0,10,10,10);
        Border adventureBorder = BorderFactory.createTitledBorder(adventureSpace, "TECHNOLOGY!!!");
        adventureScroll.setBorder(adventureBorder);
        adventureScroll.setVisible(true);


        textPane.add(adventureScroll, BorderLayout.CENTER);
        buttonPane.add(option1,BorderLayout.NORTH);
        buttonPane.add(option2,BorderLayout.SOUTH);


        add(buttonPane, BorderLayout.SOUTH);
        add(textPane, BorderLayout.CENTER);

        setVisible(true);
        buttonPane.setVisible(true);
        textPane.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==option1){
            //numClicks1++;
            //gameText="The internet: A wondrous place full of knowledge, videos, stories, memes, and everything else. Like every place, it has a dark and a light side. Where go?";
            adventureArea.append("The internet: A wondrous place full of knowledge, videos, stories, memes, and everything else. Like every place, it has a dark and a light side. Where go?");
        }else if (e.getSource()==option2){
        numClicks2++;
        };

      /* if(numClicks1==1){
           gameText="The internet: A wondrous place full of knowledge, videos, stories, memes, and everything else. Like every place, it has a dark and a light side. Where go?";
       }else if (numClicks2==1){

       };*/
    }


    private static void createAndShowGUI() {

        JFrame frame = new JFrame("The Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TheGame theContentPane = new TheGame();
        theContentPane.setOpaque(true); 
        frame.setContentPane(theContentPane);

        JFrame.setDefaultLookAndFeelDecorated(true);

        frame.pack();
        frame.setSize(800, 600);
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }



}

This is simply because adventureArea is a local field of your constructor and not a member of your class.

Instead, below the declaration of JButton option2; add private final JTextArea adventureArea;

And in your constructor of TheGame , instead of JTextArea adventureArea = new JTextArea(); replace that with this.adventureArea = new JTextArea();

Side-notes:

  • Never use setPreferredSize() , instead use an appropriate LayoutManager or provide hints of what you are trying to achieve. For example, your buttons could be placed inside a JPanel with a GridLayout (so that they both get the same size) and then you put that panel at the SOUTH of the BorderLayout . For the JTextArea , indicate the number of rows and columns you want (24 rows by 80 columns, for example): new JTextArea(24, 80); . This will automatically propagate to the scrollpane and in turn to the parent window.
  • Try to indent your code properly, it avoids silly mistakes and makes it a lot easier for others to read your code.
  • Don't call both frame.pack(); and frame.setSize(800, 600); , the last one will win. Favor pack() over setSize() .
  • All components are visible by default, no need to call setVisible(true) on them. Only top-level container (Windows) needs to be made visible explicitly.

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