前言:部分代码和效果图展示
记事本文件菜单效果图
保存文件代码
// 保存文件事件调用的方法
private void baocun() {
// 捕获异常是为了防止用户取消保存报错
try {
// 弹出文件保存对话框
FileDialog fdg = new FileDialog(frame, "另存为", FileDialog.SAVE);
// 设置默认文件名
fdg.setFile("*.txt");
fdg.setDirectory("D:\");
// 要先显示
fdg.setVisible(true);
// 判断用户是否选择了文件
if (fdg.getFile().equals(null) || fdg.getFile().equals("") || fdg == null) {
return;
}
// 获取文件路径和文件名
String fpath = fdg.getDirectory() + fdg.getFile();
try {
// 保存文件
FileOutputStream fop = new FileOutputStream(fpath);
fop.write(textarea.getText().getBytes());
fop.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("保存文件已取消");
return;
}
}
转到功能
private void zhuandao(){
//取得总行数
int totalLineCount = textarea.getLineCount();
if(totalLineCount <= 1){
return ;
}
String title = "(1..."+totalLineCount+")";
String line = JOptionPane.showInputDialog("跳转到指定行",title);
if(line==null||"".equals(line.trim())){
return;
}
try {
//用户要转到的行号
int intLine = Integer.parseInt(line);
if(intLine > totalLineCount){
JOptionPane.showMessageDialog(frame,"没有找到对应的行号");
return;
}
// 获取行对应的列号 Jtextarea起始行号是0,所以此处做减一处理
int selectionStart = textarea.getLineStartOffset(intLine-1);
int selectionEnd = textarea.getLineEndOffset(intLine-1);
//如果是不是最后一行,selectionEnd做减一处理,是为了使光标与选中行在同一行
if(intLine != totalLineCount){
selectionEnd--;
}
//获得焦点,因为弹出对话框后焦点可能已丢失
textarea.requestFocus();
textarea.setSelectionStart(selectionStart);
// 就选到此
textarea.setSelectionEnd(selectionStart);
} catch (Exception e) {
e.printStackTrace();
}
}
添加状态栏,以及状态栏显示几行几列
private void addState() {
statepl=new JPanel(new FlowLayout(FlowLayout.RIGHT));
//左右状态栏面板
JLabel zuo = new JLabel("|100% |windows(CLRF) |UTF-8 ");
JLabel youztl=new JLabel("第1行,第1列 ");
//设置焦点监听器
textarea.addCaretListener(new CaretListener(){
@Override
public void caretUpdate(CaretEvent e) {
int row=0;
int column=0;
//textarea.getCaretPosition();//获取焦点占了多少字符
int pose=e.getDot();
try {
//返回文本域焦点所在的行 ,
row=textarea.getLineOfOffset(pose);
//textarea.getLineStartOffset();返回给定行起始处的偏移量,即可获得对应行的列数
column=pose-textarea.getLineStartOffset(row);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 行、列号从0开始
youztl.setText("第"+(row+1)+"行,"+"第"+(column+1)+"列 ");
}
});
statepl.add(youztl);
statepl.add(zuo);
contentPane.add(statepl, BorderLayout.SOUTH);
}
记得点赞哦,有问题请私信呀



