1. Create a JButton.
2. Add an ActionListener to the JButton
3. To the listener, add this code:
JDialog dialog = new JDialog(MyFrame.this, true);
JEditorPane editorPane = new JEditorPane();
editorPane.setEditable(false);
java.net.URL helpURL = MyFrame.class.getResource(
"/my_dir/help.html");
if (helpURL != null)
{
try
{
editorPane.setPage(helpURL);
}
catch (IOException e)
{
System.err.println("Attempted to read a bad URL: " + helpURL);
}
}
dialog.getContentPane().add(editorPane);
dialog.setSize(400, 350);
dialog.setLocationRelativeTo(MyFrame.this);
dialog.setVisible(true);
Note: there are a couple of things you can do to make the code a little nicer but I'll leave that as an exercise for you.
> JDialog dialog = new JDialog(MyFrame.this,
> true);
> What does myFrame.this mean? I looked in the JFrame
> class, and there is no 'this' field listed.
> Shouldn't that just be MyFrame?
Why don't you try it out?
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener
{
//code in here
myButton.setActionCommand("cmd");
myButton..addActionListener(this);
//more code
public void actionPerformed(ActionEvent ae)
{
if( "cmd".equals(ae.getActionCommand()) )
{
JDialog ...
}
...
> What does myFrame.this mean? I looked in the JFrame
> class, and there is no 'this' field listed.
> Shouldn't that just be MyFrame?
"this" always refers to the current instance of the current object, right? So instead of:
setTitle("Hello World");
you can do something like:
this.setTitle("Hello World");
(Although, why would you?)
But, let's suppose you do something like this:
public class MyClass {
private String test = "test1";
private class ThreadEntryPoint implements Runnable {
private String test = "test2";
public void run() {
System.out.println("test = " + this.test);
...
ThreadEntryPoint entryPoint = new ThreadEntryPoint();
entryPoint.run();
...
Is this going to print test1 or test2? The answer is "test2", since that's the "test" variable defined in the inner class. But, since ThreadEntryPoint was not declared as a static class, if the inner class didn't have a "test" variable, the reference to "test" could refer to the outter variable. If you remove the "test2" variable in the code above, it will still compile and print "test1".
But what if you wanted to print "test1" without removing "test2"? This is where the mechanism you are inquiring about comes in; it allows you to reference variables in outter classes which are occluded by variables in the inner class. So, you could write something like:
System.out.println("TheadEntryPoint.test = " + TheadEntryPoint.this.test);
System.out.println("MyClass.test = " + MyClass.this.test);
> Jason:
>
> Thanks for that reply. I wanted the poster to see
> the error in compilation and then investigate;
> Socratic license if you will.
:) Sorry if I stepped on your toes. I just wasn't sure the mechanism would be "obvious" from a compiler error, especially if you're new to Java or OO programming in general.