Putting a jpanel into a jframe

I have a main JFrame which was created by:
public class ControllerGUI extends javax.swing.JFrameand inside this somewhere is a JPanel called myPanel.
I have a seperate class which is a JPanel created by:
public class Calc extends javax.swing.JPanelI am quite new to swing and have been using the GUI builder in Netbeans, so could someone please tell me how to put the seperate Calc JPanel into the JPanel myPanel which is in the JFrame. Is it something to do with creating a container for it? Thanks.
Thanks.

Not sure if you're still around, but here's a very simple example of putting a JPanel derived object into another JPanel. The Calc class here extends JPanel. It does nothing but shows a 3 by 3 grid of JLabels:
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
class Calc extends JPanel
    public Calc()
        setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 0));
        // what the heck, have it show a 3x3 label grid
        setLayout(new GridLayout(0, 3, 10, 10)); // sets layout for the grid
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                String labelString = "[" + (i + 1) + ", " + (j + 1) + "]";
                JLabel label = new JLabel(labelString);
                label.setBorder(BorderFactory.createLineBorder(Color.blue));
                label.setHorizontalAlignment(SwingConstants.CENTER);
                add(label); // adds each label to the grid
}Now I'll add it to myPanel which is a JPanel object, but before adding it, I'll set the myPanel's layout to be BorderLayout, and I'll add the Calc class to the CENTER position:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FooFrame extends JFrame
    // declare and initialize the myPanel JPanel object and
    // the myCalc Calc object:
    private JPanel myPanel = new JPanel();
    private Calc myCalc = new Calc();
    public FooFrame(String s)
        super(s);
        getContentPane().add(myPanel); // add myPanel to the contentPane making it the main panel
        setPreferredSize(new Dimension(500, 400));
        myPanel.setLayout(new BorderLayout());  // here set the layout of mypanel
        myPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        // create a title panel and add it to the top of myPanel
        JLabel title = new JLabel("Application Title");
        JPanel titlePanel = new JPanel(new FlowLayout()); // redundant since jpanels
                                                        //use flowlayout by default
        titlePanel.add(title);
        myPanel.add(titlePanel, BorderLayout.PAGE_START); // adds title to top of myPanel
        // create a button panel and add it to the bottom of myPanel
        // here we'll use gridlayout
        JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 15, 0));
        JButton okButton = new JButton("OK"); // create buttons
        JButton cancelButton = new JButton("Cancel");
        buttonPanel.add(okButton); // add buttons to button panel
        buttonPanel.add(cancelButton);
        myPanel.add(buttonPanel, BorderLayout.PAGE_END); // adds buttonpanel to bottom of myPanel
        //** add the myCalc object to the center of the myPanel via borderlayout
        myPanel.add(myCalc, BorderLayout.CENTER);
    // initialize and show the JFrame
    private static void createAndShowUI()
        JFrame frame = new FooFrame("FooFrame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    // but be careful to show the JFrame in a thread-safe manner:
    public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
            public void run()
                createAndShowUI();
}

