Как изменить текст в JTextArea при нажатии кнопки?

Я пытаюсь создать приключенческую игру «Выбери себе», где при нажатии кнопки текст меняется на нужную сцену. Однако в строке 71, когда я пытаюсь установить текст TextArea, он говорит: «Исключение в потоке« AWT-EventQueue-0 »java.lang.Error: нерешенная проблема компиляции: adventureArea не может быть решен». Помогите, пожалуйста?!

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



}

person Benji Cakir    schedule 24.04.2013    source источник


Ответы (1)


Это просто потому, что adventureArea является локальным полем вашего конструктора, а не членом вашего класса.

Вместо этого под объявлением JButton option2; добавьте private final JTextArea adventureArea;

И в вашем конструкторе TheGame вместо JTextArea adventureArea = new JTextArea(); замените его на this.adventureArea = new JTextArea();

Дополнительные примечания:

  • Никогда не используйте setPreferredSize(), вместо этого используйте соответствующий LayoutManager или намекайте на то, чего вы пытаетесь достичь. Например, ваши кнопки могут быть помещены внутри JPanel с GridLayout (чтобы они обе получили одинаковый размер), а затем вы поместите эту панель в SOUTH из BorderLayout. Для JTextArea укажите необходимое количество строк и столбцов (например, 24 строки на 80 столбцов): new JTextArea(24, 80);. Это автоматически распространится на область прокрутки и, в свою очередь, на родительское окно.
  • Постарайтесь сделать правильный отступ в коде, это позволит избежать глупых ошибок и значительно облегчит другим пользователям чтение вашего кода.
  • Не звоните одновременно frame.pack(); и frame.setSize(800, 600);, победит последний. Предпочтите pack() setSize().
  • Все компоненты видны по умолчанию, не нужно вызывать для них setVisible(true). Только контейнер верхнего уровня (Windows) должен быть явно виден.
person Guillaume Polet    schedule 24.04.2013