Extending JFrame to a subclass and testing it

I am following an example in my textbook that goes like this:
package project2;
import javax.swing.JFrame;
class PracticeWithJFrame2 extends JFrame
     private static final int FRAME_WIDTH=300;
     private static final int FRAME_HEIGHT=200;
     private static final int FRAME_X_ORIGIN=150;
     private static final int FRAME_Y_ORIGIN=250;
     public PracticeWithJFrame2()
          // set the frame default properties
          setTitle("My First Subclass");
          setSize(FRAME_WIDTH, FRAME_HEIGHT);
          setLocation(FRAME_X_ORIGIN,FRAME_Y_ORIGIN);
          // register 'Exit upon closing' as a default close operation
          setDefaultCloseOperation(EXIT_ON_CLOSE);
}in the testing class:
package project2;
class TestPracticeJFrameClass {
      * @param args
     public static void main(String[] args) {
          PracticeWithJFrame2 myFrame;
          myFrame = new PracticeWithJFrame2();
          myFrame.setVisible(true);
}2 errors are ocurring:
1) Multiple markers at this line
     - The serializable class PracticeWithJFrame2 does not declare a static final
      serialVersionUID field of type long
     - The type PracticeWithJFrame2 is already defined2) the test case brings up a JFrame window, but it is basically an empty window, it didn't take on the values the constructor set for it.
Thanks for some debugging help

I'll get back to you in a moment, in the meantime I've got a work around solution. I did the testing/application in a single class, by calling the constructor in the main method:
package project2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Ch14JButtonEvents extends JFrame
     private static final int FRAME_WIDTH=300;
     private static final int FRAME_HEIGHT=200;
     private static final int FRAME_X_ORIGIN=150;
     private static final int FRAME_Y_ORIGIN=250;
     private static final int BUTTON_WIDTH=80;
     private static final int BUTTON_HEIGHT=30;
     private JButton cancelButton;
     private JButton okButton;
     public static void main(String[] args)
          PracticeWithJButton frame = new PracticeWithJButton();
          frame.setVisible(true);
     public Ch14JButtonEvents()
          Container contentPane = getContentPane();
          // set the frame default properties
          setTitle("Program PracticeWithJButton");
          setResizable(false);
          setSize(FRAME_WIDTH, FRAME_HEIGHT);
          setLocation(FRAME_X_ORIGIN,FRAME_Y_ORIGIN);
          // set the layout manager
          contentPane.setLayout(new FlowLayout());
          // create and place two buttons on the frame's content pane
          okButton = new JButton("OK");
          okButton.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
          contentPane.add(okButton);
          cancelButton = new JButton("CANCEL");
          cancelButton.setSize(BUTTON_WIDTH, BUTTON_HEIGHT);
          contentPane.add(cancelButton);
          // register 'Exit upon closing' as a default close operation
          setDefaultCloseOperation(EXIT_ON_CLOSE);
}

