【问题标题】:JTextArea apparently contains no text, even when it does?JTextArea 显然不包含文本,即使它包含?
【发布时间】:2014-06-01 05:09:26
【问题描述】:

我正在创建一个简单的 java swing 应用程序,它实现了 JTextArea 的使用(它是一个简单的文本编辑类型程序)。但是,我在尝试将 textArea 的内容写入文本文件时遇到了问题。我使用以下代码来完成此操作:

    FileWriter writer = new FileWriter(targetPath);
    this.textArea.write(writer);

我已经通过使用以下方法测试相同的 FileWriter 对象消除了文件路径不正确的可能性:

   writer.write("String");

这完美地完成了它的任务。我还尝试使用 getText() 方法将 textArea 的内容打印到控制台,即使 textArea 包含文本,这也会在控制台上创建一个空白行。我输入的这个文本的一个例子是:“Hello World”。变量初始化和设置如下:

   JTextArea textArea = new JTextArea();

这个问题是不是调用方法引起的:

   textArea.setEditable(false);
   textArea.setFocusable(false);

因为这是我对文本区域设置所做的唯一修改(除了颜色修改)。我觉得我正在寻找一个简单的问题。这个项目的完整课程可以在下面找到。我不相信我忽略了任何细节,感谢您的宝贵时间。

 public class Window extends JFrame {

//TODO refine the file operations

private static final long serialVersionUID = 1L;
private javax.swing.JButton openButton;
private javax.swing.JButton saveButton;
private javax.swing.JButton addTeamButton;
private javax.swing.JButton enterButton;
private javax.swing.JButton refreshButton;
private javax.swing.JComboBox<String> dropDown;
private javax.swing.JLabel label;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea textArea;
private javax.swing.JToggleButton toggleButton;
private Color darkerBlue = new Color(20,20,130);
private Color lighterBlue = new Color(0,0,190);
private Color textColor = new Color(255,200,0);
private URL iconURL = getClass().getResource("/icon.png");
private ImageIcon image = new ImageIcon(iconURL);
public String folderPath = "";
public boolean changesSaved = false;
String currentTeamNumber = "3120";


//private boolean readOnly = false;

    public Window() {
        //Set the numbus look/feel 
        super("NDHS RoboKnights Scouting");
        try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(this.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(this.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(this.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(this.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
        //int numberOfTeams = Integer.parseInt(JOptionPane.showInputDialog(this,"How many teams are present?"));
        Main.teams.add("3120");


        initComponents();
        draw();
        setHandlers();
    }

    private void initComponents() {

        openButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        addTeamButton = new javax.swing.JButton();
        enterButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        label = new javax.swing.JLabel();
        dropDown = new javax.swing.JComboBox<String>();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new JTextArea();
        toggleButton = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        openButton.setText("openButton");

        saveButton.setText("saveButton");

        addTeamButton.setText("addTeamButton");

        enterButton.setText("enterButton");

        refreshButton.setText("refreshButton");

        label.setText("label");

        updateComboBox();

        textArea.setColumns(20);
        textArea.setLineWrap(true);
        textArea.setRows(5);
        textArea.setWrapStyleWord(true);
        jScrollPane1.setViewportView(textArea);

        toggleButton.setText("toggleButton");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(label)
                        .addGap(18, 18, 18)
                        .addComponent(dropDown, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(openButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(addTeamButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(enterButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(toggleButton, javax.swing.GroupLayout.DEFAULT_SIZE, 133, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(openButton)
                    .addComponent(saveButton)
                    .addComponent(addTeamButton)
                    .addComponent(enterButton)
                    .addComponent(refreshButton)
                    .addComponent(toggleButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dropDown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(label))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
                .addContainerGap())
        );


    }                     

    private void draw(){
        this.setIconImage(image.getImage());

        this.refreshButton.setVisible(false);

        this.openButton.setText("Open");
        this.saveButton.setText("Save");
        this.addTeamButton.setText("Add team");
        this.refreshButton.setText("Refresh");
        this.enterButton.setText("Enter");
        this.label.setText("Team:");
        this.toggleButton.setText("Read-Only");


        this.label.setForeground(textColor);

        this.getContentPane().setBackground(lighterBlue);
        this.toggleButton.setBackground(textColor);
        this.toggleButton.setForeground(darkerBlue);

        this.dropDown.setBackground(lighterBlue);       

        this.enterButton.setBackground(darkerBlue);
        this.enterButton.setForeground(textColor);

        this.refreshButton.setBackground(darkerBlue);
        this.refreshButton.setForeground(textColor);

        this.openButton.setBackground(lighterBlue);
        this.openButton.setBackground(textColor);

        this.saveButton.setBackground(darkerBlue);
        this.saveButton.setForeground(textColor);

        this.textArea.setBackground(darkerBlue);
        this.textArea.setForeground(textColor);

        this.addTeamButton.setBackground(lighterBlue);
        this.addTeamButton.setForeground(textColor);

        this.pack();
        this.setVisible(true);
    }

    private void setHandlers(){
        this.refreshButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                update();
            }
        });

        this.addTeamButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent e) {
                    addTeam();
                }   
            });
        this.toggleButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                updateToggle();
            }


        });
        this.openButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {
                folderPath = getFolder();
                System.out.println(folderPath);
                String temp[]= getAllTeamNames();
                Main.teams.clear();
                for(int i = 0; i<temp.length; i++){
                    Main.teams.add(temp[i]);
                }
                update();
            }

        });
        this.saveButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e) {

                try{
                    saveFile();
                }catch(Exception ew){
                    System.out.println("Could not save file");
                }
            }

        });
    }

    protected String getFolder() {
        JFileChooser chooser = new JFileChooser();

            int retrival = chooser.showOpenDialog(this);
            if(retrival == JFileChooser.APPROVE_OPTION){
                //chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                File filePath = chooser.getCurrentDirectory();
                this.openButton.setEnabled(false);
                return filePath.getAbsolutePath();
            }
            else{
                JOptionPane.showMessageDialog(this, "You must select a folder to begin");
                return"";
            }

    }

    public void update(){
        updateToggle();
        updateComboBox();
        System.out.println("Update");
        initComponents();
        draw();

    }

    private void addTeam(){
        for(;;){
            String teamNumber = JOptionPane.showInputDialog("Enter team number: "); //Attempts to obtain a valid team number to add
            if(teamNumber.matches("[0-9]+")){ // if the input consists only of numbers
                if(!Main.teams.contains(teamNumber)){ // if the team doesn't exist
                    Main.teams.add(teamNumber); //Add the team number to the list
                    System.out.println("Added: " + teamNumber + " to List");
                    break;
                }
                else{
                    JOptionPane.showMessageDialog(this, "This team already exists");
                    break;
                }
            }
            else{
                JOptionPane.showMessageDialog(this, "This team number contains illegal characters");
            }
        }
        updateComboBox(); // update the combo box
    }

    private void updateComboBox() {
        this.dropDown.removeAllItems();// clears the box
        ArrayList<String> al = Main.teams;
        //java.util.Collections.sort(Main.teams);//Orders the combobox by team number
        int als[] = new int[al.size()];
        for(int i =0; i< al.size(); i++){
            als[i] =Integer.parseInt(al.get(i));
        }

        Arrays.sort(als);

        Main.teams.clear();
        for(int i = 0; i< als.length;i++){
            Main.teams.add(Integer.toString(als[i]));
        }

        for(int i = 0; i< Main.teams.size();i++){ // adds all of the items to the combobox
            this.dropDown.addItem(Main.teams.get(i));
            System.out.println("Added: " + Main.teams.get(i) + " to ComboBox");
        }
    }
    private void updateToggle(){
        if(this.toggleButton.isSelected()){
            this.textArea.setEditable(false);
            this.textArea.setFocusable(false);
            System.out.println("You can't edit");
        }
        else{
            this.textArea.setEditable(true);
            this.textArea.setFocusable(true);
            System.out.println("You can edit");
        }
    }    

    private String[] getAllTeamNames(){
        File folder = new File(folderPath);
        File[] listOfFiles = folder.listFiles();
        String ret [] = new String[listOfFiles.length];
            for (int i = 0; i < listOfFiles.length; i++) {
              if (listOfFiles[i].isFile()) {
                System.out.println(listOfFiles[i].getName());
                String name = "";
                String n = listOfFiles[i].getName();
                for(int a = 0; a< n.length();a++){
                    if(n.charAt(a) == '.'){
                        break;
                    }
                    else{
                        name = name + n.charAt(a);
                    }
                }
                ret[i] = name;
              }
            }
            return ret;
    }

    private void saveFile() throws IOException{
        String targetPath = folderPath + "\\" +currentTeamNumber + ".txt"; //Path to the file that needs to be overridden
        FileWriter writer = new FileWriter(targetPath);
        this.textArea.write(writer);
        writer.write("end"); //(This works properly)
        System.out.println("Wrote to: " + targetPath);
        System.out.println(this.textArea.getText());
        writer.close();
    }

}

