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.

Similar Messages

  • Extends JFrame or extends JPanel ?

    Hi!
    I'd like to do a full screen animation but I don't know which Swing component to subclass to be able to paint the animation. Which is better:
    extends JFrame implements Runnable
    or
    extends JPanel implements Runnable
    Regards

    Do you mean full-screen exclusive mode: http://java.sun.com/docs/books/tutorial/extra/fullscreen/index.html
    In that case, you usually subclass java.awt.Window if you are doing active rendering, since Swing features
    like double buffering just get in the way.

  • Hi All, which is better while creating an object

    Hi All, which is better while creating an object,
    for ex:
    public class Joe {
    public void disp() {
    System.out.println("Joe.disp");
    (1) Joe j = new Joe();
    j.disp();
    (2) new Joe().disp();
    of course, both are equal, which is better in performance perspective

    I suggest you just write code and when the assignment is done, AND you have a performance issue, only then try to improve things. The question you're asking now is likely of no relevance to the performance of you application.
    You can run your application through a profiler to see what specific part of it is consuming (too) much memory.

  • 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

  • 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

  • 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

  • Which is better poower supply or recharge??

    which is better while i'm using my Mac : to put the power supply even if the battery is full or recharge every time the battery dies and remove the power supply??

    There's nothing wrong with running from the AC adaptor. You cannot overcharge the battery nor will it cause any battery memory effects.
    About Batteries in Modern Apple Laptops
    Apple - Batteries - Notebooks
    Extending the Life of Your Laptop Battery
    Apple - Batteries
    Determining Battery Cycle Count
    Calibrating your computer's battery for best performance
    Battery University

  • Which is better, Double Buffering 1, or Double Buffering 2??

    Hi,
    I came across a book that uses a completely different approach to double buffering. I use this method:
    private Graphics dbg;
    private Image dbImage;
    public void update() {
      if (dbImage == null) {
        dbImage = createImage(this.getSize().width, this.getSize().height);
        dbg = dbImage.getGraphics();
      dbg.setColor(this.getBackground());
      dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
      dbg.setColor(this.getForeground());
      paint(dbg);
      g.drawImage(dbImage, 0, 0, this);
    }that was my method for double buffering, and this is the books method:
    import java.awt.*;
    public class DB extends Canvas {
         private Image[] backing = new Image[2];
         private int imageToDraw = 0;
         private int imageNotDraw = 1;
         public void update(Graphics g) {
              paint(g);
         public synchronized void paint(Graphics g) {
              g.drawImage(backing[imageToDraw], 0, 0, this);
         public void addNotify() {
              super.addNotify();
              backing[0] = createImage(400, 400);
              backing[1] = createImage(400, 400);
              setSize(400, 400);
              new Thread(
                   new Runnable() {
                        private int direction = 1;
                        private int position = 0;
                        public void run() {
                             while (true) {
                                  try {
                                       Thread.sleep(10);
                                  }catch (InterruptedException ex) {
                                  Graphics g = backing[imageNotDraw].getGraphics();
                                  g.clearRect(0, 0, 400, 400);
                                                    g.setColor(Color.black);
                                  g.drawOval(position, 200 - position, 400 - (2 * position), 72 * position);
                                  synchronized (DB.this) {
                                       int temp = imageNotDraw;
                                       imageNotDraw = imageToDraw;
                                       imageToDraw = temp;
                                  position += direction;
                                  if (position > 199) {
                                       direction = -1;
                                  }else if (position < 1) {
                                       direction = 1;
                                  repaint();
              ).start();
         public static void main(String args[]) {
              Frame f = new Frame("Double Buffering");
              f.add(new DB(), BorderLayout.CENTER);
              f.pack();
              f.show();
    }which is better? I noticed smoother animation with the later method.
    Is there no difference? Or is it just a figment of my imagination??

    To be fair if you download an applet all the class files are stored in your .jpi_cache, and depending on how that game requests its graphics sometimes they are stored there to, so really if you have to download an applet game twice, blame the programmer (I've probably got that dead wrong :B ).
    But, what's wrong with Jars. They offer so much more.
    No offence meant by this Malohkan but if you can't organize your downloaded files the internet must really be a landmine for you :)
    Personally I'd be happy if I never seen another applet again, it seems java is tied to this legacy, and to the average computer user it seems that is all java is capable of.
    Admitidly there are some very funky applets out here using lots of way over my head funky pixel tricks, but they would look so much better running full screen and offline.

  • Which is better? Photoshop CS6 or Elements? And why?

    Wife is an avid photographer and likes to be able to fix photos, make collages.  Confused on which is better, Photoshop CS6 (and what is Extended?) or Elements? What are the pros and cons of each? Thank you for your time.

    The Photoshop & Elements users hang out in those software forums.  You should post there.  This area is for MBP technical problems. 

  • Which Is Better Time Machine or Backup

    So I just got a new iMac plus a 1T external drive. I have been using backup on my old mini-mac with an external drive plus I used the drive for iTunes and iPhoto. So which is better TM or the old backup (which I had no problems with). I really do not do a lot on the iMac, no work just iLife stuff.
    If I use TM can I partition the 1T to use one 500 GB for TM and another 500 GB for any odds and ends I simply want to store there (I plan to convert old videos to digital)?
    Thanks

    Hi! The drive for a bootable clone should be the same size as the internal main drive as should be the drive for TM. To create a bootable clone you can use the disk utility but I prefer SUPERDUPER and if you pay the 27.95 you get the ability to schedule auto backups! Tom
    To use the disk utility: Kappy's method
    How to Clone Using Restore Option of Disk Utility
    1. Open Disk Utility from the Utilities folder.
    2. Select the backup or destination volume from the left side list.
    3. Click on the Erase tab in the DU main window. Set the format type to Mac OS Extended (journaled, if available) and click on the Erase button. This step can be skipped if the destination has already been freshly erased.
    4. Click on the Restore tab in the DU main window.
    5. Select the backup or destination volume from the left side list and drag it to the Destination entry field.
    6. Select the startup or source volume from the left side list and drag it to the Source entry field.
    7. Double-check you got it right, then click on the Restore button.
    8. Select the destination drive on the Desktop and press COMMAND-I to open the Get Info window. At the bottom in the Ownership and Permissions section be sure the box labeled "Ignore Permissions on this Volume" is unchecked. Verify the settings for Ownership and Permissions as follows: Owner=system with read/write; Group=admin with read/write; Other with read-only. If they are not correct then reset them.
    For added precaution you can boot into safe mode before doing the clone.
    Message was edited by: Thomas Bryant

  • Refurb 13inch 2012 OR Refurb 15inch 2011 which is better?Is refurb really worth it?THOUGHTS ON REFURBISHED MBP

    hey folks i am planing to buy a macbook pro after saving cash since the past 6years i want you all to help me with which product i should go for
    i am 17 and need a good laptop which will last me another 5years..... i have been thinking about a refurb macbook pro 2012 13inch 2.9 i7dual core which is for about 1260 and another one refurb macbook pro 2011 15inch 2.2  i7 quad core which is again for 1350.....i would want to know which is a better option as price wise both are very close and if is the 15inch worth it and better as the 2011 does not have the usb3.0 and bluetooth 4.0 and its sandy bridge but again its quad core where as the 13inch 2012 has all the stuff but its dual core.... what is the difference between quad and dual core?....and i would want to know your thoughts on the refurb models as i said its importamt for me to spend my money wisely since i have been saving for the past 6years....does the refurb mbp as good as new?can they have cosmetic damages?is the outter shell and body replaced?and do they come with new parts and accesories? and is it like a second hand laptop which is used for a year or few months and then returnded and sold again as refurb? please let me know which is better and long lasting or else shall i go for a new one...cause if i buy a refurb mbp and the apple protection care plan the total cost is as much as a new mbp so is it better to buy a new mbp and not buy the apple protection  plan? PLEASE HELP ME OUT
    Thanks for your time
    Toodles
    Links of the models:
    http://store.apple.com/us/product/FD318LL/A/refurbished-macbook-pro-22ghz-quad-c ore-intel-i7#overview
    http://store.apple.com/us/product/FD102LL/A/refurbished-macbook-pro-29ghz-dual-c ore-intel-i7
    ps: is a 128gb solid state drive worth replacing the 500gb or 750gb serial ata

    USB 3 vs USB 2 -> the importance of USB 3 depends on how much you use an external drive to read/write large files or large numbers of files. I once did extensive testing with USB 2 vs FireWire 400 & 800 with TimeMachine. It was no surprise that performing a complete backup with FireWire was significantly faster than with USB (or even a large backup such as after installing an OS update). But for those hourly (or even daily) backups the difference wasn't all that significant. Exporting a large number of photos or an iMovie to FireWire was significantly faster. Copying a copy word processor files it was almost impossible to accurate time the difference. For some the USB3 ports are a big deal. For me, not at all because I'm heavily invested in FireWire drives.
    BlueTooth 4? Frankly, I can't say because the only thing I use BT for is my keyboard and mouse which the older standard is fine for. There are potential advantages - just as with USB3 - the question is whether your current/future needs align to the new standards. Again for me they don't.
    As for the CPU difference - I've already indicated that unless you are doing high processor intensive work (such as 3D modelling or big statistical modeling) either processor has plenty of power. According to the benchmarks my new work iMac runs rings around my work 2009 Core 2 Duo 13" MBP. In my real world use of those two computers I never notice the difference. If I played 3D games on them I would.
    I've already said that all but one of my refurbs looked new and from what I've seen of relatives and friends buying refurbs that runs pretty true. You aren't buying a new computer but on the other hand I've never seen a refurb that looked beat up. Most refurbs are computers that buyers returned within Apple's 14 day buyer's remorse period or were dead on arrival, a new one given to the buyer, and repaired.
    I can't tell you how long a refurb MBP will last - no more than I can tell you how long a new MBP will last. But Apple warrants them for a year and lets you buy an extended warranty just as if they were new. That indicates the confidence Apple has in its refurbs.
    Where do you get the idea that you can only put a 128GB SSD in a 13"? It can handle any standard 2.5" drive and there are plenty of SSDs in that form factor at 256GB and above. Yes an SSD is expensive compared to a standard drive but the speed increase is amazing and not just in booting up the computer. Installing an SSD on my 4.5 year old iMac gave it another year of live. Installing one in my work MBP was like getting a new computer. I wouldn't consider buying a new computer without one.

  • 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

  • 4 different GUI approaches - which is better?

    Hi people!
    Continuing my Java experiments - now with GUI writing.
    I would very much like to know the pros and cons with these 4 different ways to get exactly the same result.
    I'm sure some ways are better than others.
    class ExperimentGUI
        void ExperimentGUI() // Example A
            JFrame content = new JFrame();
            JTextArea textView = new JTextArea();
            textView.setPreferredSize(new Dimension(300,300));
            content.add(textView, BorderLayout.CENTER);
            content.pack();
            content.setLocationRelativeTo(null);
            content.setVisible(true);
    class ExperimentGUI extends JFrame
        void ExperimentGUI() // Example B
            JFrame content = new JFrame();
            JTextArea textView = new JTextArea();
            textView.setPreferredSize(new Dimension(300,300));
            content.add(textView, BorderLayout.CENTER);
            content.pack();
            content.setLocationRelativeTo(null);
            content.setVisible(true);
    class ExperimentGUI
        ExperimentGUI() // Example C
            JFrame content = new JFrame();
            JPanel pane = new JPanel(new BorderLayout());
            JTextArea textView = new JTextArea();
            textView.setPreferredSize(new Dimension(300,300));
            pane.add(textView, BorderLayout.CENTER);
            content.setContentPane(pane);
            content.pack();
            content.setLocationRelativeTo(null);
            content.setVisible(true);
    class ExperimentGUI extends JFrame
        ExperimentGUI() // Example D
            JPanel content = new JPanel(new BorderLayout());
            JTextArea textView = new JTextArea();
            textView.setPreferredSize(new Dimension(300,300));
            content.add(textView, BorderLayout.CENTER);
            setContentPane(content);
            pack();
            setLocationRelativeTo(null);
            setVisible(true);
    }Regards,
    Stefan
    - a newbie

    Be aware that if you declare variable in a local method or constructor, you will have problems with access in other places. Ex:
    import java.awt.*;
    import java.awt.event.*;
    public class ClunkyGui {
    //  private  TextArea ta;  // As oposed to global var
    //  private  Frame    f;   // As oposed to global var
      public ClunkyGui() {
        Frame    f  = new Frame("ClunkGui");
    //    f  = new Frame("ClunkGui");
        TextArea ta = new TextArea(10,20);
    //    ta = new TextArea(10,20);
        Button   b  = new Button("GO!");
        b.addActionListener(new BJActionListener());
        Panel    p  = new Panel();
        p.setLayout(new FlowLayout(FlowLayout.CENTER));
        p.add(b);
        f.add(p,BorderLayout.NORTH);
        f.add(ta);
        f.pack();
        f.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent we) {
            f.dispose(); // <access pblm
            System.exit(0);
        f.setVisible(true);
      private class BJActionListener  implements ActionListener {
        public void actionPerformed(ActionEvent ae) {
          ta.setText("HI!"); // <access pblm
      public static void main(String[] argv) {
        new ClunkyGui();
    }Now you can code around this and should be able to avoid such things, but just be aware of this.
    ~Bill

  • Droplet or Simple Nucleus component which is better ?

    Hi,
    1)Droplet or Simple Nucleus Component which is better as per memory utilization (performence wise).
    2)extending one  Droplet in another droplet is recomended or injecting droplet which is recomended ?
    Please clear these issues if any body ASAP.
    thanks

    Hi,
    Droplets are intended to connect front end (jsps) with the business functionality thro nucleus components. They are primarily used for presentation logic which involves business rules.
    So, you need to decide to go for a mere nucleus component or droplet based on your requirement.
    It is good to have any business logic / common code in a tools class and call that method from the droplet. In this case, you do not need to extend other droplet and can reuse the code from the tools class by injecting the tools component.
    Please let me know if this helps. Or else, please specify the requirements more specifically.
    Hope this helps.
    Keep posting the updates.
    Thanks,
    Gopinath Ramasamy

  • 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

Maybe you are looking for