Jframe inheritance question

hi why is it when i set the variable inside secondframe class
it just doesn't stick. i have a example that describes my problem better.
i can see that when void show is called that it makes a new instance of
second frame class so how would i fix this.
i know i could scope int x through the show method and use it that way
but im wanting to change varibles inside second class dynamicly
any ideas thanks
firstclass with frame1
public class Main {
    public static void main(String[] args) {
          firstframe frame = new firstframe();
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setSize(270, 500);
          frame.setVisible(true);
        frame.setAlwaysOnTop(true);
class firstframe extends JFrame
    private int x = 10;
    firstframe(){
    super.setTitle("first frame");
    System.out.println("first result :" + x);
    secondframe frame2 = new secondframe();
    secondclass.show();
}second class
public class secondclass {
    public static void show()
          secondframe frame = new secondframe();
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
          frame.setSize(270, 500)thanks;
          frame.setVisible(true);
        frame.setAlwaysOnTop(true);
class secondframe extends JFrame
    private int x;
    public secondframe(){
        super.setTitle("second frame");
        System.out.println("end result :" + x);
    public void setvaribles(int x){
        this.x = x;
}

Use proper Java naming conventions.
Class names should be upper cased: ie FirstFrame, not firstframe.
Method names are also upper cased except the first word: ie. setVariables, not setvariables.
Why is show a static method? The only static method should be the main(...) method.
You don't even need a show() method, the code to create the frame should be in the constructor.
Also, applications should only have a single JFrame. Other windows should be JDialogs.

Similar Messages

  • Constructor Inheritance Question

    Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
    In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
    public class ClassChild extends ClassParent
        public static void main(String[] args) {
            ClassChild child = new ClassChild();
    }Both classes compiled successfully, which raised the following question:
    I understand that the ClassParent default constructor calls the Object's no-argument constructor.
    Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
    And a somewhat non-related question:
    Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
    Edit: After running the following code, I realized that the answer to my last question is yes:
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
           boolean test = tester instanceof Object;
           System.out.println(test);
    }Edited by: youmefriend722 on May 26, 2008 1:54 PM

    youmefriend722 wrote:
    I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
    Constructor inheritance:
    If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
    So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
    But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
    If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
    If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
    Constructors in general:
    In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

  • Multiple inheritance question

    This just occurred to me. I read the other day that all classes inherit Object. So if I have a class defined as public class A {
    }and I call toString() on an instance of this class, I get Objects toString implementation (assuming it has not been overridden). OK, this I understand.
    Now if instead I havepublic class A extends B {
    }and I call toString() on A, assuming it is not overridden in either A or B, I will still get Objects toString method. My question is, does A still extend Object, or does it inherit the fact that B extends Object? And what happens if I override toString() in B - what will I get if i call toString on an instance of A?

    java.lang.Object is at the root of all class inheritance hierarchies in Java. Therefore, all classes inherit from java.lang.Object, either directly or indirectly.
    When you call a method on an object of class Foo, Foo's inheritance hierarchy is traced starting with Foo and going all the way back to java.lang.Object, looking for an implementation of the method. The first implementation encountered is the one that gets used. So in your example calling toString on an instance of class A will result in B's toString method being executed.
    Hope this makes sense.

  • JFrame Design Question

    Folks,
    I'm creating a Java App using swing and had a quick question. Does it make more sense when creating a frame to extend the JFrame class or to create a new JFrame object in the constructor of the class that will provide the gui? I don't need to extend any other classed by this gui class so I'm not worried about that but rather what makes sense from a strictly OOP design viewpoint? By extending the JFrame class I should be creating a more specific JFrame class. However, I'm not really adding any functionality (technically), I'm just painting some objects. Thanks for your input.
    Andreas

    I can think of a couple options:
    1) Let IconFrame's constructor accept a Test parameter, instead of creating an interface.
    2) Make IconFrame into a modal dialog & have it store the user's selection in a variable. Then when you show the dialog, your action listener will block until the user selects an icon. Then you can call "getSelectedIcon()" to retrieve his/her selection. This would be much like the JOptionPane.showXXX() methods, and probably the cleaner solution.

