簡體   English   中英

為什么append函數在ActionListener中不起作用?

[英]why the append function doesn't work within ActionListener?

在JFileChooser中選擇文件后,我希望JTextField附加到它的路徑。 我寫了以下代碼:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.*;

public class Program extends JFrame{


    public static void main(String[] args){

        new Program();

    }

    public Program(){

        this.setSize(500,500);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setTitle("Projekt Java");

        JPanel thePanel = new JPanel();

        thePanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        JButton button1 = new JButton("Wybierz plik:");
        JButton button2 = new JButton("Dodaj");
        JTextField text = new JTextField(23);
        JTextArea textArea1 = new JTextArea(10,30);

        thePanel.add(button1);
        thePanel.add(text);
        thePanel.add(button2);
        thePanel.add(textArea1);
        this.add(thePanel);

        button1.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                JFileChooser fileChooser = new JFileChooser();
                int returnValue = fileChooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                  File selectedFile = fileChooser.getSelectedFile();
                  System.out.println(selectedFile.getName());
                  String directory = fileChooser.getCurrentDirectory().toString();

                  text.append(directory); // doesn't work
                }
              }
            });

        this.setVisible(true);

    }

    private static void createFileChooser(final JFrame frame) {

        String filename = File.separator+"tmp";
        JFileChooser fileChooser = new JFileChooser(new File(filename));

        // pop up an "Open File" file chooser dialog
        fileChooser.showOpenDialog(frame);

        System.out.println("File to open: " + fileChooser.getSelectedFile());

        // pop up an "Save File" file chooser dialog
        fileChooser.showSaveDialog(frame);

        System.out.println("File to save: " + fileChooser.getSelectedFile());

    }       
}

但是,追加功能在這里不起作用。 有人可以解釋為什么會這樣嗎? 它可以工作,除非它不在動作監聽器中。 我的錯誤是:

無法引用在不同方法中定義的內部類中的非final變量文本對於JTextField類型,未定義方法append(String)

我改成了text.append(目錄); text.setText(目錄); 並將JTextfield修改為最終版並且有效。

使用text.setText(directory)而不是text.append(directory) append()方法適用於JTextAreaJTextField沒有它。

並且您必須將JTextField text聲明為final JTextField text

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM