Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default reference variable to JFrame

    when a class extends JFrame and you want to get
    a variable that holds the reference to that JFrame
    is this the way to do that:

    public class Aclass extends JFrame {

    JFrame frame = this;


    }

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: reference variable to JFrame

    I suppose that works, but why do you think you need to do that? Can't you just use this directly? Or not at all?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    It works indeed. You see I set up each menu of an extended text writer application in a different class.
    The file menu class called MenuFileMenu has a method that builds the file menu.
    But I want this class also to have all the opening and saving file logics.
    The MenuFileMenu class has the method getFileName that calls
    FileDialog fd = new FileDialog(frame, title, mode);
    The parent frame is the frame of the principle class that extends JFrame, so a pass a JFrame frame
    through the constructor:

    Java Code:
    public MenuFileMenu(JFrame frame) {
            fileManager = new wwFileManager();
            recentFiles = new Vector(RECENT_FILES);
            this.frame = frame;
        }
    (I still have to get rid of the Vector because it is not used any more)

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: reference variable to JFrame

    I don't really understand what you're doing, but why are you extending JFrame at all? And your original question is about referencing an extended class, not a class attribute with the name frame. I'm confused. Were you asking how to pass the JFrame into your MenuFileMenu() consructor? If so, the this keyword will indeed work.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    Here is the design and as you see the second class extends JFrame to hold all the rest
    of the swing elements:
    1)

    Java Code:
    package willemwriter;
    
    import java.awt.EventQueue;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.WindowConstants;
    
    /**
     *
     * @author willem
     */
    public class Main {
    
       public static void main(String[] args)  {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                   JFrame frame = new wwFrame();
                   frame.setDefaultCloseOperation(
    				        WindowConstants.DO_NOTHING_ON_CLOSE);
                   frame.addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosing(WindowEvent we) {
                            String ObjButtons[] = {"Yes","No"};
                            int PromptResult = JOptionPane.showOptionDialog(null,
                            "Do you realy want to close the window?",
                                    "Willem Writer Application",
                            JOptionPane.DEFAULT_OPTION,
                                            JOptionPane.WARNING_MESSAGE, null,
                            ObjButtons,ObjButtons[1]);
                            if(PromptResult==0) {
                                System.exit(0);
                            }
                       }
                });
               
                frame.setVisible(true);
                }
            });
        }
    }
    2)

    Java Code:
    package willemwriter;
    
    
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    
    
    /**
     *
     * @author willem
     */
    class wwFrame extends JFrame{
        String directory = "";	 // Current directory
        Action menuAction;
        // Recently-used file list
        JMenuItem fileListMenu;
        static final int RECENT_FILES = 4;
        Vector recentFiles;
        wwFileManager fileManager;
    
        public wwFrame() {
            setTitle("Willem Writer");
    
            // screen position and size
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            int width = (int) screenSize.getWidth();
            int height = (int) screenSize.getHeight();
            int canvasWidth = width/2 - 100;
            int canvasHeight = height - 50;
    
            setBackground(Color.GRAY);
            JFrame frame = this;
            MenuFileMenu filemenu = new MenuFileMenu(frame);
            JMenuBar mb = new JMenuBar();
            this.setJMenuBar(mb);
            mb.add(filemenu.buildFileMenu()); // here is the file menu added
    
            setBounds(canvasWidth / 2, 30, canvasWidth,canvasHeight);
            Container contentpane =  getContentPane();
    
            TextCanvas textCanvas = new TextCanvas();
            ToolBar toolbar = new ToolBar();
            contentpane.add(toolbar, BorderLayout.NORTH);
            contentpane.add(textCanvas, BorderLayout.CENTER);
    
    
        }
    }

  6. #6
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    In order to set up the file dialog at the MenuFilemenu class
    I need a ref for the parent frame (first arg):

    Java Code:
    public String getFileName(String title, int mode) {
            FileDialog fd = new FileDialog(frame, title, mode);
            fd.setFile("*.*");
            fd.setDirectory(directory);
            fd.setVisible(true);
            String dir = fd.getDirectory();
            String file = fd.getFile();
            if (dir == null || file == null) {
                return null;
            }
            directory = dir;
            String separator = System.getProperty("file.separator");
            if (dir.endsWith(separator)) {
                return dir + file;
            } else {
                return dir + System.getProperty("file.separator") + file;
            }
        }

  7. #7
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: reference variable to JFrame

    Okay, gotcha. A couple things, if you want them:

    You don't need the extra frame variable. Instead of this:

    Java Code:
    JFrame frame = this;
    MenuFileMenu filemenu = new MenuFileMenu(frame);
    You can just do this:

    Java Code:
    MenuFileMenu filemenu = new MenuFileMenu(this);
    However, you probably shouldn't be extending JFrame in the first place, unless you're overriding one of JFrame's methods (which is unlikely and usually incorrect). Google composition over inheritance for more info.

    And finally, classes should start with uppercase letters.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #8
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,651
    Rep Power
    5

    Default Re: reference variable to JFrame

    But as Kevin said, why are you extending JFrame? What is the interaction between super class and subclass that requires inheritance? I would suggest you use composition.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  9. #9
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: reference variable to JFrame

    Quote Originally Posted by willemjav View Post
    In order to set up the file dialog at the MenuFilemenu class
    I need a ref for the parent frame (first arg):
    FileDialog is an old awt class. You should probably be using JFileChooser instead. JFileChooser can use any Component as a parent, not just a top-level window.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  10. #10
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    I taught that beginning a large application is starting a class which extends JFrame....
    Like playing chess, almost always open with the queens pawn?
    Thanks I will look into all this stuff

  11. #11
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: reference variable to JFrame

    Quote Originally Posted by willemjav View Post
    I taught that beginning a large application is starting a class which extends JFrame....
    Like playing chess, almost always open with the queens pawn?
    Thanks I will look into all this stuff
    This is a rather old way of looking at it. A lot of the older Java tutorials extend JFrame, so the idea persists, but most "modern" tutorials will have you instantiate a JFrame instead of extending it. It's not a huge deal either way, just something to keep in mind.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  12. #12
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    Is this btw an correct model for the menu actions:


    Java Code:
     AbstractAction exitAction = new AbstractAction() {
                {
                    putValue(NAME, "Exit");
                    putValue(MNEMONIC_KEY, new Integer('X'));
                    putValue(SHORT_DESCRIPTION, "Closes the open file and "
                                             + "exits the application");
                    putValue(LONG_DESCRIPTION, "Closing the application");
                }
                public void actionPerformed(ActionEvent evt) {
                    System.exit(0);
                }
            };

  13. #13
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    Okay great that makes sense, since I am studying old manuals like corejava and JFC
    Thank you I will look into "modernizing" stuff.

  14. #14
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,651
    Rep Power
    5

    Default Re: reference variable to JFrame

    Since you already know Java I highly recommend Joshua Bloch's book, Effective Java, v2 (or whatever the lastest version is). It is essentially a best practices book. It is written in such a manner that each "Item" covered in the book is independent of others. So you don't need to read it starting at the beginning.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  15. #15
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    I'll look into that book, great, thanks!

    So this would be a better approach:

    Java Code:
    package willemwriter;
    
    
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    
    
    /**
     *
     * @author willem
     */
    class wwFrame {
        String directory = "";	 // Current directory
        Action menuAction;
        // Recently-used file list
        JMenuItem fileListMenu;
        static final int RECENT_FILES = 4;
        Vector recentFiles;
        wwFileManager fileManager;
    
        public wwFrame() {
            JFrame f = new JFrame();
            f.setTitle("Willem Writer");
    
            // screen position and size
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            int width = (int) screenSize.getWidth();
            int height = (int) screenSize.getHeight();
            int canvasWidth = width/2 - 100;
            int canvasHeight = height - 50;
    
            f.setBackground(Color.GRAY);
            
            MenuFileMenu filemenu = new MenuFileMenu(f);
            JMenuBar mb = new JMenuBar();
            f.setJMenuBar(mb);
            // the build of each menu
            mb.add(filemenu.buildFileMenu());
    
            f.setBounds(canvasWidth / 2, 30, canvasWidth,canvasHeight);
            Container contentpane =  f.getContentPane();
    
            TextCanvas textCanvas = new TextCanvas();
            ToolBar toolbar = new ToolBar();
            contentpane.add(toolbar, BorderLayout.NORTH);
            contentpane.add(textCanvas, BorderLayout.CENTER);
    
    
        }
    }

  16. #16
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,651
    Rep Power
    5

    Default Re: reference variable to JFrame

    Yes! But you don't need to get the content pane. The add method puts it there for you. And has already been stated, class names by convention begin with uppercase letters.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  17. #17
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    Instead of:
    Container contentpane = f.getContentPane();
    TextCanvas textCanvas = new TextCanvas();
    ToolBar toolbar = new ToolBar();
    contentpane.add(toolbar, BorderLayout.NORTH);
    contentpane.add(textCanvas, BorderLayout.CENTER);


    You mean this 1):
    f.add(toolbar, BorderLayout.NORTH);
    f.add(textCanvas, BorderLayout.CENTER);

    or this 2):
    f.getContentPane().add(toolbar, BorderLayout.NORTH);
    f.getContentPane().add(textCanvas, BorderLayout.CENTER);

  18. #18
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default Re: reference variable to JFrame

    Either one does the same thing. The JFrame.add() and related methods all just refer to the content pane behind the scenes. Check out the API for more info: JFrame (Java Platform SE 7 )
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  19. #19
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: reference variable to JFrame

    wow, I learned that differently!

  20. #20
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,050
    Rep Power
    6

    Default Re: reference variable to JFrame

    Quote Originally Posted by KevinWorkman View Post
    This is a rather old way of looking at it. A lot of the older Java tutorials extend JFrame, so the idea persists, but most "modern" tutorials will have you instantiate a JFrame instead of extending it. It's not a huge deal either way, just something to keep in mind.
    To be honest I did that too and I would still do it. When I use Swing I will have classes that represent the main application window and I will have classes that represent dialogs in the application; I like them to be of the "is-a" type, so for example MainAppGui or whatever I will call it will be a JFrame that sets itself up the way I want according to standard repeatable programming conventions I applied for myself for Swing applications. To this class I will add methods in which I can (safely) manipulate the JFrame itself.

    Of course that has a huge downside: autocompletion will also list all the methods of JFrame and up, so it might be a little more cumbersome to find the methods I added myself. That problem resolved itself in the end because I always have the same conventions and so could memorize the methods.

    To each his/her own, I'm not going to say what is bad and what is good. I have the same sentiment about extending Thread or not.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Page 1 of 2 12 LastLast

Similar Threads

  1. Reference Variable
    By shaunythesheep in forum New To Java
    Replies: 4
    Last Post: 12-18-2013, 05:48 PM
  2. Checking if a reference variable is empty.
    By BigBlueBuffalo in forum New To Java
    Replies: 11
    Last Post: 04-09-2013, 10:14 AM
  3. reference variable or an attribute value
    By agater in forum New To Java
    Replies: 1
    Last Post: 04-23-2012, 11:49 AM
  4. Reference variable
    By lala in forum New To Java
    Replies: 2
    Last Post: 02-03-2011, 07:27 PM
  5. static variable /pass by reference
    By katturv in forum New To Java
    Replies: 15
    Last Post: 10-03-2010, 08:17 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •