Friday, January 18, 2008

Java Coding Question And Answers

Detecting Double and Triple Clicks

component.addMouseListener(new MyMouseListener());
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 3) {
// triple-click
} else if (evt.getClickCount() == 2) {
// double-click
}
}
}

Handling Focus Changes

component.addFocusListener(new MyFocusListener());

public class MyFocusListener extends FocusAdapter {
public void focusGained(FocusEvent evt) {
// The component gained the focus.
}
public void focusLost(FocusEvent evt) {
// The component lost the focus.
}
}

Files, Streams, I/O (java.io)

Constructing a Path

On Windows, this example creates the path \blash a\blash b. On Unix, the path would be /a/b.

String path = File.separator + "a" + File.separator + "b";

Reading Text from Standard Input

try {

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (str != null) {
System.out.print("> prompt ");
str = in.readLine();
process(str);
}
} catch (IOException e) {
}

Reading Text from a File

try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
} catch (IOException e) {
}
Writing to a File
If the file does not already exist, it is automatically created.

try {
BufferedWriter out = new BufferedWriter(new FileWriter("outfilename"));
out.write("aString");
out.close();
} catch (IOException e) {
}

Creating a Directory

(new File("directoryName")).mkdir();

Appending to a File

try {
BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
out.write("aString");
out.close();
} catch (IOException e) {
}

No comments:

 
Google