Magazine
 
Tips & Tricks
 

menu.add(cut);
menu.add(paste);
menu.add(save);
menu.add(quit);
menuBar.add(menu);
//Add listeners to the items.
open.addActionListener(this);
copy.addActionListener(this);
cut.addActionListener(this);
paste.addActionListener(this);
save.addActionListener(this);
quit.addActionListener(this);
}
public static void main(String[] args){
new Notepad(“Notepad”).setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String cmd =
(String)ae.getActionCommand();
if (cmd.equals(“Open”)) open();
else if (cmd.equals(“Copy”)) copy();
else if (cmd.equals(“Cut”)) cut();
else if (cmd.equals(“Paste”)) paste();
else if (cmd.equals(“Save”)) save();
else if (cmd.equals(“Quit”)) quit();
}
public void open() {
JFileChooser fileChooser = new
JFileChooser();
fileChooser.setFileFilter
(javaFileFilter);

int returnVal =
fileChooser.showOpenDialog(this);
if(returnVal ==
JFileChooser.APPROVE_OPTION){
file = fileChooser.getSelectedFile();
String fileContent = readFile(file);
field.setText(fileContent);
}
}
public String readFile (File file) {
StringBuffer strBuffer;
String fileContent=null;
String lineString;
try {
FileReader fr = new FileReader(file);
BufferedReader br = new

 

BufferedReader(fr);
strBuffer = new StringBuffer() ;
while ((lineString = br.readLine ()) != null) {
strBuffer.append (lineString + “\n”);
}
fr.close();
fileContent = strBuffer.toString();
String name = file.getName();
if(name != null) {
int extensionIndex = name.lastIndexOf(‘.’);
setTitle(name.substring(0,extensionIndex));
}
}
catch (IOException e ) {
return null;
}
return fileContent;
}
public void copy() {
String s = field.getSelectedText();
int start=field.getSelectionStart();
int end=field.getSelectionEnd();
StringSelection ss = new
StringSelection(s);
// Set the content to the clipboard.
this.getToolkit().getSystemClipboard().
setContents(ss, ss);
}
public void cut() {
String s = field.getSelectedText();
int start=field.getSelectionStart();
int end=field.getSelectionEnd();
field.replaceRange(“”,start,end);
StringSelection ss = new
StringSelection(s);
// Set the content to the clipboard.
this.getToolkit().getSystemClipboard().setContents(ss,
ss);
}
public void paste() {
Clipboard cb = this.getToolkit().getSystemClipboard();
Transferable tr = cb.getContents(this);
try {
// Get the content from the clipboard.
String s = (String)

Oct 2007 | Java Jazz Up | 69
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78,   Download PDF