我正在尝试保存选项卡式窗格内面板上的文本区域的内容。
到目前为止,我已经尝试过:
bw.write(tabbedPane.getComponent(tabbedPane.getSelectedIndex()).toString());
并且一直在查看 tabbedpane 的所有方法,但我似乎无法解决。我知道我必须从 中获取选定的组件tabbedPane
,然后以某种方式从中获取 textarea,然后将其转换为我假设的字符串?
我打开文件时的代码是:
private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == fileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
JTextArea x = new JTextArea();
JScrollPane scroll = new JScrollPane(x);
p.add(scroll, BorderLayout.CENTER);
x.read( new FileReader( file.getAbsolutePath() ), null );
File selectedFile = fileChooser.getSelectedFile();
String name = selectedFile.getName();
tabbedPane.add(p,name);
tabbedPane.setSelectedComponent(p);
} catch (IOException ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
我已经添加了类,因为您坚持更新当前 SaveAs 方法:
private void btnSaveAsActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showSaveDialog(this);
if (returnVal == fileChooser.APPROVE_OPTION) {
File dir1 = fileChooser.getCurrentDirectory();
String dir = dir1.getPath();
String name = fileChooser.getSelectedFile().getName() + ".txt";
try {
File file = new File(dir,name);
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
JPanel no = (JPanel) tabbedPane.getSelectedComponent();
JTextArea bo = (JTextArea) no.get
bw.write(bo.getText());
bw.close();
tabbedPane.setTitleAt(tabbedPane.getSelectedIndex(), name);
} catch(Exception e) {
System.out.println(e);
}
}
}
当前打开文件方法:
private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == fileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
FilePanel p = new FilePanel(file);
tabbedPane.add(p,p.getName());
tabbedPane.setSelectedComponent(p);
} catch (IOException ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
我是否需要将新类的新对象添加到数组中,还是只需将它们插入到 tabbedPane 中就可以了?