JFrame v/s JPanel

Hi
I havent understood the JFrame,JPanel hierarchy
of Swing.
I am reading the Swing tutorials but am unable
to get the meaning of this.
If I have understood correctly,JFrame is the
top level container and all components must
be added to this container.Right?
Container c = getContentPane();
So,what is JPanel?
Can someone please guide?

1) So what is JPanel ?The basic Swing container.
2) Cant we add components to a JPanel and add this
JPanel to the JFrame?Yes, if you do it like the following:
import java.awt.*;
import javax.swing.*;
public class Example {
    public static void main(String[] args) {
        JPanel panel = new JPanel();
        for(int i=0; i<10; ++i)
            panel.add(new JButton("#"+i));
        JPanel another = new JPanel();
        for(int i=0; i<10; ++i)
            another.add(new JButton("#"+i));
        JFrame f = new JFrame("");
        Container cp = f.getContentPane();
        cp.add(panel, BorderLayout.NORTH);
        cp.add(another, BorderLayout.SOUTH);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);

Similar Messages

  • Calling a method on a jFrame from a jPanel that created by the jFrame

    Hi all
    I can not for the life of me work out how to do this.
    Calling a method on a jFrame from a jPanel that created by the jFrame.
    I have used this code to set a handle for one jPanel to another.
    i.e I can create new jpanel and pass in handles from one to another but not back to the jFrame.
    // this is sudo code
      private Panel_Top topPanel;
      private Menu_Panel menuPanel;
      private DataPanel dataPanel;
    //create new
        topPanel = new Panel_Top();
        menuPanel = new Menu_Panel();
        dataPanel = new DataPanel();
    // add handles from one to another
        menuPanel.setDataPanel(dataPanel);
        topPanel.setDataPanel(dataPanel);
        topPanel.setMenu_Panel(menuPanel);
        dataPanel.setMenu_Panel(menuPanel);
    // in each class I use this to set
      public void setDataPanel(DataPanel dataPanel) {
        this.dataPanel = dataPanel;
      }But I can not seam to get a handle back to the jFrame that created it.
    Please help
    as you can see I am trying but no luck so far
    Thanks

