Search code examples
splitlinesystemjtextareaseparator

How can i check for enter key command in JTextArea after using .split?


I am using .getText().split(";") to separate a JTextArea's input. Then, I am needing to read from each line afterwards. Problem: Each line after the first seems to start with a System.lineSeparator() and I can't figure out how to detect it. I'm trying things like .indexOf(System.lineSeparator()) and .indexOf("/n"), but it's not being detected. What is it called? And yes, I know that I could just tell the program to take lines[c].substring(1, lineLeft.length()) once it has already checked the first line, but there must be a simple explanation as to why I cant find the "new line" thing with an indexOf(). It would also help to prevent bugs in my program to use indexOf() with the new line thing. I'm making something like Jeroo, in case you guys are wondering what this is for. To see my issue visually, simply grab any image large enough from the internet or on your PC and set it as "label", then change the frame.setSize() in the TheRunner class. But you probably already know this. Then, type something like:

hi;

hi;

into the JTextArea, and click on the print button. You'll see the issue.

import javax.swing.JFrame;
public class TheRunner{
    public static void main(String[] args){
        JFrame frame = new JFrame("My GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new Test());
        frame.setVisible(true);
        frame.setSize(640, 960);
    }
}

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Test extends JPanel implements ActionListener{
    JTextArea textArea = new JTextArea();
    String lineLeft;
    JButton button = new JButton("Print");
    public Test(){
        toDo();
    }
    public void toDo(){
        JLabel label = new JLabel(new ImageIcon("C:\\00105_1.jpg"));
        label.setLayout(null);
        add(label);
        label.add(textArea);
        label.add(button);
        button.setBounds(20, 230, 140, 60);
        textArea.setBounds(20, 20, 400, 200);
        button.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e){
        if(e.getSource() == button){
            String[] lines = textArea.getText().split(";");
            for(int c = 0; c < lines.length; c++){
                System.out.println(lines[c]);
            }
        System.out.println("First line starts with: " + lines[0].substring(0, 1));
        System.out.println("Second line starts with: " + lines[1].substring(0, 1));
        }
    }
}

Solution

  • I think there is no need to use ; character. If you want to get each line from JTextArea you can use following

    String[] lines = textArea.getText().split("\n");