Similar Messages

  • Pros & cons of extending jframe or adding it

    Hi i've written a class code that extends jframe (and is my main code for the application) now i see that many code examples (such as the divelog.java posted on java.sun) prefer adding a jframe to the class and .pack & .setvisible
    beside code comfort (either way) is there a real reason to prefer one way over the other ?
    thanks .

    yes. always favour composition over inheritance. class inheritance is one of the most abused features of the language, I have to struggle with inappropriate use of it on a daily basis because we've got a team of morons who think it's ok to extend a class twelve times, just to change the order in which some buttons get displayed on-screen. that's not an exaggeration, at all
    extend classes when the subclass really is an extension of the superclass, really is a kind-of JFrame or whatever. not just to re-use some methods and save some typing. hint: JFrame is a Container,which means it was intended to contain other UI objects. thus, by adding widgets to it, you are making use of it as intended, not making a new kind of JFrame

  • Adding a JPanel from one class to another Class (which extends JFrame)

    Hi everyone,
    So hopefully I go about this right, and I can figure out what I'm doing wrong here. As an exercise, I'm trying to write a Tic-Tac-Toe (TTT) game. However, in the end it will be adaptable for different variations of TTT, so it's broken up some. I have a TTTGame.java, and TTTSquareFrame.java, and some others that aren't relavent.
    So, TTTGame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              addPanel = startSimple();
              if(!addPanel.isValid())
                   System.out.println("Something's wrong");
              contents.add(addPanel);
              setSize(300, 300);
              setVisible(true);
         public JPanel startSimple()
              mainSquare = new TTTSquareFrame(sides);
              mainSquarePanel = mainSquare.createPanel(sides);
              return mainSquarePanel;
    }and TTTSquareFrame:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import joshPack.jUtil.Misc;
    public class TTTSquareFrame
         private JPanel squarePanel;
         private JButton [] squares;
         private int square, index;
         public TTTSquareFrame()
              System.out.println("Use a constructor that passes an integer specifying the size of the square please.");
              System.exit(0);
         public TTTSquareFrame(int size)
         public JPanel createPanel(int size)
              square = (int)Math.pow(size, 2);
              squarePanel = new JPanel();
              squarePanel.setLayout(new GridLayout(3,3));
              squares = new JButton[square];
              System.out.println(MIN_SIZE.toString());
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setRolloverEnabled(false);
                   squares[i].addActionListener(bh);
                   //squares[i].setMinimumSize(MIN_SIZE);
                   squares[i].setVisible(true);
                   squarePanel.add(squares[i]);
              squarePanel.setSize(100, 100);
              squarePanel.setVisible(true);
              return squarePanel;
    }I've successfully added panels to JFrame within the same class, and this is the first time I'm modularizing the code this way. The issue is that the frame comes up blank, and I get the message "Something's wrong" and it says the addPanel is invalid. Originally, the panel creation was in the constructor for TTTSquareFrame, and I just added the mainSquare (from TTTGame class) to the content pane, when that didn't work, I tried going about it this way. Not exactly sure why I wouldn't be able to add the panel from another class, any help is greatly appreciated.
    I did try and cut out code that wasn't needed, if it's still too much let me know and I can try and whittle it down more. Thanks.

    Yea, sorry 'bout that, I just cut out the parts of the files that weren't relevant but forgot to compile it just to make sure I hadn't left any remnants of what I had removed. For whatever it's worth, I have no idea what changed, but something did and it is working now. Thanks for your help, maybe next time I'll post an actual question that doesn't somehow magically solve itself.
    EDIT: Actually, sorry, I've got the panel working now, but it's tiny. I've set the minimum size, and I've set the size of the panel, so...why won't it respond to that? It almost looks like it's being compressed into the top of the panel, but I'm not sure why.
    I've compressed the code into:
    TTTGame.java:
    import java.awt.*;
    import javax.swing.*;
    public class TTTGame extends JFrame
         private Integer sides = 3;
         private TTTSquareFrame mainSquare;
         private TTTGame newGame;
         private Container contents;
         private JPanel mainSquarePanel, addPanel;
         public static void main(String [] args)
              TTTGame newGame = new TTTGame();
              newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TTTGame()
              super("Tic-Tac-Toe");
              contents = getContentPane();
              contents.setLayout(new FlowLayout());
              mainSquare = new TTTSquareFrame(sides.intValue());
              contents.add(mainSquare);
              setSize(400, 400);
              setVisible(true);
    }TTTSquareFrame.java
    import java.awt.*;
    import javax.swing.*;
    public class TTTSquareFrame extends JPanel
         private JButton [] squares;
         private int square, index;
         private final Dimension testSize = new Dimension(50, 50);
         public TTTSquareFrame(int size)
              super();
              square = (int)Math.pow(size, 2);
              super.setLayout(new GridLayout(size, size));
              squares = new JButton[square];
              for(int i = 0; i < square; i++)
                   squares[i] = new JButton();
                   squares.setMinimumSize(testSize);
                   squares[i].setVisible(true);
                   super.add(squares[i]);
              setSize(200, 200);
              setVisible(true);
    I've made sure the buttons are smaller than the size of the panel, and the panel is smaller than the frame, so...
    Message was edited by:
    macman104

  • Decorate window of class extending JFrame

    Hello,
    I have a class that extends JFrame and I'd like to set it's look decorated the same way that it does when a new JFrame is built inside the code. Currently it's got the regular Java look (if I create a JFrame somewhere in the code it has the look I want), the following code didn't help, it only sets the subsequently created JFrames decorated:
        GUI frame = new GUI(); //GUI extends JFrame
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
        frame.setDefaultLookAndFeelDecorated(true);

    Thanks for your reply. I already read that, in fact the section "Programmatically Setting the Look and Feel " instructs to write the code I posted on the previous post. I also tried:
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    SwingUtilities.updateComponentTreeUI(this);And it didn't work. The main frame has the regular LNF and subsequently created JFrames will have the javax.swing.plaf.metal.MetalLookAndFeel
    Also, after the code I posted on my previous post, GUI.isDefaultLookAndFeelDecorated() returns true.
    Thanx in advance! :)

  • Which is better? Extend JFrame or Wrap it in a class???

    Just a random thought, have been programming swing for a long time now and during the time have been researhed a lot of swing examples on web and found out that most people tend to make a class extend JFrame in order to use it stuff.
    However the way i've been programming is to wrap it around a class by creating an instance of JFrame inside my class. In that way i feel is more easier to program.
    But which is better style of programming and which is better programming technique in terms of robustness, reusablitity & good general programming practice?

    The usual answer, it depends. If you don't want to change a JFrame's behaviour, you wrap it. If the JFrame class is lacking a feature you need, you extend it and implement the desired feature.

  • Tds cycle mapping and testing

    hi,
    i have the problem regarding to the tds cycle,so pls inform about the total process of 'TDS CYCLE-MAPPING AND TESTING'
    REGARDS
    JANA

    hai,
    the following is the process to get the TDS certificate
    TDS Certificate
    1.EWT-Basic Settings-Check Recipient type-In-WHTYPE-Rectype-Text
    1.Extended WHT – Basic Setting-india-define business place- 1000
    Enter 1000 as business place and enter description and fill address coloumn.
    Assign Business Place to Country Calendar and Day After
    Define Section code as 1000 and assign business place and fill address coloumn
    Company
    Leave on row as blank
    Enter TDS circle
    Enter TDS No of the company in Search Term ½ and after fillup the address and save it
    Extended WHT – Posting – Certificate numbering for WHT
    1.     Define Numbering Class
    2.     Define Numbering Group
    3.     Define Number Ranges
    4.     Assign numbering Group Numbering class
    1.Extended WHT – Posting-India- Remittance Challan- Document Type
    2.Maintain Number Group
    Company code – Business Area – WHT Type – Number Group
    3.Maintain Number Range for 1,2,3,4,5 under----- text number range from 10001-99999
    4.     Assign number range to number group 1-01,2-01,03-01,4-01,5-01
    WHT tax certificate for Vendor & Customers
    1.     Maintain Number Group and SAP script forms
    Company code/Business Place/Offtake Key/form/No.Group
    2.Maintain Number Range – 2007 – 0001 -1000
    3. Assign Number range to number groups
    1-01,2-02 etc.
    Pls assign points if it is useful.
    Govind.

  • Invoke a panel object in a class which extends JFrame

    I have a class LoginUI which extends JFrame and another class NewUserUI which extends JPanel. The LoginUI contains a button which when clicked should display the NewUserUI panel in a separate window. How should I invoke the NewUserUI object in the LoginUI class?

    One possibility would be the use of a JOptionPane containing the JPanel.
    Cheers
    DB

  • TOBJ entries missing from upgrade dev and test systems

    Hi,
    We are in the process of ECC Upgrade from 4.7 to ECC 6.0 and upgraded our dev and test systems. We missing some SAP defined object entries in TOBJ table from dev and test. Because of this some of the roles getting transport errors if the roles contain those missing objects. We tried to transport the missing entries but we don't see any provision for that. Does any one through an idea to move those missing entries from dev to test. Not sure we will get same error in production. This table updates during upgrade and may be we missed some thing in test as though we followed the same upgrade process for both systems.
    Thank you
    Venkat

    Possibly you are no longer licensed for components which these objects are called from in their concepts.
    In that case the ability to start the component objects should be removed as well.
    Of course if some Z-programs checked these objects or SAP's own "package concept" extended syntax checks did not respect them then you might have problems.
    This should normally only apply to manual authorization instances, as if you had upgraded the roles and regenerated them, then you would not have this problem (in the roles).
    It tells us something about how you or someone else without any training have built these roles (or subsequently mucked them up...)...
    When reading stuff like this, I am always of two minds...
    1) SAP should make the concepts simpler and more intuitive to use without "cowboy" activities allowed by users with SAP_ALL etc.
    2) Customers should bleed for their own sins for not training people appropriatly (here, faking CV's is also ma major pest!).
    It is always a bit of a cat & mouse game and ends up in forums such as SDN in the long run.
    Some of it might also have become "available" to be used by SAP (I believe it was the 6.20 upgrade which installed everything...).
    Real bugger. I would accept it and test as best you can. You can also compare "where.used-lists" and "code scans" before and after the upgrade to see whether it is used by foreign repository objects.
    The scan is more reliable here, as sometimes the object name itself is a variable from a data declaration or condition which you cannot see in the "procedural" code.
    Cheers,
    Julius

  • Why we extend JFrame in java swings? how is it different from code not ...?

    how is it different from code nt extending JFrame?
    please explain the role of contentpane in both cases?
    thanx

    Search the net for examples and/or explanations of "inheritance vs composition.
    For the role of a contentPane, read the API for interface RootPaneContainer and class JRootPane. The second named API also has a link to the Swing tutorial on How to Use Root Panes.
    db

  • How to compile and test SIM card applet

    Dear all
    I have a sample applet:
    package sim.access.sample;
    import sim.access.*;
    public final class helloFile extends Applet implements ToolkitInterface
           private static SIMView  theGsmApplet;
           private static USIMView aUsimApplet;
           private static AID theGSMAppletAID;
           private static AID theUSIMAppletAID;
           private static final byte[]  baGSMAID = {(byte)0xA0,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x09,(byte)0x00,(byte)0x01};
           protected helloFile(){
           public MyApplet () {
                theGSMAppletAID = new AID();
                // get a reference to the GSM interface
                theGsmApplet = SIMSystem.getTheSIMView(theGSMAppletAID);
           public void doSomethingWithAFile(){
                   // returns the SIMView of the currently selected Applet
                   // allows to implement services that are depend on specific
                   // file in GSM or USIM application as well as to implement
                   // technolgie independent applets.
                   SIMView theView = SIMSystem.getTheSIMView();
                   if(theView instanceof SIMView){
                        // do something with a GSM file
                   else if(theView instanceof USIMView) {
                        //do something with a USIM specific file
                   // Or request a View to a specific application
                   USIMView theView = SIMSystem.getTheSIMView(aUSIMAppletAID);
    }I want to compile and test it, how can i do it ???

    I am trying to compile it on eclipse using JCOP:
    package mytest;
    import sim.toolkit.ToolkitException;
    import sim.toolkit.ToolkitInterface;
    import javacard.framework.APDU;
    import javacard.framework.Applet;
    import javacard.framework.ISO7816;
    import javacard.framework.ISOException;
    public class Test extends Applet implements ToolkitInterface{
         public static void install(byte[] bArray, short bOffset, byte bLength) {
              // GP-compliant JavaCard applet registration
              new Test().register(bArray, (short) (bOffset + 1), bArray[bOffset]);
         public void process(APDU apdu) {
              // Good practice: Return 9000 on SELECT
              if (selectingApplet()) {
                   return;
              byte[] buf = apdu.getBuffer();
              switch (buf[ISO7816.OFFSET_INS]) {
              case (byte) 0x00:
                   break;
              default:
                   // good practice: If you don't know the INStruction, say so:
                   ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
         public void processToolkit(byte arg0) throws ToolkitException {
              // TODO Auto-generated method stub
    }It is giving following error on package name:
    resolving constant-pool of clazz Lmytest/Test; failed: missing export file for package sim/toolkit

  • Why we extends JFrame class in java

    Hello Java Developers,
    I am new to Java & Currently I am trying my hands on Java Swings.
    I wrote a very simple program in Java to display a JFrame on screen. My code is as follows:
    import javax.swing.*;
    public class JavaFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    I saw some examples on internet & they are extending "JFrame" in their every example. I want to know what is the benefit of this ??? here is code:
    import javax.swing.*;
    public class JavaFrame extends JFrame {
    public static void main(String args[]){
    JFrame frame = new JFrame();
    frame.setTitle("My Frame");
    frame.setSize(400, 150);
    frame.setLocation(300, 300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    My second question is what is the meaning of line "frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);"
    frame - This object of class created by me.
    setDefaultCloseOperation() - This is predefined method in JFrame class.
    JFrame.EXIT_ON_CLOSE - what is the meaning of this ??

    I saw in JFrame API as you suggested & I found that
    EXIT_ON_CLOSE is an "public static final" method.Look again. It's not a method.
    final: this mehod must be executed
    am I right ???No. final means that the value cannot be reassigned.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • Japplet is not able to call a class that extends JFrame in internet Explore

    Hi
    I am doing an application on Japplet.The Japplet class calls anathor class which extends JFrame.When I am running this appication on Applet Viewer it works fine.but when I am running this aplication in internet Explorer the Frame window doesn't come.What might be the problem.
    Thanks
    Srikants

    There is no error or exceptio comming when i am running that application on Internet Explorer.Convert the html page to use the object tag instead of the applet tag.
    The IE build in jre (called msjvm) cannot display JFrame since the version is
    1.1.2 and it has no javax classes.
    Still problems?
    A Full trace might help us out:
    http://forum.java.sun.com/thread.jspa?threadID=656028

  • Getting grid layout to work with a class that extends JFrame

    In my code, I have a class extending JFrame and setting the layout to grid works and the code to add with three parameters compiles just fine but when I run it I get this:
    java.lang.IllegalArgumentException: illegal component position
         at java.awt.Container.addImpl(Container.java:999)
         at java.awt.Container.add(Container.java:928)
         at javax.swing.JFrame.addImpl(JFrame.java:479)
         at java.awt.Container.add(Container.java:928)
    on the add(myLabel, 1, 1); line

    I see on these from
    http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Container.html#add(java.awt.Component)
    1.public Component add(Component comp)
    2.public Component add(String name, Component comp)
    3.public Component add(Component comp, int index)
    you should use method add(...) of JPanel instead

  • Retrieve method from class which extends JFrame

    hi, i need some help with my program.
    I have two class which both extends JFrame. The first class called security class and second class is available class.
    In the SECURITY class, i create a button to operate the AVAILABLE class and it generate a result in method Count(). I want to view the result in Frame SECURITY by calling method count() but i could manage to do it. Could somebody help me how to manage this problem?
    Thanks.

    may be you could create a instance of the class you wanted to access method from or pass the instance from one class to another.
    like this:
    public class A extends JFrame
    public B newB= new B();
    public A(){}
    public void someMethod()
    newB.someOtherMethod();
    public class B extends JFrame
    public B(){}
    public void someOtherMethod()
    i hope it is what you are looking for

  • Extending JFrame

    Hi Everyone, I want to create my own utility class named as MyJFrame which will extend the JFrame, so that I can extend MyJFrame instead of JFrame while creating any application. My application will not use the JFrame, instead it will use the MyJFrame, but still I should be able to do all the things which we generally do while developing any application using JFrame.
    I want to do this because I want to provide some more operations to a application developer along with the JFrame.
    To achieve this what are the things I will have to do? If you have any idea about doing this, please guide me.
    Thanks and Regards.

    nikhil_shravane wrote:
    one of them may be MyJFrame extends JFrame, but still no idea what to do further so that MyJFrame will have all the behaviors of JFrame. ?
    suggest me other ideas also.If your class extends JFrame, it will automatically have all of the "behaviors" of JFrame. What functionality do you think you will lose by extending the class? You are being very vague in your question; please provide a specific question or concern or you might not get much help.
    As Encephalopathic says, many people will advise you not to extend JFrame at all, telling you to google [Composition vs. Inheritance|http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html]. However if you really insist on going the "inheritance" route, I'd suggest extending JRootPane as opposed to JFrame. JRootPane provides all of the functionality you really use in an appliction (menu bar, manages the content pane, glass pane, etc.), and extending and using it as your base class for a generic "application" would allow you to shove your "application base" into JApplets as well as JFrames.

Maybe you are looking for

  • Cannot update iTunes after upgrading to Lion

    After installing Lion on two machines - a new MacBook Pro and a year old iMac - I get a 'The update "iTunes" can't be installed' 'An unexpected error has occurred'. When trying to update iTunes. The error happens during the Cleaning Up step.

  • External monitor doesn't work.

    hello, please look into my situation. i finally got the apple mini-dvi to dvi convertor, got a generic dvd-to-vga convertor and after removing 4 wires from it for which there is no space in the apple dvi output, i hooked up the sony sdm-hs75 display

  • Creating a Different Movie Folder for Apple TV

    I have a lot of family movies that I've shot, edited and sent to my itunes library. All of these are in the Movies folder in itunes. I would like to be able to segragate my family movies in itunes from my other movies. When I Cntr click/get info/opti

  • Removed photos from internal hard drive (iPhoto), but it also removed from my external hard drive (iPhoto). HELP!!

    I just bought a new external hard drive (Seagate) to move my numerous photos in iPhoto off my iMac. Set the EHD up to work on both Mac & PC. When I removed some of the photos in the iPhoto library on my internal drive it also removed them from the EH

  • Alert inbox in RWB

    Hi, whenever i executed a program of RSALERTTEST, testing alerting message was sent by executing RSALERTTEST with alerting category i define by ALRTCATDEF to alert inbox in rwb as well. but i made deliberate receiver determination error, then i could