  • For loops & inheritance question

    I am trying this exercise dealing w/inheritance. I enter at command line a random number of c's, s's and m's. for checking,savings and money market. I then parse the string and check for the character. From there I create one of the accounts. then I am supposed to make a report that displays the past 3 months activities. the first account created gets 500 deposit the from there each account after the first gets an additional 400. so it would be: 500,900,1300,etc. Here is what I have so far, but the report part is where I can't figure out exactly how to go about solving it. Thanks in advance.
    public static void main( String args[] ){
         int intDeposit = 500;
         char charTest;
         Object [] objArray = new Object[args[0].length()];
         for ( int j = 0; j < 3; j ++ ){                        System.out.println( "Month " + ( j +1 ) + ":" );
             for( int i = 0; i < args[ 0 ].length(); i ++ ){
              charTest = args[ 0 ].charAt( i );
                         if (charTest == 'c' ){
                  BankAccount at = new  CheckingAccount( intDeposit );
                  objArray=at;
              else if( charTest == 's' ){
              BankAccount at = new SavingsAccount( intDeposit );
              objArray[i]=at;
              else if( charTest == 'm' ){
              BankAccount at = new MoneyMarket( intDeposit );
              objArray[i]=at;
              else{
              System.out.println( "invalid input" );
              }//else
              intDeposit += 400;
              System.out.println();
         }//for j
         for (int counter = 0; counter < objArray.length; counter ++ ){
              System.out.println( "Account Type: " +
                        objArray[counter].toString() );
              System.out.println( "Initial Balance: " +
                        (BankAccount) objArray[counter].getCurrentBalance() );
         System.out.println( "TotalDeposits: " + objArray[counter].getTotalDeposits() );
         System.out.println();
         }//for i
    }//main
    }//TestBankAccount.java\

    The only thing I think is wrong is the following line:
    System.out.println( "Initial Balance: " +                    (BankAccount) objArray[counter].getCurrentBalance() );
    Should be:
    System.out.println( "Initial Balance: " +                    ((BankAccount) objArray[counter]).getCurrentBalance() );

  • Multiple Components in a JFrame (simple question)

    Hello everyone, I need to put two components in my JFrame, and I have been expieriencing some odd problems. I use this to add my components...
    MyComponent mc=new MyComponent();
    MyOtherComponent me = new MyOtherComponent();
    When I try to access methods they work fine. I can use repaint() in a method and it works. BUT when I try to draw on the component using anything besides paintComponent() It gives me a java.lang.NullPointerException
    here is what I tried.....
    me.draw(getGraphics());
    //later on in the component def..
    draw(Graphics g) {
    } // I get a java.lang.NullPointerException in main
    whenever i use getGraphics() it does'nt work what am I doing wrong?

    Yup I did that and repaint does jack all. When I run the code all I see the contents of the first component. I know that the methods of the second component are being executed, but the paintComponent method is simply not running. I put a System.out.println("hi"); in and it never showed in the console..
    Anyone who can help me gets a duke, here's my second component code..
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    class MyOtherComponent extends JComponent {
    public void paintComponent(Graphics gg) {
    System.out.println("paintComponent executed!!!");
    Graphics2D g2D = (Graphics2D)gg;
    ImageIcon icon = null;
    try {icon = new ImageIcon(new URL("http://images.neopets.com/m.gif")); }
    catch(MalformedURLException e) {
    System.out.println("no"); return;
    resize(icon.getIconWidth(),icon.getIconHeight());
    Image mark = icon.getImage();
    g2D.drawImage(mark,0,0,this);
    g2D.drawString("hello folk",40,40);
    drawe(g2D);
    public void drawe(Graphics2D g2D) {
    g2D.drawLine(50,50,500,500);
    g2D.fillRect(20,20,20,20);
    repaint();
    public void line() {
    System.out.println("Hello, from MyOtherComponent");
    public void re() {
    repaint();
    System.out.println("re");     
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • JFRAME- JPANEL question

    I have a JFrame that holds a JPanel. If that JPanel needs to contact the JFrame how do I get access to parent? I tried panelname.getParent, when I did I got a
    java.lang.ClassCastException
    Any help would be great.
    Brock

    i think you have to buid your own JPanel class lyke this:
    public class MyJPanel extends JPanel{
    JFrame parent;
    public MyJPanel(JFrame p){
    parent = p;
    // here you have access to the parent JFrame in your JPanel
    public JFrame getParentFrame(){
    return parent;
    // here you return the parent of the JPanel
    so in your JFrame class you add the JPanel like this:
    getContentPane().add(new MyJpanel(this));
    i hope it helps you. :)

  • JFrame resizing question

    When i resize a JFrame the components it hold remain unchanged until I stop resizing the frame. Then the components conform to the frame size. Is there a way to have the components resize dynamically?

    Thank for the answer, that's exactly what I nedded!

  • Inheritance questions

    Say a superclass has 3 methods and 3 properties. NExt, I create a subclass which overrides these same 3 methods and properties. Either way, my question really is this... When casting up and down, when it is a subclass and a super class reference, are the properties preserved when it is cast(implicitly) up to a superclass reference, so that, in case it needs to be cast back down (explicitly) to its original subclass form, the subclass properties can still be referred to? Are the original variables still preserved (much like a static variable)?

    are the properties preserved when it is cast(implicitly) up to
    a superclass reference, so that, in case it needs to be cast backAn object instance does not change when it's casted into a superclass reference. This means it can be casted back (if this weren't the case, then all methods that return Object would be pretty useless).
    In addition, accessing an object method via a superclass reference does not mean that you'll invoke a superclass method. Instead, it invokes the method appropriate to the object (otherwise overriding and polymorphism would be pretty useless).
    However, accessing an object's instance variable via a superclass reference does access the superclass variable, not the subclass variable.
    I would suggest playing with this for a while ... here's something to start with:
    public class DROCPDP
        public static void main( String argv[] )
        throws Exception
            Base a = new Base();
            Sub b = new Sub();
            Base c = (Base)b;
            Sub d = (Sub)c;
            System.out.println("\nOperations on A:");
            System.out.println("a.var = " + a.var);
            a.method();
            System.out.println("\nOperations on B:");
            System.out.println("b.var = " + b.var);
            b.method();
            System.out.println("\nOperations on C:");
            System.out.println("c.var = " + c.var);
            c.method();
            System.out.println("\nOperations on D:");
            System.out.println("d.var = " + d.var);
            d.method();       
        private static class Base
            public String var = "Base";
            public void method()
                System.out.println("Called Base.method; variable = " + var);
        private static class Sub extends Base
            public String var = "Sub";
            public void method()
                System.out.println("Called Sub.method; variable = " + var);
    }

  • Small inheritance question

    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.
    Player class and Enemy class contains extra stuff like different image and moves different.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?
    Also,
    If values change in the 'Player' class do the values also change in te 'User' class?
    I am fairly new to java.
    Thanks

    MarcLeslie120 wrote:
    Got a small quesiton about inheritance.
    I have a 'User' Class and extending that class is 'Player' and 'Enemy'.Sounds odd. Aren't some players also your enemy? Or is Player me, and everybody else is Enemy?
    Player class and Enemy class contains extra stuff like different image and moves different.Okay. If it's just different, that's one thing. If it's adding extra methods, you probably don't want to inherit.
    When I create a new player do I create an instance of the 'User' class or the 'Player' class?If it's going to be a Player, you need to create a Player.
    If values change in the 'Player' class do the values also change in te 'User' class?If you mean an instance variable (a non-static member variable), then there aren't two separate objects. There's just one object, that is both a Player and a User. The variable exists only once.
    Your inheritance hierarchy smells funny, but without more details about what these classes represent and what you're trying to accomplish, it's hard to provide concrete advice.

  • JFrame size question

    In my JFrame I have setsize(600, 600) and an addComponentListener. I have the getWidth() and getHeight() called in componentResized method. But I am getting values in (608, 634) in return. Can anyone tell me why is that?

    Show us the code - a simple working example that shows the problem - and then we can probably help you.

  • [Solved] C++ inheritance question

    I have a base class and a bunch of inherited classes.
    I am doing something like this in the main.
    baseclass* base[2];
    base[0]= new _derived1("hello");
    base[1]= new _derived2("world");
    How do I code my base class or what-ever-else so that I CAN'T do this:
    baseclass* base2;
    base2 = new baseclass("class");
    The base class has 1 constructor with an argument type string. I can't have a default constructor.
    So in short. I can create a particular derived class, like a derived1, but can't create a plain base class. (it should throw a compilation error)
    Any help would be appreciated.
    Thanks.
    Last edited by lamdacore (2011-02-06 00:38:43)

    Oh I want a compile error when I do this:
    baseclass* base2;
    base2 = new baseclass("class");
    Example code. So I don't want the base class to be able to make a Base type object. As soon as I do that it SHOULD throw a compilation error.
    class Base{
    public:
    Base(string st):m_st(st)
    virtual ~Base(){
    virtual string ann() const{
    return "";
    virtual string bnn() const{
    return m_st;
    virtual string cnn(string msg) const{
    string k="hey ";
    k.append(msg);
    return k;
    private:
    string m_st;
    class derived1:public Base{
    public:
    derived1(string st):Base(st){
    virtual ~derived1(){
    cout<<"kill";
    virtual string ann() const{
    return "hullo";
    virtual string bnn() const{
    return Base::bnn();
    virtual string cnn(string msg) const{
    string k="hey ";
    k.append(msg);
    return k;
    private:
    string m_st;
    Last edited by lamdacore (2011-02-06 23:38:23)

  • JFrame Sizeing question

    Hello....
    I have a JFrame that i'm using a card layout to bring in panels from separet classes, but when the program starts the frame is super small i have to strech it out to see my panel, how do i force the frame to fit to the panel????

    try using pack() on JFrame

  • Inheritance question

    I'm working on an assignment but I'm getting the following error when I test the code:
    "Card.java": Error #: 300 : constructor CraftItem() not found in class questiontester.CraftItem at line 3, column 8
    I've already tried a number of things to resolve the issue but it keeps cropping up. Can anyone shed any light on what I'm doing wrong please?
    Here's my code:
    CraftItem.java
    (I know this works because it tested out okay)
    package questiontester;
    public class CraftItem {
    // instance variables
    public String itemCode;
    public double price;
    // constructor
    public CraftItem(String itemCodeValue, double itemPriceValue){
    itemCode = itemCodeValue;
    price = itemPriceValue;
    // getter for itemCode
    public String getItemCode() {
    return itemCode;
    // getter for price
    public double getPrice() {
    return price;
    // setter for itemCode
    public void setItemCode(String itemCodeValue) {
    itemCode = itemCodeValue;
    // setter for price
    public void setPrice(double itemPriceValue) {
    price = itemPriceValue;
    // toString() value
    public String toString() {
    return "Item code is " + itemCode + " and costs " + price + " pounds.";
    Card.java
    (this class extends CraftItem and is where I'm getting the error. The error message highlights the class bit in italics as being the problem)
    package questiontester;
    public class Card extends CraftItem {
    // instance variables
    private String cardType;
    private String cardSize;
    //private String itemCode;
    //private double price;
    // Constructor
    public void Card(String cardTypeValue, String cardSizeValue,
    String itemCodeValue, double itemPriceValue) {
    cardType = cardTypeValue;
    cardSize = cardSizeValue;
    itemCode = super.getItemCode();
    price = super.getPrice();
    // methods
    Test.java
    (this the code I'm using to test functionality - it normally works just fine but the error message cropped up when I tried to extend CraftItem with Card)
    package questiontester;
    public class Test {
    public static void main(String args[]) {
    // creating a new object instance with default values
    // values 123456 and 1.5 could also have been set here
    CraftItem defaultItem = new CraftItem("000000",0.0);
    // calling the toString() method to display the text
    // this should display defaultItem with its initial values
    System.out.println(defaultItem.toString());
    // setting the item code to 123456
    // this overrides the initial String value of defaultItem
    defaultItem.setItemCode("123456");
    // setting the price to 1.5
    // this overrides the initial double value of defaultItem
    defaultItem.setPrice(1.5);
    // calling the toString() method to display the text
    // this should now show defaultItem with its new values
    System.out.println(defaultItem.toString());
    // test to check whether getter methods work
    System.out.println(defaultItem.getItemCode());
    System.out.println(defaultItem.getPrice());
    // test to see that setters work for additional items
    CraftItem anotherItem = new CraftItem("000000",0.0);
    anotherItem.setItemCode("345345");
    anotherItem.setPrice(0.5);
    System.out.println(anotherItem.toString());
    As I say, I'm not sure how to resolve the Error#: 300 so any advice on how to do this would be greatly appreciated.
    Cheers - Nic

    Here's my updated code - I'll repost the Test and CraftItem code too:
    Card.java
    package questiontester;
    public class Card extends CraftItem {
      // instance variables
      private String cardType;
      private String cardSize;
      private String itemCode;
      private double price;
      // Constructor
      public Card(String cardTypeValue, String cardSizeValue) {
            super(itemCodeValue, itemPriceValue);
            cardType = cardTypeValue;
            cardSize = cardSizeValue;
    // methods
    CraftItem.java
    package questiontester;
    public class CraftItem {
      // instance variables
      public String itemCode;
      public double price;
      // constructor
      public CraftItem(String itemCodeValue, double itemPriceValue){
        itemCode = itemCodeValue;
        price = itemPriceValue;
      // getter for itemCode
      public String getItemCode() {
        return itemCode;
      // getter for price
      public double getPrice() {
        return price;
      // setter for itemCode
      public void setItemCode(String itemCodeValue) {
        itemCode = itemCodeValue;
      // setter for price
      public void setPrice(double itemPriceValue) {
        price = itemPriceValue;
      // toString() value
      public String toString() {
        return "Item code is " + itemCode + " and costs " + price + " pounds.";
    Test.java
    package questiontester;
    public class Test {
      public static void main(String args[]) {
        // creating a new object instance with default values
        // values 123456 and 1.5 could also have been set here
        CraftItem defaultItem = new CraftItem("000000",0.0);
        // calling the toString() method to display the text
        // this should display defaultItem with its initial values
        System.out.println(defaultItem.toString());
        // setting the item code to 123456
        // this overrides the initial String value of defaultItem
        defaultItem.setItemCode("123456");
        // setting the price to 1.5
        // this overrides the initial double value of defaultItem
        defaultItem.setPrice(1.5);
        // calling the toString() method to display the text
        // this should now show defaultItem with its new values
        System.out.println(defaultItem.toString());
        // test to check whether getter methods work
        System.out.println(defaultItem.getItemCode());
        System.out.println(defaultItem.getPrice());
        // test to see that setters work for additional items
        CraftItem anotherItem = new CraftItem("000000",0.0);
        anotherItem.setItemCode("345345");
        anotherItem.setPrice(0.5);
        System.out.println(anotherItem.toString());
    Update
    I've removed the void and the original error#: 300 message has gone, replaced by the following two:
    "Card.java": Error #: 300 : variable itemCodeValue not found in class questiontester.Card at line 14, column 15
    "Card.java": Error #: 300 : variable itemPriceValue not found in class questiontester.Card at line 14, column 30

  • Inheritance Question part 2

    class ClassA
    public void sayHelloInA() { System.out.println("Hello in class A"); }
    public void show() { System.out.println("Show in ClassA"); }
    class ClassB extends ClassA
    public void sayHelloInB() { System.out.println("Hello in class B"); }
    public void show() { System.out.println("Show in ClassB"); }
    public class Test
    public static void main(String[] args)
    ClassA c = new ClassB();
    c.sayHelloInB();
    c.show();
    Why c.sayHelloInB() does not compile but c.show() compiles and runs (which displays "Show in ClassB")

    Russell53 wrote:
    Why c.sayHelloInB() does not compile but c.show() compiles and runs (which displays "Show in ClassB")The answer was already posted in your [previous thread|http://forums.sun.com/thread.jspa?threadID=5372352]. Please continue the discussion there.

Maybe you are looking for