Add JPanel to a JFrame

I have two classes. One is the main frame, and the other class is a panel. The constructor of the main frame looks like this:
          JFrame.setDefaultLookAndFeelDecorated(true);
          JFrame frame = new JFrame("main");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JPanel entryMgmt = new EntriesMgmt(dbConn);     
          frame.getContentPane().add(entryMgmt);
          frame.pack();
          frame.setVisible(true);The EntriesMgmt class extends JPanel. The constructor for it looks like this:
public EntriesMgmt(SqlBackend.DbConn conn){
          this.conn = conn;
          JPanel pane = new JPanel();
          //Add radio buttons
          pane.add(initRadioBtns());
          //Add input area
          pane.add(initInputArea());
          //Add buttons
          pane.add(initButtons());
     }The problem is that only the main window appears and there is nothing in it. I tried creating another JFrame in the EntriesMgmt constructor but it would cause 2 windows to appear and i don't want to use internalFrame because what I'm actually trying to do is have a JTabbedPane in the main window and I would have external JPanel under each tab. But let's concentrate on why is it that my EntriesMgmt panel does not appera in the main window.

What i did to fix this problem was the following. Since EntriesMgmt class extends JPanel I did not have to define another JPanel in the constructor but I could directly add components. Instead of :
public EntriesMgmt(){
JPanel pane = new JPanel();
          //Add radio buttons
          pane.add(initRadioBtns());
          //Add input area
          pane.add(initInputArea());
          //Add buttons
          pane.add(initButtons());I have:
public EntriesMgmt(){
          //Add radio buttons
          add(initRadioBtns());
          //Add input area
          add(initInputArea());
          //Add buttons
          add(initButtons());And somehow it works. Anyways I would like to know if there was any other way to do it.

Similar Messages

  • 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 replace one JPanel on a JFrame with another?

    I want to replace one JPanel on a JFrame with a different JPanel when the user clicks on a certain menu item. The menu item is working corrrectly but I cant seem to repaint / refresh the component.
    My code is as follows:
    c.add(knotPanel, BorderLayout.CENTER);
    c.add(stepPanel, BorderLayout.NORTH);
         if (stepChoice != 9) {
         c.remove(ownPanel);
         c.add(lessonPanel, BorderLayout.EAST);
         else {
         c.remove(lessonPanel);
         c.add(ownPanel, BorderLayout.EAST);
         c.invalidate();
         c.validate();
         c.update(c.getGraphics());
    Any ideas?

    I think you should use CardLayout manager.
    With CardLayout you can switch beetwen JPanels without removing or adding.

  • 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

  • Can i add JPanel to Jasper Report

    I have a panel on which I have drawn some graphics and now I want this panel to be added on report, is this possible?
    Can we add Jpanel to Jasper report, if anybody has any thoughts and ideas please share with me?
    Thanks & regards,
    - Prashant

    Don't know exactly what you mean but this is how I add a JPanel to a JScrollPane.
    public class Scroll extends JFrame{
    JScrollPane jsp;
    JPanel panel;
    public Scroll(){
    jsp = new JScrollPane();
    panel = new JPanel();
    jsp.getViewPort().add(panel);
    getContentPane().add(jsp, BorderLayout.CENTER)
    }

  • Add a Button in JFrame Title Bar

    How can I add a button in JFrame Title Bar. I want to put on more button for docking after the closing button in the title bar.

    if you use JFrame.setDefaultLookAndFeelDecorated(true) then you can do it by extending the JRootPaneUI class of the L&F (the default is the metal L&F). that is not a easy task but if you want take a look at BasicRootPaneUI, there you will have to point it to a new TitlePane which you will have to create. to load all this you must use the UIManager class. if you need more explaination try reading on look and feel and customizing it.

  • How to add JPanel in  JComboBox?

    Hi.
    How to add JPanel in JComboBox...?
    Regards
    Bilal

    I do not know much about Cardlayout.
    As far as I know, it is a layout which let you assign a serveral 'card' and exist together. By consider the order of the card, you could change the view of each page by using method- first, last, next etc. However, I would like to know what if I got a number of buttons, say A B C D E F, and having cards called a b c d e f,I know I could change from a to b, but what if I want to change from c to e by pressing the button E (assuming it showing the c card now).
    Actually, I was able to create the code now which adding one JPanel to another now. First create a JPanel with prefer size, min max size.
    then add a JPanel into the CENTER of the above JPanel, both using borderlayout.
    But having a little difficulties, could I add more JPanel into the CENTER such that one overlapping each other, by those Buttons, through action and event, hide those which I do not want to show?
    Like A B C buttons, a b c panels. When press A hide b c and show a, so on.
    Could I use method like movetofront(something like that, forgot detail which read in a book) to do this?
    Cheers

  • How to have focus in 2 JPanels on 1 JFrame?

    Hey all..
    Like i wrote in the subject, how can i do that?
    I have 2 JPanels in 1 JFrame. 1 top JPanel and 1 buttom JPanel. I've a keylistener in top JPanel and a buttonslistener in buttom JPanel. When i press on the button on the buttom JPanel, then my keylistener wont trigger in the top JPanel.
    Plz help.
    Thx.

    The whole point to window focus is to avoid this! There is at most one focused component per window.
    As a rule of thumb, when someone uses a KeyListener, they're mistaken. You should be using key binding. This can make your focus problems go away, since you can choose to associate the keyStoke with the whole window, not just the focused component.
    [http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]

  • How to add JPanel,JFrame to JSP Page so that it does'nt popup

    i have added a JPanel jp1
    which is as follows
    <%JPanel jp1 = new JPanel();%>
    i am getting a error in the page in webbrowser
    javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=null,alignmentY=null,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
    also i have added a frame as follows
    <%adminlog adllogz = new adminlog();%>
    <%adllogz.setVisible(true);%>
    so these two lines of code make a poop up window of adminlog
    from a webbrowser
    what i want is that these two lines of code should not do
    a pop up but come inside a webbrowserPlease tell asap

    The problem is that you used position:absolute, my post talked about using position:fixed.
    Also your image does not need to be inside the adBox, just use adImage by itself with this CSS:
    #adImage{
    background-color: #FF0000;
    position:fixed;
    bottom:0px;
    right:0px;
    width:100px;
    height: 100px;
    will fix adImage to bottom right 0 px from the edge of window. If you want a little separation, just change
    bottom:0px;
    right:0px;
    to 5 or 10 px or so.
    No jQuery needed.
    Best wishes,
    Adninjastrator

  • How to add an image to JFrame....

    Hello evryone,
    Here i'm posting my code..and in this i would like to add a .jpg file as background..I hav tried for imageicon and Bufferdimage...
    Help me out...
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    import java.lang.*;
    import java.awt.image.*;
    import java.awt.Container.*;
    import java.io.FileInputStream.*;
    import java.io.*;
    import javax.imageio.*;
    public class Kbc extends JFrame implements ActionListener
    Container c;
    JButton b1,b2,b3;
    JLabel l;
    public Kbc()
    c = getContentPane() ;
    c.setLayout(null) ;
    l=new JLabel("--:WeLcoMe :--");
    Font f = new Font("Dialog", Font.PLAIN, 24);
    l.setFont(f);
    l.setBounds(300,30,1100,20);
    c.add(l);
    b1=new JButton("START");
    b1.setFont(f);
    b1.setPreferredSize( new Dimension(200,100) ) ;
    b1.setSize( b1.getPreferredSize() ) ;
    b1.setLocation(350,100) ;
    b1.addActionListener(this) ;
    c.add(b1) ;
    b2=new JButton("QUIT");
    b2.setFont(f);
    b2.setPreferredSize( new Dimension(200,100) ) ;
    b2.setSize( b2.getPreferredSize() ) ;
    b2.setLocation(350,210) ;
    b2.addActionListener(this) ;
    c.add(b2) ;
    b3=new JButton("HELP");
    b3.setFont(f);
    b3.setPreferredSize( new Dimension(200,100) ) ;
    b3.setSize( b3.getPreferredSize() ) ;
    b3.setLocation(350,320) ;
    b3.addActionListener(this) ;
    c.add(b3) ;
    setSize(1100,700);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if(e.getSource()==b1)
    new Start1();
    this.hide();
    else
    if(e.getSource()==b2)
    System.exit(0);
    if(e.getSource()==b3)
    JOptionPane.showMessageDialog(c,"RuLes"");
    public static void main(String args[])
    Kbc k=new Kbc();
    /*<applet code="Kbc" height=500 width=900>
    </applet>*/
    {code}{code}

    Hi,
    extends JFrame is application.
    If applet extends JApplet.
    Here is an example of the application.
    Please run this way java Kbc test.jpg
    test.jpg is the background image. Please change file name.
    public class Kbc extends JPanel implements ActionListener {
    private JButton b1, b2 , b3 ;
    private JLabel l ;
    static private String filename ;
    private Image image ;
    private JLayeredPane layeredPane ;
    public Kbc() {
         layeredPane = new JLayeredPane() ;
         layeredPane.setPreferredSize( new Dimension(1100,700) ) ;
    l=new JLabel(":Wellcome :");
    Font f = new Font("Dialog", Font.PLAIN, 24);
    l.setFont(f);
    l.setBounds(300,30,1100,20);
    layeredPane.add(l, new Integer( 3 ) );
    b1=new JButton("START");
    b1.setFont(f);
    b1.setPreferredSize( new Dimension(200,100) ) ;
    b1.setSize( b1.getPreferredSize() ) ;
    b1.setLocation(350,100) ;
    b1.addActionListener(this) ;
    layeredPane.add(b1,new Integer( 1 ) ) ;
    b2=new JButton("QUIT");
    b2.setFont(f);
    b2.setPreferredSize( new Dimension(200,100) ) ;
    b2.setSize( b2.getPreferredSize() ) ;
    b2.setLocation(350,210) ;
    b2.addActionListener(this) ;
    layeredPane.add(b2, new Integer( 2 ) ) ;
    b3=new JButton("HELP");
    b3.setFont(f);
    b3.setPreferredSize( new Dimension(200,100) ) ;
    b3.setSize( b3.getPreferredSize() ) ;
    b3.setLocation(350,320) ;
    b3.addActionListener(this) ;
    layeredPane.add(b3, new Integer( 5 )) ;
    add( layeredPane);
    public void paintComponent (Graphics g) {
              super.paintComponent(g);
    try {
    File f = new File(filename);
    BufferedImage image = ImageIO.read(f);
    g.drawImage(image, 0, 0, this);
    } catch (Exception ex) {
    ex.printStackTrace();
    public void actionPerformed(ActionEvent e) {
    if (e.getSource()==b1)
    // new Start1();
    this.setVisible(false) ;
    else if (e.getSource()==b2) {
    System.exit(0);
    } else if (e.getSource()==b3) {
    JOptionPane.showMessageDialog(this,"RuLes");
    public static void main(String args[]) {
    filename = args[0] ;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    private static void createAndShowGUI() {
    System.out.println("Created GUI on EDT? "+
    SwingUtilities.isEventDispatchThread());
         Kbc k=new Kbc();
    JFrame frame = new JFrame("Kbc");
         frame.add(k);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(1100, 700 ) );
    frame.setVisible(true);
    }

  • One JPanel is missing after adding two JPanels to a JFrame

    I have two classes, ScoreTableView and CardView, which both extends the JPanel class. ScoreTableView is used to show one table only, and CardView is to show a set of cards for a memory game. My objective is to separate the development of the panels, so that it will easier to modify either of them later. I add instances of these two class to the contentPane of my top level JFrame object. However, I can only see the ScoreTableView(which is supposed to show me a table only) on the top part of the frame, and the CardView panel never show up.
    ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
            scoreTable = new JTable();//this scoreTable is a JTable object
            scoreTable.setModel(scoreTableData);  //scoreTableData is my data    
            JScrollPane jsp = new JScrollPane(scoreTable);          
            p = this;
            p.setLayout(new BorderLayout());
            p.add(jsp, BorderLayout.CENTER);
        }CardView.java
    public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            JPanel cardPanel = new JPanel();
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
          // ... more other none GUI coiding 
             }Here's what I have in my main
            Container contentPane = jf.getContentPane();//jf is the JFrame object          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);      

    Sorry, but I copied the wrong files. Now both panels can show up, but the score table is on the NORTH, and the card panel is on the SOUTH(although I set it to CENTER and wish it can occupy the rest of the window), but the center part of the window has nothing. How can I get rid of the white space, so that the score panel can can 30% of the top part of the window(even after resize), and the card panel can occupy the remaining 70%? I can't attach pictures here, otherwise I can upload some screenshot to show you what's the problem I have. Thank you in advance.
    This is my CardView class, I didnt' copy all of them upstair.
    public class CardView extends JPanel{
        private int cardWidth;
        private int cardHeight;
        private CardModel cm;
        private JPanel cardPanel;
        public CardView(int w, int h){
            cardWidth = w;
            cardHeight = h;
            cardPanel = this;
            cardPanel.setLayout(new GridLayout(cardWidth,cardHeight)); 
            CardImageButton[][] cardsButtons = new CardImageButton[cardWidth][cardHeight];
            int[][] list  = init(cardWidth, cardHeight);       
            cm = new CardModel(list);
            int count = 0;
            for(int i=0;i<cardWidth;i++){
                for(int j=0;j<cardWidth;j++){
                    cardsButtons[i][j] = new CardImageButton("Press me"+count, cm, i, j, 0);
                    cardPanel.add(cardsButtons[i][j]);
                    count++;               
    public int[][] init(int n, int m){
            int[][] list  = {
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2},
                    {1, 2, 1, 1},
                    {2, 1, 2 , 2} };
            return list;
        }This is from my main.
           //setup the content panel
            Container contentPane = jf.getContentPane();          
            contentPane.setLayout(new BorderLayout()); 
    //      create the score panel                 
            ScoreTableView scoreTableView = new ScoreTableView(4);
          contentPane.add( scoreTableView, BorderLayout.NORTH);
            //create the cards panel
            CardView cardPanel = new CardView(4,4);
            contentPane.add(cardPanel, BorderLayout.CENTER);
            jf.pack();
            jf.setVisible(true);   ScoreTableView.java
      public ScoreTableView(int numberOfPlayer){
    //      Create a model of the data.
    scoreTable = new JTable();//this scoreTable is a JTable object       
    scoreTable.setModel(scoreTableData);  //scoreTableData is my data            
    JScrollPane jsp = new JScrollPane(scoreTable);                  
    p = this;       
    p.setLayout(new BorderLayout());       
    p.add(jsp, BorderLayout.CENTER);   
    }

  • Placing JPanels in a JFrame

    Hi,
    In my program I plan to put JPanels, containing Traffic Lights (data calculated somewhere else in my program) inside a JFrame. At the moment I have a problem with getting the panels where I want them.
    When I construct the JFrame, I set its size to be screen wide, and a bit less higher than screen height:
    public class TlsFrame extends JFrame implements WindowListener,
                                                    Observer {
         private JComponent component;
         public TlsFrame (String title, TlsModel theModel, TlsView theView) {
              super(title);
              model = theModel;
              model.addObserver(this);
              view = theView;
              // Default close operation
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              addWindowListener (new CloseListener() );
              setup();   
         private void setup () {
              setBackground (Color.WHITE);
              setLayout(new GridBagLayout());
              // Set the size of the window so in covers the whole screen
              dimension = Toolkit.getDefaultToolkit().getScreenSize();
              setBounds (0, 0, dimension.width, dimension.height - 200);
              // Create the Menu bar
              tlsMenu = new TlsMenu(model);
              tlsMenu.createMenuBar();         
              // Create the Panel used to log in (replaced later with the traffic lights)
              logInPanel = new LogInPanel(model);
              add(logInPanel);
              logInPanel.requestFocusInWindow();
              setVisible (true);
         }After logging in, I am ready to display the traffic lights:
         private void setUpTrafficLights() {
              // Remove all previous traffic lights from the panel
              if (component != null) {
                   removeAll();
              component = createComponent();
              add(component);
              setVisible (true);
         private JComponent createComponent () {
              JPanel panel = new JPanel ();
              panel.setBounds (0, 0, dimension.width, 300);
              // X coordinate for the different traffic lights
              int xCoordinate = 0;
              // Add the Customers as TrafficLights to the panel
              for (int i = 0; i < view.getTrafficLights().size(); i++) {
                   TrafficLight light = (TrafficLight) view.getTrafficLights().get(i);
                   light.setBounds(INSETS + xCoordinate, INSETS, light.getWidth(), light.getHeight());
                   System.out.printoln ("info", "TlsFrame.createComponent: light.getBounds()=" + light.getBounds());
                   xCoordinate += light.getWidth();
                   panel.add(light);
              return panel;
         }The logging I get about this part is:
    TlsFrame.createComponent: light.getBounds()=java.awt.Rectangle[x=2,y=2,width=144,height=266]
    TlsFrame.createComponent: light.getBounds()=java.awt.Rectangle[x=146,y=2,width=100,height=266]
    TlsFrame.createComponent: light.getBounds()=java.awt.Rectangle[x=246,y=2,width=108,height=266]But although I place my TrafficLight's to be placed on the top row, they are placed in the middle of my screen. And that is not what I expected. Is there a LayoutManager I need to set, or set to null (tried it, but that did not help)?
    Abel
    Edited by: Abel on Feb 12, 2008 9:31 AM
    I just found out I use the BorderLayout

    Found it.
         private void setUpTrafficLights() {
              // Remove all previous traffic lights from the panel
              if (component != null) {
                   removeAll();
              component = createComponent();
              add(component);
              this.setLayout(null);
              addItem ("info", "TrlsFrame.setUpTrafficLights: current layoutManager is " +
                        this.getLayout());
              setVisible (true);
         }Logging is your friend:
    while (problemNotFound) {
        addLogging();
    }

  • JPanel inside a JFrame

    How do you make a JPanel resize automatically with its parent JFrame?
    Thanks,
    -Zom.

    Use BorderLayout for the JFrame and set the JPanel at centre like this:myJFrame.getContentPane().setLayout(new BorderLayout());
    myJFrame.getContentPane().add(myPanel,  JFrame.CENTER);

  • 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();
    }

Maybe you are looking for

  • URL to open an inner PDF within PDF portfolio

    Can we open specific inner PDF within PDF portfolio by using URL, like http://www.myserver.com/files/myPDFportfolio.pdf?inner=adc.pdf ? Imagine a PDF portfolio that includes following multiples files in it. mytest.pdf abc.pdf test.xls test2.doc What

  • Including large number of jars in classpath...

    Hello, I have an application that relies on over 100 jars and a set of classes - I have been using an IDE to set the classpath so far, which has been fine, but I need to distribute the application to others, and so need to bundle the classes, prefera

  • Query designer error

    hi all, while i am trying to do changes in BEX Query designer, following error occurs and not allowing me do the changes(like drag and droppinf of char and key fig in rows and colums) errors 1 Bex transport request is not suitable or available 2 choo

  • Custom JAAS Login Module

    I have a question about sample in "Developing security providers for weblogic server" of WebLogic 7.0 In 3-21 in the document, abort() method may be called n times after abort. Why is it possible that abort() method is called many times? Regards,

  • Issue creating ipa file

    Hi, Im trying to create a ipa file from an swf created in Flash Builder Burrito using Flex Hero. Im using ./pfi.bat -package -target ipa-test -provisioning-profile FlexProfile.mobileprovision -storetype pkcs12 -keystore Certificates.p12 pass MyFlexAp