Similar Messages

  • 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

  • How can i put one scene into JPanel of the swing?

    how can i put one scene into JPanel of the swing?

    980571 wrote:
    ty for the information but i have a problen with JFXpanel when i try to into a panel it doesnt display insideSorry to hear that. If you want assistance with the code, feel free to post the relevant parts of it. Make sure to use \ tags when you do.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Putting an Image into a Frame

    Hi there,
    Ive created an applet in Java which is basically a square with a boucing ball in it. The problem is i want to put this into a JFrame so i can add other controls. How would i go about this?? I initialise the image in the intialisation... i.e.
    Buffer=createImage(600,600);
    gBuffer=Buffer.getGraphics();
    then i have my paint method as so.
    public void paint(Graphics g)
    gBuffer.setColor(Color.blue);
    gBuffer.fillRect(0,0,size().width,size().height);
    gBuffer.setColor(Color.yellow);
    gBuffer.fillOval(0,0,600,600);
    //Loop through Crabs
    for (int i=0; i<=iNumberofCrabs; i++){
    //Get Home
    if(iCrab.getHasHome()){
    Home phome = iCrab[i].getHome();
    //Paint Home and Crab
    phome.paint(gBuffer);
    iCrab[i].paint(gBuffer);
    g.drawImage (Buffer,20,10, this);
    Any help would be great....
    Regards James

    i would probably do like this....................
    * ImageClass.java
    * Created on February 16, 2006, 1:20 AM
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    * @author hussain
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    public class ImageClass extends JFrame
        jpanel j;
        public ImageClass()
            super("Image Application");
            Container cpane = getContentPane();
            j = new jpanel();
            cpane.add(j);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public static void main(String args[])
            final JFrame f = new ImageClass();
            f.setBounds(100, 100, 300, 300);
            f.setVisible(true);
    class jpanel extends JPanel
        Image image;
        int i = 0;
        short array[]= null;
        jpanel()
            setBackground(Color.WHITE);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            BufferedImage aImage = gc.createCompatibleImage(200, 200, Transparency.BITMASK);
            image = Toolkit.getDefaultToolkit().getImage("c:\\fatwa.jpg");
            g.drawImage(image, 0,0,this);
    }

  • How to Load a wav file into a JFrame

    Ok, I have a JFrame with a JPanel and JButtons, play, pause, stop....etc...I have a menu with items load song and exit. Now when you click file load song, it pops up a JFileChooser.....that all works fine. Now I want to be able to select a wav file from that file chooser and have it load into the JFrame, displaying the name of the song in the JPanel...as a JLabel or whatever. Also how can I make the buttons, play pause stop, etc. work with the song. I.E. when i press play, the song plays, stop the song stops...any ideas?

    Create a JLabel with the filename as its text. Add the JLabel onto your JPanel. Add the JPanel
    onto the JFrame. Call setVisible(true) on the JFrame. For Java GUI basics, study:
    http://java.sun.com/docs/books/tutorial/uiswing/index.html
    For wav file playing:
    String filename = "foo.wav";
    java.applet.AudioClip clip
    = java.applet.Applet.newAudioClip(new File(filename).toURI().toURL());
    clip.play();

  • Several Jpanels in a JFrame

    Hi,
    I have three buttons in Jtoolbar and a JPanel inside a JFrame. Now my program is supposed to work in the follwoing way-
    when I click a button a new JPanel containing general information comes in that fixed Jpanel place in that JFrame.
    When I press another button "a form" should come.
    When I press the third button then the a Jtable will come.
    Now all these should come in the same place inside that JFrame. So, when I press the JToggleButtons then how to call and set up so that the Jpanels replace each other?
    Please post some example if possible along with your advice.
    Thanks a lot in advance.

    I figured what the heck, here's a trivial example of card layout:
    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    * main jpanel that is added to a jframe's contentPane
    * this main panel uses a borderlayout and places a label
    * in the north position, a swap button in the south
    * position, and a jpanel in the center position that uses
    * the cardlayout. 
    * @author Pete
    public class CardPracticeMainPanel extends JPanel
        private static final long serialVersionUID = 1L;
        private JButton swapButton = new JButton("Swap Panels");
        private CardLayout cardlayout = new CardLayout();
        private JPanel cardLayoutPanel = null;
        public CardPracticeMainPanel()
            int ebGap = 20;
            setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
            setLayout(new BorderLayout());
            cardLayoutPanel = createCardLayoutPanel();
            add(createNorthPanel(), BorderLayout.NORTH);
            add(cardLayoutPanel, BorderLayout.CENTER);
            add(createSouthPanel(), BorderLayout.SOUTH);
        public void addCard(JPanel panel, String string)
            cardLayoutPanel.add(panel, string);
        private JPanel createNorthPanel()
            JPanel p = new JPanel();
            JLabel titleLabel = new JLabel("CardLayout Practice Program");
            titleLabel.setFont(new Font(Font.DIALOG, Font.BOLD, 24));
            p.add(titleLabel);
            return p;
        private JPanel createCardLayoutPanel()
            JPanel p = new JPanel();
            p.setLayout(cardlayout);
            return p;
        private JPanel createSouthPanel()
            JPanel p = new JPanel();
            p.add(swapButton);
            swapButton.addActionListener(new SwapButtonListener());
            return p;
        private class SwapButtonListener implements ActionListener
            public void actionPerformed(ActionEvent arg0)
                cardlayout.next(cardLayoutPanel);
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    * the "driver" program that creates a JFrame and places a
    * CardPracticeMainPanel into the contentpane of this jframe.
    * It also adds JPanel "cards" to the CardPracticeMainPanel object.
    * @author Pete
    public class CardPracticeTest
        private static Random rand = new Random();
        private static void createAndShowGUI()
            // create the main panel and add JPanel "cards" to it
            CardPracticeMainPanel mainPanel = new CardPracticeMainPanel();
            for (int i = 0; i < 4; i++)
                JPanel card = new JPanel();
                card.setPreferredSize(new Dimension(600, 400));
                card.setBorder(BorderFactory.createLineBorder(Color.blue));
                String panelString = "panel " + String.valueOf(i + 1);
                card.add(new JLabel(panelString));
                mainPanel.addCard(card, panelString);
                card.setBackground(new Color(
                        127 * rand.nextInt(3),
                        127 * rand.nextInt(3),
                        127 * rand.nextInt(3)));
            JFrame frame = new JFrame("CardLayout Practice Application");
            frame.getContentPane().add(mainPanel); // add main to jframe
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        // let's show the jframe in a thread-safe manner
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • Having trouble displaying a JPanel on a JFrame

    Hello all,
    I'm fairly new to Java and I am having trouble displaying a JPanel on a JFrame. Pretty much I have a class called Task which has a JPanel object. Everytime the user creates a new task, a JPanel with the required information is created on screen. However, I cannot get the JPanel to display.
    Here is some of the code I have written. If you guys need to see more code to help don't hesitate to ask.
    The user enters the information on the form and clicks the createTask button. If the information entered is valid, a new task is created and the initializeTask method is called.
    private void createTaskButtonMouseClicked(java.awt.event.MouseEvent evt) {                                             
        if (validateNewTaskEntry())
         String name = nameTextField.getText().trim();
         Date dueDate = dueDateChooser.getDate();
         byte hourDue = Byte.parseByte(hourFormattedTextField.getText());
         byte minuteDue = Byte.parseByte(minuteFormattedTextField.getText());
         String amOrPm = amPmComboBox.getSelectedItem().toString();
         String group = groupComboBox.getSelectedItem().toString();
         numberTasks++;
    //     if (numberTasks == 1)
    //     else
         Task newTask = new Task(mainForm, name, dueDate, hourDue, minuteDue,
             amOrPm, group);
         newTask.initializeTask();
         this.setVisible(false);
    }This is the code that I thought would display the JPanel. If I put this code in anther form's load event it will show the panel with the red border.
    public void initializeTask()
         taskPanel = new JPanel();
         taskPanel.setVisible(true);
         taskPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
         taskPanel.setBounds(0,0,50,50);
         taskPanel.setLayout(new BorderLayout());
         mainForm.setLayout(new BorderLayout());
         mainForm.getContentPane().add(taskPanel);
    }I was also wondering if this code had anything to do with it:
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new AddTaskForm(new MainForm()).setVisible(true);
        }As you can see I create a new MainForm. The MainForm is where the task is supposed to be drawn. This code is from the AddTaskForm (where they enter all the information to create a new task). I had to do this because AddTaskForm needs to use variables and methods from the MainForm class. I tried passing the mainForm I already created, but I get this error: non-static variable mainForm cannot be referenced from a static context. So to allow the program to compile I passed in new MainForm() instead. However, in my AddTaskForm class constructor, I pass the original MainForm. Here is the code:
    public AddTaskForm(MainForm mainForm)
       initComponents();
       numberTasks = 0;
       this.mainForm = mainForm;
    }Is a new mainForm actually being created and thats why I can't see the JPanel on the original mainForm? If this is the case, how would I pass the mainForm to addTaskForm? Thanks a ton for any help/suggestions!
    Brian

    UPDATE
    While writing the post an idea popped in my head. I decided to not require a MainForm in the AddTaskForm. Instead to get the MainForm I created an initializeMainForm method.
    This is what I mean by not having to pass new MainForm():
        public static void main(String args[])
         java.awt.EventQueue.invokeLater(new Runnable()
             public void run()
              new MainForm().setVisible(true);
        }Even when I don't create the new MainForm() the JPanel still doesn't show up.
    Again, thanks for any help.
    Brian

  • Putting an image in a JFrame

    I'm trying to paint an image onto a JFrame. Im making a monopoly game and need to paint the board, and repaint it after every turn. I dont know how to put an image onto a JFrame and was wondering if anyone could give me a basic algorithm or code example of how to do this. Thanks.

    Here is the basic algorithm to paint to a JFrame:
    Don't do it!
    Set the preferred size of a JPanel and add the JPanel to the JFrame. Paint to the JPanel by extending the paintComponent method. When you're ready to display, then remember to pack the JFrame and setVisible appropriately.
    You can read about doing this in the Java Tutorial.
    public void paintComponent(Graphics g){ //override in JPanel
      super.paintComponent(g);
      //do what ever you need to do here to draw your graphics.
    }I prefer to do all of my drawing to a BufferedImage and then use drawImage to show the image (off screen rendering):
    public void paintComponent(Graphics g){ //override in JPanel
      g.drawImage(myImage, 0, 0, this);
    }

  • HT2518 How do I transfer music from an external hard drive to my itunes on my mac? I have put the files into the itunes media, but they are not showing up in iTunes!

    How do I transfer music from an external hard drive to my itunes on my mac? I have put the files into the itunes media, but they are not showing up in iTunes!

    Hi, did you try iTunes>File>Import?

  • When I convert my pdf doc to word, the fonts go really weird and it also puts some text into boxes. when I try to select the test and change the font, it does not change it properly?

    When I convert my pdf doc to word, the fonts go really weird and it also puts some text into boxes. when I try to select the text and change the font, it does not change it properly? This is making it impossible to amend.

    Hi Janedance1,
    If the PDF that you converted already has searchable text, please try disabling OCR as described in this document: How to disable Optical Character Recognition (OCR) when converting PDF to Word or Excel. (If the PDF was created from a scanned document and doesn't already have searchable text, disabling OCR isn't a great option, as the text won't be searchable/editable in the converted Word doc.)
    Please let us know how it goes.
    Best,
    Sara

  • I forgot my password for my iphone 4 and it is now disabled. I am trying to restore it through itunes, but it say I have to put my passcode into my phone first. Is there a way to restore without using my passcode?

    I forgot my password for my iphone 4 and it is now disabled. I am trying to restore it through itunes, but it say I have to put my passcode into my phone first. Is there a way to restore without using my passcode?

    The instructions are in that link. Just follow them VERY CAREFULLY. Especially the part about:
    Turn off your device and leave it off.
    Plug in your device's USB cable to a computer with iTunes. [but DON'T connect it to the iPhone yet]
    Hold down the Home button on your device as you connect the USB cable. Keep holding down the Home button until you see the Connect to iTunes screen.
    When you see the iTunes screen, release the Home button. If you don't see this screen, try steps 1 through 3 again.
    When your device is connected, iTunes will open. You'll see a message saying that iTunes has detected an iPhone, iPad, or iPod touch in recovery mode.
    Hold down the Home button on your device as you connect the USB cable. Keep holding down the Home button until you see the Connect to iTunes screen.

  • How can I format an SD card on my mac?  I have tried the erase thing but when I put the card into my 35mm camera it says that the card has to be formatted.

    I just purchased two new SanDisk 8gb SD cards for my trail cameras.  When I put the cards into the trail cameras, the cameras will take pictures but it won't store them on the cards.  When I put the cards into my 35mm camera the camera tells me that the cards need to be formatted.  I have went through the steps in the disk utilities and erased the cards, which I assume is the same as formatting them??  I have tried this for hours and have had no luck getting these things to work at all.  It was awful disgusting when I checked my two trail cameras the first time and found out that they had taken close to 75 pictures but the cards were empty.  When I bought my 35mm camera several years ago, I bought a couple of Kodak SD cards and used them right out of the package and never had to do any of this formatting thing.  I don't understand what is going on and could sure use some help with this.  Thanks for any information anyone can give me with this problem.  I would love to have seen what animals set my cameras off 75 times in the last few days.  Thanks again.
    Respectully
    Jim

    AFAIK cameras offer their own built-in format utility for inserted SD cards.  You should use that.  Otherwise, refer to the manual that came with your camera to determine precisely how your SD cards need to be formatted to work properly.  Personally, I'd suggest Partition Scheme: MBR, and Filesystem: FAT32.
    Try to limit the number of formats you perform on the SD cards, though, as you're reducing their lifespan.  I believe formatting causes re-writes to a portion of the SD card that has fewer read/write cycles than the rest of the card as a whole.

  • How do I add multiple JPanels to a JFrame?

    I've been trying to do my own little side project to just make something for me and my friends. However, I can't get multiple JPanels to display in one JFrame. If I add more than one JPanel, nothing shows up in the frame. I've tried with SpringLayout, FlowLayout, GridBagLayout, and whatever the default layout for JFrames is. Here is the code that's important:
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import javax.swing.*;
    public class CharSheetMain {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              CharSheetFrame frame=new CharSheetFrame();
              abilityPanel aPanel=new abilityPanel();
              descripPanel dPanel=new descripPanel();
              frame.setLayout(new FlowLayout());
              abilityScore st=new abilityScore();
              abilityScore de=new abilityScore();
              abilityScore co=new abilityScore();
              abilityScore in=new abilityScore();
              abilityScore wi=new abilityScore();
              abilityScore ch=new abilityScore();
              frame.add(aPanel);
              frame.add(dPanel);
              frame.validate();
              frame.repaint();
              frame.pack();
              frame.setVisible(true);
    }aPanel and dPanel both extend JPanel. frame extends JFrame. I can get either aPanel or dPanel to show up, but not both at the same time. Can someone tell me what I'm doing wrong?

    In the future, Swing related questions should be posted in the Swing forum.
    You need to read up on [How to Use Layout Managers|http://download.oracle.com/javase/tutorial/uiswing/layout/index.html]. The tutorial has working example of how to use each layout manager.
    By default the content pane of the frame uses a BorderLayout.
    For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org], that demonstrates the incorrect behaviour.
    The code you posted in NOT a SSCCE, since we don't have access to any of your custom classes. To do simple tests of adding a panel to frame then just create a panel, give it a preferred size and give each panel a different background color so you can see how it works with your choosen layout manager.

  • How do i put multiple albums into one huge album collection?

    How do i put multiple albums into one huge album collection?
    Some examples include: Linkin Park - Studio Collection, Michael Jackson - The Indisposable Collection

    Hi skullkrunch3r,
    Thanks for visiting Apple Support Communities.
    If you "Get Info" on the tracks that are part of your collection, you can use the Compilation option in iTunes.
    In iTunes 8 and later, you find the option to mark multiple items as "Part of a compilation" in the Options tab of the Multiple Item Information window.
    See this article for more information on marking your albums as part of a compilation:
    Why aren't songs with the same album art grouped together?
    http://support.apple.com/kb/TS1468
    Best Regards,
    Jeremy

  • How to put a String into a byte array

    How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David

    javadocs for String
    getBytes
    public byte[] getBytes()
    Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
    Returns:
    The resultant byte arraySince:
    JDK1.1

Maybe you are looking for

  • DVI to VGA cable disables trackpad

    Used the mini dvi to vga cable for months with no problem. Today i plugged in the DVI and the track pad was disabled - could not use track pad at all. Additionally when i select system preferences and display the display is automatically reverted to

  • Pdf export indesign - size options?

    Hey guys, I could not find anything in the internet, I hope someone here can help me. I have a document in Indesign that has a size of Din A4 and needs to be printed later on. If I export it with best settings it has a size of 20 MB, if I do it with

  • Packaging a captive runtime bundle for desktop computers

    This question was posted in response to the following article: http://help.adobe.com/en_US/air/build/WSfffb011ac560372f709e16db131e43659b9-8000.html

  • Linear linked list and NullPointerException

    its a cd archive. the CDnode public class CDnode {     public CD data;     public CDnode neste; }The LinkedList class public class LinkedList {     int length;        public CDnode firstNode;     /** Creates a new instance of nesteedList */     publi

  • Arch linux install and setup questions

    Personally it seems a bit to cumbersome to have to setup xorg etc and is proving to be difficult in getting it to work right. Do they have any arch forks that just auto detect the xorg settings like some of the other distros? I can't see myself havin