    class Life extends JPanel{
          pulic Life( JFrame owner )
                owner.doSomething(); // pass the JFrame to the constructor and feel free to use it
    }[code[                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Putting an image into a JFrame or a JPanel

    Hello everybody,
    I'd like to know how to put an image (a real one, not a small icon we can't see it!) into a JFrame, or a JPanel, or included into a miscellanea element (label, textfield or somethiong else).
    Thanks,
    Regards
    Cedric

    Hi Cedric,
    If the image format is Jpg or gif, then the best way to insert the image
    into the Frame or panel is to use JLabel. You can pass the argument to the file as parameter to JLabel construction.
    For other formats, you have the option of using drawimage in paint function of applets.
    Hope this helps.
    Best Regards,
    Chandru

  • JFrame switching to JPanel

    My JFrame is working perfectly. Its got a button on it that when pressed I want my panel to appear. I don't mind if the other one dissapears or stays there.
    I have created a JPanel in a seperate java file. Its fine aswell, but now I want it to appear when I hit my add button.
    I expecetd it to be a case of a new instance the following would work;
    JPanelAdd panel = new JPanelAdd();But no joy. Then I thought I could do something like panel.show();
    So, I'm obviously doing something basic wrong. I'd appreciate the help.

    No joy with the following:
    private void
    jButtonAddMouseClicked(java.awt.event.MouseEvent evt)
    JPanelAdd panel = new JPanelAdd();
    this.getContentPane().add(panel);
    panel.setVisible(true);
    System.out.println("got here");
    Being a novice myself, I can only tell you that these two code snippets:
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            dlgPrueba.setVisible(true);
        private void miFilePreferencesLoadActionPerformed(java.awt.event.ActionEvent evt) {                                                     
            PrefDialog pf = new PrefDialog();
            System.out.println("Option 'Load Preferences...' has been choosed.");
            pf.setVisible(true);
        }                                                     work for me. The first one launches a jDialog created inside the jFrame (when I say "inside", I mean that you add a jDialog from the Palette Manager while editing the jFrame; that jDialog is bound to be used exclusively as part of the jFrame).
    The second one is closest to your environment. I've got a separate .java file to define the class "PrefDialog" which, as you may suppose, extends jDialog.
    In both cases, the dialogs work fine. As a side note, the first runs on a button click, while the second one gets launched by choosing a menu item.
    Sorry to not be able to help you further.

  • 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.

  • HELP Create Extenstion using JFrame instead of JPanel (10.1.3 Release 3)

    Hi,
    I manage to create a custom GUI editor in JDev but if i switch it to JFrame, JDev GUI Designer display nothing but an invinsible frame.
    I'm using sample from customeditor in extension sdk
    Any ideas ?
    Thanks

    It seems that you are trying to use a JFrame as the GUI of your custom editor. The JFrame is a heavy weight component (has a real window behind it). In JDeveloper custom editors must not use JFrames or AWT Frames as their root GUIs. The windows of these frames will paint on top of other editors even if they are behind in the component stacking order.

  • Repainting a JFrame when a JPANEL is changed

    Hi,
    I have a jframe with one panel.
    Inside the jframe there are also two jbuttons.
    Inside the frame I have a List<Panel> panelList which displays one panel at a time in the frame.
    When the up jbutton is selected I want the frame to display the next panel in the panelList.
    Currently I construct a new frame and dispose of the old one.
    Can I just replace the old panel and repaint the frame?
    Cheers
    Bobby

    Use a CardLayout.

  • Need help:JPanel not being displayed in the JFrame

    Hello,
    I have a class called ConstructRoom.java which extends JFrame and another class called DimensionsPanel.java which extends JPanel. In the ConstructRoom class I use the following theContainer.add(new DimensionsPanel());, so I can display my JPanel. Well I get the JFrame but no JPanel. When the this call is made the DimensionsPanel.java code is cycled through, Where has my JPanel gone to?
    If I change the DimensionPanel.java extend JFrame and add the the JFrame code. Then I get the JFrame and the JPanel.
    Whats going on here?
    Thanks

    I made some of the changes with no luck. Here is some of the code:
    ---------from ConstructRoom.java--------
    //Imports
    public class ConstructRoom extends JFrame
    //----Member objects and varibles
    private static String theTitle; //Varible for title of frame
    private JFrame theFrame; //Object for the JFrame
    // ----------------------------------------------------------- ConstructRoom
    public ConstructRoom(String theTitle)
    super(theTitle); //JFrame super class
    theFrame = new JFrame("My frame");
    Container theContainer = theFrame.getContentPane(); //Frame container
    theContainer.setLayout(new FlowLayout());
    theContainer.add(new DimensionsPanel());
    theFrame.pack();
    theFrame.setBounds(10,10,400, 400);
    theFrame.addWindowListener(new WindowHandler());
    theFrame.setVisible(true);
    }//end ConstructRoom(String theTitle)
    // -------------------------------------------------------------------- main
    public static void main(String args[])
    ConstructRoom theRoom = new ConstructRoom(theTitle);
    }//end main(String args[])
    //----WindowHander
    }//end class ConstructRoom extends JFrame
    --------from DimensionsPanel.java
    //Imports
    public class DimensionsPanel extends JPanel
    //----Member objects and varibles
    private JPanel dimensionsPanel; //The main panel to hold all info
    private Box panelBox; //Box for all boxes which is added to the JPanel
    private Box furnListBox; //Box for all related items of the furnList
    private Box dimensionsBox; //Box for all dimensions (x, y, z)
    private Box xFieldBox; //Box for all related items of the xField
    private Box yFieldBox; //Box for related items of the yField
    private Box zFieldBox; //Box for related items of the zField
    private Box buttonsBox; //Box for all buttons
    private Box clearBox; //Box for related clear button items
    private Box buildBox; //Box for related build button items
    private JLabel furnListLabel; //Label for the furnList comboBox
    private JLabel xFieldLabel; //Label for the xField
    private JLabel yFieldLabel; //Label for yField
    private JLabel zFieldLabel; //Label for zField
    private JTextField xField; //Text field to enter the x dimension
    private JTextField yField; //Text field to enter the y dimension
    private JTextField zField; //Text field to enter the z dimension
    private JComboBox furnList; //List of selectable furniture objects
    private JButton clearButton; //Clear button
    private JButton buildButton; //Build button
    // --------------------------------------------------------- DimensionsPanel
    public DimensionsPanel()
    //----Setting up dimensions panel
    dimensionsPanel = new JPanel();
    dimensionsPanel.setLayout(new BorderLayout());
    dimensionsPanel.setPreferredSize(new Dimension(150,150));
    dimensionsPanel.setBorder(new TitledBorder(new EtchedBorder(),
    "Select Furniture and Enter Dimensions"));
    //----Initializing GUI components
    furnListLabel = new JLabel("Select from list ");
    furnList = new JComboBox();
    xFieldLabel = new JLabel("Enter Width ");
    xField = new JTextField();
    yFieldLabel = new JLabel("Enter Height ");
    yField = new JTextField();
    zFieldLabel = new JLabel("Enter Depth ");
    zField = new JTextField();
    buildButton = new JButton("Build Object");
    clearButton = new JButton("Clear Object");
    //-----Setting up the combo box and adding items
    furnList.addActionListener(new ComboProcessor());
    furnList.addItem(" "); //Default item
    furnList.addItem("Color Cube");
    furnList.setMaximumRowCount(6); //Max number of items before scrolling
    furnList.setSelectedItem(" "); //Set initial to default item
    //--Add the furnList to its box for placement in the JPanel
    furnListBox = Box.createHorizontalBox();
    furnListBox.add(Box.createHorizontalStrut(5));
    furnListBox.add(furnListLabel); //Adding the combo box label
    furnListBox.add(furnList); //Adding the combo box
    furnListBox.add(Box.createHorizontalStrut(5)); //Spacing
    //-------------------------------- Start Dimensions Components
    //----Setting up the xField
    xField.setEnabled(false); //Disabled at start
    xField.setFocusTraversalKeysEnabled(false); //Disabling the Tab Key
    //----Adding the event listeners
    xField.addActionListener(new XTextProcessor()); //Enter Key
    xField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the xField to its box for placement in the dimensionsBox
    xFieldBox = Box.createHorizontalBox();
    xFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    xFieldBox.add(Box.createGlue()); //Take up extra space
    xFieldBox.add(xFieldLabel); //Adding the text field label
    xFieldBox.add(xField); //Adding the text field
    xFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the yfield
    yField.setEnabled(false); //Disabled at start
    yField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    yField.addActionListener(new YTextProcessor()); //Enter Key
    yField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the yField to its box for placement in the dimensionsBox
    yFieldBox = Box.createHorizontalBox();
    yFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    yFieldBox.add(Box.createGlue()); //Take up extra space
    yFieldBox.add(yFieldLabel); //Adding the text field label
    yFieldBox.add(yField); //Adding the text field
    yFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Setting up the zfield
    zField.setEnabled(false); //Disabled at start
    zField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
    //----Adding the event listeners
    zField.addActionListener(new ZTextProcessor()); //Enter Key
    zField.addMouseListener(new ClickProcessor()); //Mouse Click
    //--Add the zField to its box for placement in the dimensionsBox
    zFieldBox = Box.createHorizontalBox();
    zFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
    zFieldBox.add(Box.createGlue()); //Take up extra space
    zFieldBox.add(zFieldLabel); //Adding the text field label
    zFieldBox.add(zField); //Adding the text field
    zFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
    //----Adding all dimension components to the dimensionsBox
    dimensionsBox = Box.createVerticalBox();
    dimensionsBox.add(xFieldBox); //Adding the xFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(yFieldBox); //Adding the yFieldBox
    dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsBox.add(zFieldBox); //Adding the zFieldBox
    //-------------------------------- End Dimension Components
    //----Setting up the clearButton
    clearButton.setEnabled(false); //Disabled at start
    //----Adding the event listener
    clearButton.addActionListener(new ClearProcessor());
    //--Add the clear button to its box for placement
    clearBox = Box.createHorizontalBox();
    clearBox.add(Box.createHorizontalStrut(5)); //Spacing
    clearBox.add(clearButton); //Adding the clearButton
    //----Setting up the buildButton
    buildButton.setEnabled(false); //Disabled at start
    //--Add the action listener here
    buildBox = Box.createHorizontalBox();
    buildBox.add(buildButton); //Adding the buildButton
    buildBox.add(Box.createHorizontalStrut(5)); //Spacing
    //----Adding both buttons the buttonsBox
    buttonsBox = Box.createHorizontalBox();
    buttonsBox.add(clearBox); //Adding the clearBox
    buttonsBox.add(Box.createHorizontalStrut(10)); //Spacing
    buttonsBox.add(buildBox); //Adding the buildBox
    //----Create the JPanel (dimensionsPanel)
    //--Creating the main box to be added to the JPanel
    panelBox = Box.createVerticalBox();
    panelBox.add(furnListBox); //Adding the furnListBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(dimensionsBox); //Adding the dimensionBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    panelBox.add(buttonsBox); //Adding the buttonsBox components
    panelBox.add(Box.createVerticalStrut(10)); //Spacing
    dimensionsPanel.add(panelBox); //Adding all components to the JPanel
    System.out.println("end dimensionpanel");
    }//end DimensionsPanel()
    //------ActionListeners
    }//end class DimensionsPanel extends JPanel

  • 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. :)

  • Beginners Questions about Multiple JPanels in JFrame and event handling

    I am a newbie with SWING, and even a newerbie in Event Handling. So here goes.
    I am writing a maze program. I am placing a maze JPanel (MazePanel) at the center of a JFrame, and a JPanel of buttons (ButtonPanel) on the SOUTH pane. I want the buttons to be able to re-randomize the maze, solve the maze, and also ouput statistics (for percolation theory purposes). I have the backbone all done already, I am just creating the GUI now. I am just figuring out EventHandlers and such through the tutorials, but I have a question. I am adding an ActionListener to the buttons which are on the ButtonPanel which are on JFrame (SOUTH) Panel. But who do I make the ActionListener--Basically the one doing the work when the button is pressed. Do I make the JFrame the ActionListener or the MazePanel the ActionListener. I need something which has access to the maze data (the backbone), and which can call the Maze.randomize() function. I'm trying to make a good design and not just slop too.
    Also I was wondering if I do this
    JButton.addActionListener(MazePanel), and lets say public MazePanel implments ActionListenerdoesn't adding this whole big object to another object (namely the button actionlistener) seem really inefficient? And how does something that is nested in a JPanel on JFrame x get information from something nested in another JPanel on a JFrame x.
    Basically how is the Buttons going to talk to the maze when the maze is so far away?

    I'm not an expert, but here's what I'd do....
    You already have your business logic (the Maze classes), you said. I'm assuming you have some kind of public interface to this business logic. I would create a new class like "MazeGui" that extends JFrame, and then create the GUI using this class. Add buttons and panels as needed to get it to look the way you want. Then for each button that does a specific thing, add an anonymous ActionListener class to it and put whatever code you need inside the ActionListener that accesses the business logic classes and does what it needs to.
    This is the idea, though my code is totally unchecked and won't compile:
    import deadseasquirrels.mazestuff.*;
    public class MazeGui extends JFrame {
      JPanel buttonPanel = new JPanel();
      JPanel mazePanel = new JPanel();
      JButton randomizeB = new JButton();
      JButton solveB = new JButton();
      JButton statsB = new JButton();
      // create instanc(es) of your Maze business logic class(es)
      myMaze = new MazeClass();
      // add the components to the MazeGui content pane
      Component cp = getContentPane();
      cp.add(); // this doesn't do anything, but in your code you'd add
                // all of your components to the MazeGui's contentpane
      randomizeB.addActionListener(new ActionListener {
        void actionPerformed() {
          Maze newMaze = myMaze.getRandomMazeLayout();
          mazePanel.setContents(newMaze); // this is not a real method!
                                          // it's just to give you the idea
                                          // of how to manipulate the JPanel
                                          // representing your Maze diagram,
                                          // you will probably be changing a
                                          // subcomponent of the JPanel
      solveB.addActionListener(new ActionListener {
        void actionPerformed() {
          Solution mySolution = myMaze.getSolution();
          mazePanel.setContents(mySolution); // again, this is not a real
                                             // method but it shows you how
                                             // the ActionListener can
                                             // access your GUI
      // repeat with any other buttons you need
      public static void main(String[] args) {
        MazeGui mg = new MazeGui();
        mg.setVisible(true);
        // etc...
    }

  • Urgent!!!!!!!! JFrame+JPanel problem

    How can I add a JFrame to a JPanel? What kind of objects can be contained Frames in at all?
    Thanks in advance

    Hi
    You cant add JFrame,JWindow,JApplet,JDialog to any other component.
    These are top level component and can not be added to any other.
    Ashish

  • Fitting JPanel perfectly inside content pane of JFrame

    Say I have a JPanel with size W x H that I want to add to a JFrame such that the JFrame will be sized as small as possible while still fitting the panel inside its content pane. Is there a method in JPanel that I can overwrite or a specific method of adding to a JFrame that I can use to accomplish this, or do I need to calculate the JFrame's size with getInsets()?
    Thanks.

    If I do this...
    JFrame frame = new JFrame("Pack Test");
    JPanel panel = new JPanel();
    panel.setSize(300, 300);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);...the resulting content pane is most definitely not 300x300 pixels. What am I doing wrong?

  • JPanel that close the parent JFrame

    Hello.
    I'm puzzled... how can I close a JFrame from the JPanel it contains?
    I mean:
    I have a Form that extends JFrame. In this form there's a JPanel, which has a BorderLayout. In the South part of the BorderLayout there's a JPanel (BoxLayout) that contains a JButton.
    I'd like this JButton to get disposed of the Form.
    How should I?
    Is there a better way to manage with this?
    (putting the button somewhere else...)
    Thank you

    Sorry, I forgot to mention that my sub-panel is in another class, another file.
    So I don't know how to call the parent frame.
    I tried with some .getParent(), but I get
    JPanel
    JLayerPane
    JRootPane
    and no JFrame.
    I could just put everything into 1 single class (or inner classes at least), but if there's a chance to keep them in different files, I would be glad to learn about it :)
    Thank you.

  • Can we add JFrame to JPanel?

    hi
    I m trying to add JFrame which has JPanel with BufferedImage to another JPanel.
    Is it possible? if yes kindly tell me how to achieve this.
    thanx

    Just another cross poster.
    [http://www.java-forums.org/java-2d/16085-how-add-jframe-inside-jpanel.html]
    db

  • HELP: How to get window (JFrame) from JPanel ???

    Hi there,
    anyone knows how I can get a ref. to the window (in the form of JFrame) from my JPanel that is in the actual window??
    I need that window when I display a modal dialog from the panel, as the dialog constructor takes the window as a param.
    I could always pass a window-ref. to the JPanel when I create it, but as I have a lot of panels, I'd rather be able to get it just when I need it from the JPanel!
    Thanks a lot for any help on this issue!
    Best regards,
    AC

    Thanks a lot!
    I'll use windowForComponent in swingUtils, I think getRootPane() would only return the panel that the component is in!
    Regards,
    AC

Maybe you are looking for

  • Updated to 6.1 but badge still on settings.

    I updated my 4g ipod touch to 6.1 but now on my homescreen the small red circle with 1 in it that indicates there is an update is still there. How can I get rid of this? would anything else be causing it? When I go into settings nothing else has that

  • LSMW program

    need to assign different  roles to different users and the role number and user number is here big so need to create the LSMW program to accomplish this work, please let me know step by step procedure to create LSMW script/program to assign mutiple r

  • Guide me

    hello i can't authorize store itunes on my macbook pro after to enter apple id and password correctly please help me Ali

  • AIA FP 2.2.1 installation fails.

    Hi, While trying to install AIA FP 2.2.1 it fails while executing "AIA Foundation Pack Config Utility" with the following error. exec java.lang.InstantiationException: No location specified for resource-ref jdbc/AIADataSource exec at com.evermind.ser

  • Trial version of contribure CS5 difficulty downloading.

    Hi I have tried to selet the download now for the trial of contribute CS5, the download button does not work.  Any suggestions. Thanks