Adding a panel to a frame

Hi! All,
I'm new to java and i have a little problem here. I have created a frame and i want to put two panels inside it. well, i managed to put the first one, but i'm having problems with the second one. I want this second one to be added when I click on a button.
The button that I will click is the new JButton i have defined. it is called draw. I really do not know what the problem is. I will apprecite any help. Below is my code.
// My Code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
public class Main extends JFrame {
//all components I'll need
public JButton draw;
public JButton addFormula;
public JButton modelCheck;
/** Creates a new instance of Main */
public Main () {
super("Graphical Model Checker for Knowledge");
//content pane is the main panel where i'll put everything
JPanel contentPane = new JPanel();
draw = new JButton("Draw");
draw.addActionListener(
new ActionListener() {         
public void actionPerformed(ActionEvent event) {
if(event.getActionComman().equals"Draw")) {               
JPanel drawing = new JPanel();
drawing.setBackground(Color.BLUE);
drawing.setSize(100, 100);
drawing.setLayout(new FlowLayout
FlowLayout.CENTER));
add("North", drawing);
drawing.setVisible(true);
contentPane.add(draw);
addFormula = new JButton("Add Formula");
contentPane.add(addFormula);
modelCheck = new JButton("Model Check");
contentPane.add(modelCheck);
Canvas canvas = new Canvas();
canvas.setSize(40, 40);
canvas.setBackground(Color.white);
contentPane.add(canvas);
repaint();
//add panel to the frame
add("South", contentPane);
//colours for window
contentPane.setBackground(Color.yellow);
//set layout manager
contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
addWindowListener(new CloseWindow());
pack();
setVisible(true);
String [] fileItems = {"Open", "Save", "Rename"};
String [] editItems = {"Copy", "Cut", "Paste"};
//instantiate a menu bar object
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
for (int index=0; index != fileItems.length; index++)
file.add(fileItems[index]);
bar.add(file);
setJMenuBar(bar);
JMenu edit = new JMenu("Edit Graph");
for (int index=0; index != editItems.length; index++)
edit.add(editItems[index]);
bar.add(edit);
setJMenuBar(bar);
public static void main(String args []) {
JFrame window = new Main();
}

Don't forget to use the "Code Formatting Tags",
see http://forum.java.sun.com/help.jspa?sec=formatting,
so the posted code retains its original formatting.
add("North", drawing); The "North" means nothing when adding a component to a panel using a FlowLayout. You should just be using:
add( drawing );After you add the component to the container you need to use:
frame.validate();

Similar Messages

  • Hello everybody, Problem with Two panel in a Frame

    This is my first mail in this forum.I'm trying to learn java myself & have a problem in adding more than one panel in a JFrame.
    i should be able to add one panel which occupies 3/4 of a frame and another panel occupies the rest.
    Thanx in advance for anyone who helps me in sorting out this problem.

    You can use for example the GridLayout
    In your JFrame constructor, add lines below, it will add 2 colored panel in your frame
    Container container = getContentPane();
    container.setLayout(new GridLayout(1,2)); // 1 row, 2 cols
    JPanel panel1 = new JPanel();
    panel1.setBackground(Color.red);
    container.add(panel1);
    JPanel panel2 = new JPanel();
    panel2.setBackground(Color.green);
    container.add(panel2);

  • Sizing two panels in a frame

    Hi,
    i would like to set the size of two panels which are next to each other in a frame.
    The left one should be about 5 times wider than the one on the right.
    splitPane.setPreferredSize(new Dimension(1000,500));This one is not working.
    Thx:
    james

    SplitPane is my right panel in the frame, this should
    be 5x wider than the right panel, It should be 5x wider than itself?
    So it is nothing to do with Splitpane, the problem is
    that 1 add the splitpane and the buttonPanel to
    mainPanel, and these 2 panels are which are added are
    the same wide!You should have posted a Short,Self Contained, Compilable and Executable, Example Program.

  • Adding a Panel to JApplet doesn't work properly

    Hi there,
    I have a class "Editor" extended from JPanel to edit some data. In my JApplet I added a JMenubar with setJMenubar() and registered an ActionListener to the menu items. Everything works fine except the displaying of the EditorPanel after choosing the menu item.
    When I'm adding the Panel in the constructor of the applet it is shown correctly.
    public class EditorApplet extends JApplet implements ActionListener
      public void init()
        setJMenuBar(createJMenuBar());
        Editor e = new Editor();
        getContentPane().add(e); // works perfectly
        e.load(2); // load data into editor
      public void actionPerformed(ActionEvent e)
        if (e.getActionCommand().equals("..."))
          Editor e = new Editor();
          e.loadObjects(1);
          getContentPane().removeAll();
          getContentPane().add(e); // nothing happens!?
          getContentPane().repaint(); // ???
          repaint(); // ???
        }What else needs to be done to display the 'new' Editor?

    Wait. You're adding an ActionEvent to your panel.
    I think you want to do "add(this.e)".

  • Display 3 Panels in one frame.....

    Hi
    I need to display 3 different panels in one frame.
    The first panel will contain a JXTreeTable [North]
    The second Panel will contain a Tree [Center]
    The third Panel will contain a JXTreeTable [South]
    I am unable to get this working as the components to be displayed
    are not being placed properly.
    The JXTreeTable is being displayed only at the NORTH.
    Is it better to create 3 different panels or create just one panel with GridLayout(as I have done)
    Have I overlooked something in the code below?
    Thnx
    This is my code:
    public class PositionCostingView {
         public PositionCostingView(){
              initComponents();
         private void initComponents(){
              final JFrame frame = new JFrame("Position Costing");
              frame.setPreferredSize(new Dimension(450, 300));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // First,testing my model
              TreeTableModel model = new OpTreeTableModel();
              JXTreeTable treeTable = new JXTreeTable(model);
              // Add the TreeTable to a Scroll Pane.
              JScrollPane scrollPane = new JScrollPane(treeTable);
              JPanel players = new JPanel(new GridLayout(3, 0));
              players.add(scrollPane);
              players.add(MyTree);
              players.add(scrollPane);
              JPanel content = new JPanel();
              content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
              content.add(players);
              frame.getContentPane().add(content);
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              new PositionCostingView();

    Please ignore my code on top.I am trying something else.....
    No offence meant please.

  • Adding a panel to an open GUI with a background image

    Dear java programmers,
    I want to add a JPanel with some components on an open(visible) GUI whenever a button is clicked. That JPanel carries a button, a progress bar, a label, and a textarea inside a scrollpane. Whenever the button of the panel is clicked a program starts working, and the progress and output of that program is reflected on the progress bar and textfield respectively. I 'put the code to generate and add the panel in a so called "Progress" class, which is different from the GUI class that contains the code to create and display the main gui.
    My gui also has a background image to make is look fancy, which is added by the following way:
    GUI mygui = new GUI();
    mygui.getContentPane().add(new ImagePanel(new ImageIcon("/home/thomas/Documents/external_placement/Report/presentation4_transp.png").getImage()));
    My problem is that the background image is hiding the panel (whenever added) and only when the cursor passes above the button inside the panel it becomes visible (just the button). However when I click the button and the program starts I can see everything inside the panel.
    Is there an efficient way of making the panel visible at once?
    thanks in advance,
    Tom

    Ok now that I'm certain about how to use code tags I'll try to make myself clear.
    First of all I made it work by removing the ImagePanel , adding the JPanel and re-adding ImagePanel, all from within the Progress.class. But I'm not sure if this is the right way.
    Below I'll make an attempt to provide some SSCCE--code. First of all the classes I'm using are 2, the GUI.class which contains all the components of the gui, and the Progress.class which has the additional panel and adds it to the gui whenever the "submit" button is clicked.
    The code from GUI.class which is relevant to this question is:
    public class GUI extends javax.swing.JFrame{
    //the following are declared as "protected" because they are also used elsewhere
                protected static GUI mygui = new GUI();
                protected static ImagePanel backgroundImagePanel = new ImagePanel(new ImageIcon("/home/thomas/Documents/external_placement/Report/presentation4_transp.png").getImage());
                /* The constructor */
                public GUI() {
            initComponents(); //this method initializes all the components, puts the in a JTabbedPane and packs them the JFrame
            setLayout(new BorderLayout());
        /* the eventlistener of the "submit" button */
        private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
            ProgressBarTest pbt = new ProgressBarTest(mygui);
            pbt.StartProgress();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    mygui.getContentPane().add(backgroundImagePanel);
                    mygui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    mygui.pack();
                    mygui.setVisible(true);
    } And then I have my Progress.class:
    public class Progress implements ActionListener, Runnable {
    //the following are declared as "private" because they are also used elsewhere inside the class
        private static javax.swing.JProgressBar progressBar = new JProgressBar(0, 100);
        private static javax.swing.JTextArea progressTextArea = new javax.swing.JTextArea(5,20);
        private static ProgressBarTest _this;
        {color:#0000ff}private static GUI mygui;{color}
        /* the constructor */
        public Progress(GUI gui){
            _this = this;
            {color:#0000ff}mygui = gui;{color}
        private static void createAndShowPanel(){
            javax.swing.JScrollPane progressScrollPane = new JScrollPane(progressTextArea);
            javax.swing.JLabel progressLabel = new JLabel("Progress");
            javax.swing.JButton progressButton = new JButton("Do something");
            progressButton.addActionListener(_this);
            javax.swing.JPanel progressPanel = new JPanel();
            javax.swing.GroupLayout progressPanelLayout = new javax.swing.GroupLayout(progressPanel);
            progressPanel.setLayout(progressPanelLayout);
            progressPanelLayout.setAutoCreateGaps(true);
            progressPanelLayout.setAutoCreateContainerGaps(true);
            progressPanelLayout.setHorizontalGroup(
                    progressPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(progressPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(progressPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(progressScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 872, Short.MAX_VALUE)
                    .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 872, Short.MAX_VALUE)
                    .addComponent(progressLabel)
                    .addComponent(progressButton, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addContainerGap())
            progressPanelLayout.setVerticalGroup(
                    progressPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, progressPanelLayout.createSequentialGroup()
                    .addContainerGap(25, Short.MAX_VALUE)
                    .addComponent(progressButton)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(progressLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(19, 19, 19)
                    .addComponent(progressScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout({color:#0000ff}mygui.getContentPane(){color});
            {color:#0000ff}mygui.getContentPane().setLayout(layout);{color}
            layout.setHorizontalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(progressPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent{color:#0000ff}(mygui.jTabbedPane1{color}, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(100, Short.MAX_VALUE))
            layout.setVerticalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent({color:#0000ff}mygui.jTabbedPane1{color}, javax.swing.GroupLayout.PREFERRED_SIZE, 362, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(progressPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
           {color:#0000ff} mygui.getContentPane().remove(mygui.backgroundImagePanel);
            mygui.getContentPane().add(progressPanel, BorderLayout.SOUTH);
            mygui.getContentPane().add(mygui.backgroundImagePanel);
            mygui.pack();{color}
        public static void StartProgress(){
            ProgressBarTest t = new ProgressBarTest({color:#0000ff}mygui{color});
            new Thread(t).start();
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowPanel();
        public void actionPerformed(ActionEvent ae){
    // signal the worker thread to get crackin
            synchronized(this){notifyAll();}
    // worker thread
        public void run(){
            while(true){
    // wait for the signal from the GUI
                try{synchronized(this){wait();}} catch (InterruptedException e){}
                Dock dock = new Dock();
                int chainArrayLength = dock.PrepareDockEnvironment();
    // start a long-running process -this is a task performed by "Dock.class"
                for (int i = 0; i <= 100; i++){
                    progressBar.setValue(i*100/chainArrayLength);
                    progressTextArea.append("Docking chain No "i".\n");
                    System.out.println("actionPerformed sets progressBar value to: "+i);
                    dock.StartDocking(i);
    }Please notice how I use the GUI object (named "mygui") inside the Progress.class to retrieve components from the main gui (particularly the jTabbedPane1), align them with the additional panel (progressPanel) and add them to the main gui again. I tried to color blue the lines where the GUI instance is used but I'm not sure if they will be visible.
    My questions are:
    1. Is this the right way to add a new panel to a jFrame from an external class? Do I add jTabedPane twice in the above code?
    2. Is this the most efficient way of making the additional panel visible at once, meaning by removing the ImagePanel (backgroundImagePanel) adding the panel (progressPanel) and finally adding again the ImagePanel (backgroundImagePanel)?
    Hope I was perspicuous.
    Tom

  • Make a square Panel inside a Frame (awt)

    Hi all. I have a Frame that contains an panel.
    The Frame has BorderLayout and panel is positioned Center in it, occuping all the space. However I want the Panel to be perfectly square.
    The Panel MUST have LayoutManager(null).
    If I call setSize(100,100) on Frame, the Frame incorporates the height to include the Windowsbar on top, and then the Panel won't be square.
    If I call SetSize(100,100) on Panel, the Frame don't display anything else than the Windowbar.
    How can I solve this? Am I missing something important?

    One more question please noah....
    My applet i dependent on the square panel like I said. However it is important that the applets Frame can be resized, but its panel must still be sqaure.
    My code goes as follows:
    class Spanel extends Frame{
        panel.setBackground(Color.red);
        panel.setLayout(null);
        panel.setSize(200,200);
        add("Center",panel);
        pack();
        show();
    this.addComponentListener(new java.awt.event.ComponentAdapter() {
          public void componentResized(ComponentEvent e) {
            int x = calculateFrameSize(e);
            panel.setSize(x,x);
            pack();
            show();
    calculateFrameSize() {
    // only returns the lowest number of
    //getWidth() and getHeight()
    }This code however will go in an infinite loop, calling
    COmponentResized over and over.
    How can I avoid the loop?

  • Changing panels on a frame depending on what the user clicks

    I'm making a small application with a JFrame and some JPanels.
    When the application starts a start panel is added to the frame where the user can press two buttons. If he presses a button, then a new panel must be painted on the frame. In the new panel there is a button for going back to the starting panel.
    How can I accomplish this changing of panels? How does one panel give control to another panel? How can I let the frame control everything (if I should do that)?

    I guess just use CardLayout, CardLayout will solve your problem

  • Video doesn't slow when added to timeline of different frame rate

    I'm having trouble understanding what's going on here.  I have a video shot at 59.94 fps, and I add it to a sequence that is set at 29.97 fps.  It plays back normally which makes sense if premiere is dropping frames by 1/2, but the drop frame indicator says that it isn't dropping frames.  The clip also runs the same length.  The interpret frame rate for the clip in the project window says 59.94 fps, so if it's added to a sequence that is set at 29.97 fps and it's NOT dropping frames, shouldn't it be slowed down?

    OK cool thank you very much.  So I've been doing some research to figure out the best way to edit this project.  The problem is that I have some GoPro videos shot at 1080X1920 and 59.94 fps and some at 480X840 and 240 fps.  But the catch is I want to make the final product work well for Youtube.  This is how I feel I should go about getting the best quality for my final video.
    1.  Set the sequence settings to 720X1280 (which is what I will export as so that the 480X840 doesn't loose as much quality compared to having to resize up to 1080X1920 to match the other clips).  I don't think there's much quality loss in down-scaling the 1080X1920 to 720X1280 (if any, or is there?), so it's kind of a happy medium for both frame sizes that I have and it's still good for Youtube.
    2.  Apparently Youtube really works well with 29.97 fps, so this is what I will set the sequence frame rate at.
           **Another side question I have is what if my sequence frame rate is set at 29.97fps and I interpret the frame rate of a 59.94fps clip as 29.97fps and add it to the sequence.  Now if I use the rate stretch tool to speed up the now slowed down clip to 200% so that it plays at normal speed.  Will Premiere remove frames to speed up the clip or does it really increase the rate of the frames so that I don't loose any frames?**  My guess is if I export at 29.97fps it will remove half of the frames.
    Is it not possible to have an exported movie clip that contains multiple frame rates?

  • Passing data from a panel to a frame / disposing of a frame from in a panel

    Hello, I have recently created a program where all windows are made of seperate frames, now, to make the whole thing a bit more appealing and professional looking, i'd like to make 1 main frame, and load my content panels into this 1 frame. Problem i'm having with this is passing data from the loaded in panel to the main frame, so the main frame can hide one panel to load another with data inserted in the first panel. OR another solution to my problem would be a way to dispose of a frame, but from within the seperate panel class. I have searched the www for a solution, but haven't found one so far, so, any suggestions or references to some info about this kind of issue? Any pointer is greatly appreciated

    kennethdm wrote:
    EDIT: I took a look at the cardlayout, and, although i see its relevance to my question, it still leaves me with the question how exactly i will pass data the user inputs into the first panel, to the second panel. The second panel is built by the info which is provided in the first panel.Stop thinking of them as Panels and start thinking of them as OOP objects that have data that must be shared. It's often a matter of using getters and setters and sometimes requiring a sprinkling of the Observer design pattern.

  • IMovie - adding a picture (without black frame below) in the very bottom of a video

    Hello iMoviers,
    I'd like to add a picture on top of a movie. As far as I understand this can be done by using iMovie's picture-in-picture feature. The picture, however, is centered in a black frame.
    1) How can I position the picture on the ver bottom of the video, so that there's no black frame below or let's say the picture is not centered anymore?
    2) How can I get rid of the black frames and instead have the video placed below shining through? I saw some green screen approaches, but it seemed to be very  tedious workaround.
    Thanks so much for any helpful comments,
    mikkolaus

    depends on the version of iM you're using:
    in older versions, the pic-in-pic was limited: it allowed only to insert content with the same aspect-ratio as the project itself = 16.9 .... if the pic was square, iM added 'borders' to make it fit.
    Work-around:
    make your pics 16:9 by adding transparency, read this in the UseR Tipp section of this board:
    How to create a pointer or a custom title
    or, update to latest iMovie10 ....
    here, a diff. aspect ratio of pic has no 'borders' -effect; .....

  • Strange problem loading panels in a Frame

    Hi,
    My Frame has a splitpane which has 2 Jpanels with in it. When I run my application using JWS, the frame and the splitpane show up but with nothing in it. All the class files that I'm using are all in the same package and they are all in the jar file. I do not get any null pointer exceptions too. I looked at couple of examples (Rachel's etc) and theres nothing different that I'm doing. I've been pulling my hair for past couple of days figuring out this stuff, if any one has any clue, please .... let me know. Thank You
    Viplavi

    Does it work as a stand-alone app?
    It may help you to post the code where you add the panels to the splitpane and where you display the gui etc...
    Gavin

  • Changing a panel in a frame at runtime

    I have a frame setup with buttons on the BorderLayout.WEST area. Now for each clicked event those buttons generate I want to add a panel to the SOUTH area depending on which button was pressed.
    I have all the action listeners setup, and when a button is clicked the following code is executed
    getContentPane().add(new buttonPanel(),BorderLayout.SOUTH)
    The code seems to be executing but nothing will show up in my JFrame.....
    The buttonPanel object works and if I add to the SOUTH section during design time it will show up ok. But I need to be able to change this panel to buttonPanel2() whenever the user clicks the appropriate button...

    okay that worked, the correct panels will come up, but when I click on one of the buttons that was just created, one of the previous buttons will come onto the foreground. Do I need to destroy the previous panel?
    and if so, how do i do that generically? So that I can destroy any object in the BorderLayout.SOUTH region.

  • Resize panels in a frame

    Hi, I tried searching through the forums, but am obviously using the wrong search words.
    I have a JFrame with a JPanel in it. The JPanel is using the following layout:
    new BoxLayout (parentPanel, BoxLayout.LINE_AXIS)
    Then I added two JPanels to the parentPanel.
    But then I would like to click and drag the separator between the two panels to change the size of the two JPanels.
    Any hints?
    Thanks,
    Novice

    As it turns out I should have been looking at the JSplitPane class.
    Novice

  • Swaping Panels in a frame?

    Hey, I have a frame that has a GridLayout of (1,2) so it can jold 2 Panels of equal size, when I press a button i need the 2 Panels in there to go away so I can put new ones in. This is my code to add Panels:
    public void addPanels()
             frame.getContentPane().setLayout(new GridLayout(1,2));
             frame.getContentPane().add(myLeftPanel);
             frame.getContentPane().add(myRightPanel);
         }And I have this one to switch Frames
         public void swapPanels(JPanel leftPanel, JPanel rightPanel)
             myLeftPanel = leftPanel;
             myRightPanel = rightPanel;
             addPanels();
         }I tried the remove(Component comp) meathod and it didn't work and I'v also tried the removeAll() but that didn't work either looks like it removed more then just the Panels because a can't add new ones. Any ideas?

    You don't really need to set the content pane's layout each time. Set it once and it is always set. In your addPanels method, you need to call getContentPane().removeAll() then add each panel as you are currently doing then call getConentPane().revalidate().
    public void addPanels() {
      Container contentPane = frame.getContentPane();
      contentPane.removeAll();
      contentPane.add(myLeftPanel);
      contentPane.add(myRightPanel);
      contentPane.revalidate();
    }

Maybe you are looking for