【问题讨论】:

  • 这个(可能是微不足道的)问题不应该用 350 LOC 来演示!为了尽快获得更好的帮助,请发布MCVE(最小完整且可验证的示例)。
  • 哦,我不知道这存在,谢谢你的参考:)

标签: java swing awt jtextarea


【解决方案1】:

我不确定我是否完全理解您的问题。但在我看来,您正试图将 JTextArea 中的文本写入文件。如果是这样,那么这就是我通常这样做的方式。

实际编写代码在嵌套的 ButtonHandler 类中。

public class TextAreaWrite extends JFrame{

private JTextArea area = new JTextArea();

public TextAreaWrite(){
    setLayout(new BorderLayout());
    area.setText("Hi \n bye");
    add(area, BorderLayout.CENTER);
    JButton button = new JButton("write");
    button.addActionListener(new ButtonHandler());
    add(button, BorderLayout.SOUTH);
    setVisible(true);
}

private class ButtonHandler implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent arg0) {
        //Create the path to the file
        File file = new File("C:\\text.txt");
        try {
            //create the file if it doesn't exist
            file.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //create a stream from the file
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //Create a printWriter from the fileOutputStream
        PrintWriter writer = new PrintWriter(fos);
        //get the text from the text area and split it into an array splitting at the new line character
        //so that eash line from the textArea is in the array
        String[] text = area.getText().split("\n");
        //And now print all the lines from the textArea onto the lines in the textfile
        int c = 0;
        while(c < text.length){
            writer.println(text[c]);
            c++;
        }
        //flush to make sure the data is send
        writer.flush();
        //close our resources
        writer.close();
    }
}

public static void main(String[] args){
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new TextAreaWrite();
        }
    });
}

}

这将在您的 C: 驱动器上创建一个名为 text.txt 的文件。
如果您运行此程序,请确保以管理员权限运行,否则可能不会允许 java 写入您的 C: 驱动器

希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 2021-04-26
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2014-11-18
    相关资源
    最近更新 更多