Skip to main content

swing question

3 replies [Last post]
frost750
Offline
Joined: 2006-12-22

Fairly new to Java... problem is trying to pass a Jframe (or frame) to another class. Both classes extend JFrame.

public class firstClass extends JFrame
stuff...
secondClass second = new secondClass("sometext", getFrames());
end firstClass

public class secondClass extends JFrame
stuff...
public secondClass(String sometext, Frame[] aframe)
aframe[0].setEnabled(false);
end secondClass

The above code works some of the time depending on how I interact with the gui. I have spent hours searching through the methods for Window, Frame and JFrame. Once again I am fairly new to Java(over a year) and any input would be welcomed. Thanks

Greg

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
tarbo
Offline
Joined: 2006-12-18

If you want a back reference--your second class wishes a reference to the JFrame that created it--then you can simply use the [b]this[/b] keyword.

[code]public class firstClass extends JFrame {
// stuff...
secondClass second = new secondClass("sometext", this);
}

public class secondClass extends JFrame
// stuff...
public secondClass(String sometext, Frame aframe) {
aframe.setEnabled(false);
}
}[/code]

I'm otherwise not sure what you intend to do.

frost750
Offline
Joined: 2006-12-22

Thank you for your reply. I do want to pass the JFrame along to the next class so I can use setEnabled(false). I tried using the this keyword before I posted here and wasn't able to get it to work. Doesn't find a suitable constructor in the second class. I know this is a simple problem and I can usually figure stuff out by reading through the API. This 1 really has me confused though. Thanks again for your reply.

tarbo
Offline
Joined: 2006-12-18

You need a method with suitable signature. Each of the provided arguments should be upward castable (widening) to their respective formal ones.

The code provided should suffice. If it does not, then either you have not entered the provided code correctly, or you are not working with your compiled classes.

I haven't compiled or run it, but try the following:
[code]import java.awt.Dimension;
import javax.swing.JFrame;

public class TestCase1 extends JFrame {
public TestCase1() {
super("TestCase1 instance");
}
}

class TestCase2 extends JFrame {
protected JFrame other;

public TestCase2(JFrame other) {
super("TestCase2 instance");
this.other = other;
other.setEnabled(false);
}
}

public static void main(String[] args) throws InterruptedException {
final Dimension prefSize = new Dimension(200, 120);
JFrame test1 = new TestCase1();
test1.setPreferredSize(prefSize);
test1.setVisible(true);
Thread.sleep(2000); /* Wait for 2 seconds */
JFrame test2 = new TestCase2(test1);
test2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test2.setPreferredSize(prefSize);
test2.setVisible(true);
}[/code]