Даже этот вопрос уже ответил. У меня есть другой подход к использованию RegExp и совпадение, чтобы игнорировать регистр. См. Мою ссылку https://jsfiddle.net/marchdave/7v8bd7dq/27/
$("#btnGuess").click(guessWord);
function guessWord() {
var letter = $("#guessLetter").val();
var word = 'ABC';
var pattern = RegExp(letter, 'gi'); // pattern: /a/gi
var result = word.match(pattern);
alert('Ignore case sensitive:' + result);
}
Ниже приведен пример сохранения текстового файла с помощью JButton
для запуска события.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.io.*;
public class DisplayPanel {
public static String textFilePath = // adjust path as needed
"C:\\Users\\Andrew\\Documents\\junk.txt";
private JComponent ui = null;
private JFrame frame;
private JTextArea theText;
private JButton saveButton;
private ActionListener actionListener;
File file;
DisplayPanel(File file) {
this.file = file;
try {
initUI();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void saveText() {
Writer writer = null;
try {
writer = new FileWriter(file);
theText.write(writer);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public final void initUI() throws FileNotFoundException, IOException {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
theText = new JTextArea(20, 120); //120 monospaced chrs
theText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
theText.setLineWrap(true);
theText.setEditable(true);
JScrollPane scroll = new JScrollPane(theText);
scroll.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
ui.add(scroll);
saveButton = new JButton("Save");
ui.add(saveButton, BorderLayout.PAGE_START);
actionListener = (ActionEvent e) -> {
saveText();
};
saveButton.addActionListener(actionListener);
Reader reader = new FileReader(file);
theText.read(reader, file);
}
public void createAndShowGUI() {
frame = new JFrame(this.getClass().getSimpleName());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setContentPane(getUI());
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
File file = new File(textFilePath);
DisplayPanel o = new DisplayPanel(file);
o.createAndShowGUI();
};
SwingUtilities.invokeLater(r);
}
}
Один из способов справиться с этим - изменить поведение по умолчанию закрытия окна и добавить WindowListener, который улавливает событие закрытия окна и выполняет сохранение там.
Простой пример, который можно добавить в Класс DisplayPanel (сразу после создания объекта jFrame):
theFrame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
theFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
String[] lines = theText.getText().split("\\n");
try (BufferedWriter writer = new BufferedWriter(new FileWriter("newfile.txt"))) {
for (String line : lines)
writer.write(line + "\n");
} catch (IOException i) {
System.out.println("Cannot write file...");
}
System.out.println("File saved!");
System.exit(0);
}
});
При закрытом окне код выше сохранит измененный текст в файле newfile.txt
.
В приведенном выше примере расщепление на строки, вероятно, не нужно; вы, вероятно, получите правильный результат, просто выполнив writer.write(theText.getText());
.
Некоторая соответствующая документация: