比较JTextArea中的行可以使用以下代码示例中的解决方法:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextAreaComparisonExample {
public static void main(String[] args) {
JFrame frame = new JFrame("TextArea Comparison Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea textArea1 = new JTextArea();
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
JTextArea textArea2 = new JTextArea();
textArea2.setLineWrap(true);
textArea2.setWrapStyleWord(true);
JButton compareButton = new JButton("Compare");
compareButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String[] lines1 = textArea1.getText().split("\\n");
String[] lines2 = textArea2.getText().split("\\n");
if (lines1.length != lines2.length) {
JOptionPane.showMessageDialog(frame, "Number of lines is different");
return;
}
for (int i = 0; i < lines1.length; i++) {
if (!lines1[i].equals(lines2[i])) {
JOptionPane.showMessageDialog(frame, "Lines at index " + i + " are different");
return;
}
}
JOptionPane.showMessageDialog(frame, "All lines are the same");
}
});
JPanel panel = new JPanel();
panel.add(new JScrollPane(textArea1));
panel.add(new JScrollPane(textArea2));
panel.add(compareButton);
frame.add(panel);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
这个示例创建了一个包含两个JTextArea和一个比较按钮的简单Swing应用程序。当点击比较按钮时,它将获取两个文本区域中的行,并逐行比较它们。如果行数不同,它将显示一个消息框指示行数不同。如果行相同,则显示一个消息框指示所有行都相同。