Search code examples
javaswingawtjtextarea

JTextArea apparently contains no text, even when it does?


I am creating a simple java swing application that implements the usage of a JTextArea (it is a simple text editing type program). I however have encountered an issue when trying to write the contents of the textArea into a text file. I use the following code to accomplish this:

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

I have eliminated the possibility of an incorrect file path by testing the same FileWriter object with the method:

   writer.write("String");

this accomplishes its task perfectly. I also have tried to print the contents of the textArea to the console with the getText() method, this creates a blank line on the console even when the textArea contains text. An example of this text I had entered would be: "Hello World". The variable initialization and setup are below:

   JTextArea textArea = new JTextArea();

Could this issue be caused by calling the methods:

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

because that is the only modification I have done to the settings of the text area(other than color modifications). I feel like there is a simple issue that I am over looking. The full class for this project can be found below. I do not believe that I have overlooked any details, Thanks for your time.

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

}


Solution

  • I am not sure if I understand you problem fully. But it seems to me that you are trying to write the text in a JTextArea to a file. If that's so then this is the way I ussually do that.

    The actual write code is in the nested ButtonHandler class.

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

    }

    This will create a file called text.txt on your C: drive.
    And if you run this programm make sure to run with administrator rights or else java might not be alowed to write to your C: drive

    Hope this solves your problem.