日期:2014-05-20  浏览次数:20685 次

关于监听器的一些事?
package ydtextNote;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class TextNode 
{
public static void main(String[] args)
{
TextNoteFrame frame=new TextNoteFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

}

}

class TextNoteFrame extends JFrame
{
private String titleName="未命名";
JMenu FileMenu,EditMenu;
private boolean isDirty=false;
JMenuItem NewFile,OpenFile,SaveFile,SaveFileTo,Exit,Copy,Paste,Search,Replace;
public static final int DEFAULT_WIDTH=400;
public static final int DEFAULT_HEIGTH=350;
public static final int DEFAULT_XLOCATION=300;
public static final int DEFAULT_YLOCATION=250;
JTextArea TextArea;

public TextNoteFrame()
{
setTitle(FormatTitleName());
setSize(DEFAULT_WIDTH,DEFAULT_HEIGTH);
setLocation(DEFAULT_XLOCATION,DEFAULT_YLOCATION);
JMenuBar menuBar=new JMenuBar();
FileMenu=new JMenu("文件");
EditMenu=new JMenu("编辑");
menuBar.add(FileMenu);
menuBar.add(EditMenu);
setJMenuBar(menuBar);
NewFile=new JMenuItem("新建");
OpenFile=new JMenuItem("打开");
SaveFile=new JMenuItem("保存");
SaveFileTo=new JMenuItem("另存为");
Exit=new JMenuItem("退出");
Copy=new JMenuItem("复制");
Paste=new JMenuItem("粘贴");
Search=new JMenuItem("查询");
Replace=new JMenuItem("替换");


FileMenu.add(NewFile);
FileMenu.add(OpenFile);
FileMenu.add(SaveFile);
FileMenu.add(SaveFileTo);
FileMenu.add(Exit);
EditMenu.add(Copy);
EditMenu.add(Paste);
EditMenu.add(Search);
EditMenu.add(Replace);

JTextArea TextArea=new JTextArea();
TextArea.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
if(!isDirty())
{
setIsDirty(true);
}
}
});

JScrollPane scrollPane=new JScrollPane(TextArea);
add(scrollPane,BorderLayout.CENTER);
NewFileActionListener newFileAction=new NewFileActionListener();
NewFile.addActionListener(newFileAction );//大侠们看看这有啥错误?为啥连框架也显示不出来了? 这样加监听,对不?
}



private String getTileName()
{
return titleName;
}
private void setTileName(String titleName)
{
this.titleName=titleName;
}

public boolean isDirty()
{
return isDirty;
}
public void setIsDirty(boolean dirty)
{
isDirty=dirty;
setTitle(FormatTitleName());
}
public String FormatTitleName()
{
StringBuffer strTitleName=new StringBuffer(getTileName());
strTitleName.append(isDirty()?"*":"");
strTitleName.append("-");
strTitleName.append("MyText");
return strTitleName.toString();

}
class TxtFileFilter implements FileFilter
{
public boolean accept(File f) 
{
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
public String getDescription() 
{
return "*.txt(文本文件)";
}
 
}

}

class NewFileActionListener implements ActionListener
{
TextNoteFrame fr=new TextNoteFrame();
public void actionPerformed(ActionEvent e)
{
if(fr.isDirty())
{
int ret=JOptionPane.showConfirmDialog(fr.getContentPane(), "文件已改变,是否保存", 
"MyText", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
if(ret==JOptionPane.OK_OPTION)
{
JFileChooser saveDialog=new JFileChooser();