Subclass of JPanel invisible in a subclass of JFrame

I am very, very new to Java GUI, so bear with me:).
I create a subclass of JFrame and add a menu bar it. That is ok. Then I create a subclass of JPanel and added it to the contentPane of the subclass of the JFrame. But when I run the code, it is not visible, only the frame and the menu bar can be seen. I tried it differently, creating a class for the entire GUI that then creates an instance of JFrame and adds the instance of the said subclass of JPanel and it works fine. I do not see what is the difference. Also, when debugging the first version, I put the break point inside the painComponent of the JPanel subclass and it seems that the program never enters it. Can somebody please tell me why? Is the subclass of JPanel not properly added to the subclass of JFrame?
Here is the code:
* PlanITED.java
* Created on 30 de Maio de 2008, 17:53
* @author Branka
package PlanITEDLibraries;
public class PlanITED extends javax.swing.JFrame {
/** Creates new form PlanITED */
public PlanITED() {
initComponents();
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
loadMapItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("PlanITED");
fileMenu.setText("File");
fileMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileMenuActionPerformed(evt);
loadMapItem.setText("Load map");
loadMapItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadMapItemActionPerformed(evt);
fileMenu.add(loadMapItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
pack();
}// </editor-fold>//GEN-END:initComponents
private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_fileMenuActionPerformed
private void loadMapItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadMapItemActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_loadMapItemActionPerformed
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
PlanITED oPlanITED = new PlanITED();
oPlanITED.getContentPane().add(new DrawingArea());
oPlanITED.setVisible(true);
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuItem loadMapItem;
private javax.swing.JMenuBar menuBar;
// End of variables declaration//GEN-END:variables
And the code for the class DrawingArea:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package PlanITEDLibraries;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Color;
* @author Branka
public class DrawingArea extends JPanel {
@Override
public Dimension getPreferredSize() {
return new Dimension(500,500);
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("This is my custom Panel!",10,20);
g.setColor(Color.RED);
g.fillRect(0, 0, 500, 500);
Thanks!

Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.
Is the subclass of JPanel not properly added to the subclass of JFrame?That would be my guess. I have no idea how GroupLayout works but you didn't set any constraints when you added the panel to the content pane so I would guess that is the problem.
Don't use the IDE to create your code. Learn how to create GUIs yourself and then you will understand the code. Spend your time learning Java, not learning the IDE.

Similar Messages

  • Need help:JPanel not being displayed in the JFrame

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

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

  • Why won't JPanel show up in an external JFrame?

    My code generates a graph and displays it in a JPanel.
    If the class extends JFrame, the output looks exactly as it should. The problem is that I need to extend it as a JPanel so that I can imbed it in another GUI. When I modify the code so that it is a JPanel, the graph does not show up at all (except a tiny little smudge).
    What am I missing? Here is a trimmed down version:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    * @author Rob Kallman <[email protected]>
    public class GraphSSCCE extends JPanel {
         protected JPanel mainPanel;
         protected JPanel graphPanel;
         protected final int FRAME_PANEL_WIDTH = 950;
         protected final int FRAME_PANEL_HEIGHT = 400;     
         protected final int GRAPH_PANEL_WIDTH = 950;
         protected final int GRAPH_PANEL_HEIGHT = 400;
         protected final int NODE_COUNT = 3;
         protected final int node_d = 30;
         protected int centerX = GRAPH_PANEL_WIDTH/2;
         protected int centerY = GRAPH_PANEL_HEIGHT/2;
         protected java.util.List<Node> nodes = new ArrayList<Node>(NODE_COUNT);
         public GraphSSCCE() {
              //super("Graph Redux");
              this.setSize(FRAME_PANEL_WIDTH,FRAME_PANEL_HEIGHT);
              //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              mainPanel = new Graph();
              this.setBackground(Color.WHITE);
              this.add(mainPanel);
         public static void main(String args[]) {
              JFrame frame = new JFrame("Graph Test");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              GraphSSCCE gr = new GraphSSCCE();
              frame.setSize(gr.getSize());
              frame.add(gr);
              frame.setVisible(true);
    @SuppressWarnings("serial")
    class Graph extends JPanel {
         public Graph() {
              super();
              graphPanel = new JPanel();
              graphPanel.setBackground(Color.WHITE);
              graphPanel.setSize(GRAPH_PANEL_WIDTH, GRAPH_PANEL_HEIGHT);
              repaint();
         public void paint(Graphics g) {
              super.paint(g);
              int graphW = graphPanel.getWidth() - 100;
              int graphH = graphPanel.getHeight() - 100;
              //Draw Root node
              Node root = new Node(0, (graphPanel.getWidth() - 100)/4, graphH/2 + 20, node_d);
              g.setColor(Color.BLACK);
              g.fillOval(root.x-2, root.y-2, root.d + 4, root.d + 4);
              g.setColor(Color.RED);
              g.fillOval(root.x, root.y, root.d , root.d);
              //Draw site nodes
              for(int i = 0; i < NODE_COUNT; i++) {
                   double nc = NODE_COUNT;
                   double frac = i/(nc-1);
                   Node node = new Node(i, 3*(graphW)/4, (int)(frac * graphH) + 20 + (int)frac, node_d);
                   nodes.add(i, node);  // An ArrayList that contains all of the Node objects.
              // Populate network with edges from root to site     
                   for(Node noodle : nodes) {
                        g.setColor(Color.BLACK);
                        g.drawLine(root.x + root.d/2, root.y + root.d/2, noodle.x + noodle.d/2, noodle.y + noodle.d/2);
                        g.setColor(Color.BLACK);
                        g.fillOval(noodle.x - 2, noodle.y - 2, noodle.d + 4, noodle.d + 4);
                        g.setColor(Color.RED);
                        g.fillOval(noodle.x, noodle.y, noodle.d, noodle.d);
                   g.setColor(Color.BLACK);
                   g.fillOval(root.x - 2, root.y - 2, root.d + 4, root.d + 4);
                   g.setColor(Color.RED);  // Root
                   g.fillOval(root.x, root.y, root.d, root.d);
    class Node {
         protected int d;
         protected int x;
         protected int y;
         protected int node_id;
         public Node(int id, int x, int y, int d) {
              this.node_id = id;
              this.d = d;
              this.x = x;
              this.y = y;
    }

    Welcome to the Sun forums.
    >
    What am I missing? ...>That code was doing some odd things. Once I'd trimmed it down far enough to get it working, I'd made a number of undocumented changes. Have a look over this, and see if it get you back on track.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    * @author Rob Kallman <[email protected]>
    public class GraphSSCCE extends JPanel {
         public static void main(String args[]) {
              JFrame frame = new JFrame("Graph Test");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Graph gr = new Graph();
              JPanel mainPanel = new JPanel(new BorderLayout());
              mainPanel.add(gr, BorderLayout.CENTER);
              frame.setContentPane(mainPanel);
              frame.pack();
              frame.setSize(gr.getSize());
              frame.setVisible(true);
    @SuppressWarnings("serial")
    class Graph extends JPanel {
         protected final int FRAME_PANEL_WIDTH = 950;
         protected final int FRAME_PANEL_HEIGHT = 400;
         protected final int GRAPH_PANEL_WIDTH = 950;
         protected final int GRAPH_PANEL_HEIGHT = 400;
         protected final int NODE_COUNT = 3;
         protected final int node_d = 30;
         protected int centerX = GRAPH_PANEL_WIDTH/2;
         protected int centerY = GRAPH_PANEL_HEIGHT/2;
         protected java.util.List<Node> nodes = new ArrayList<Node>(NODE_COUNT);
         public Graph() {
              super();
              setBackground(Color.WHITE);
              repaint();
         public Dimension getPreferredSize() {
              return new Dimension(GRAPH_PANEL_WIDTH,GRAPH_PANEL_HEIGHT);
         /** Do not override paint() in a Swing component! */
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.setColor(getBackground());
              g.fillRect(0,0,getWidth(),getHeight());
              int graphW = getWidth() - 100;
              int graphH = getHeight() - 100;
              //Draw Root node
              Node root = new Node(0, (getWidth() - 100)/4, graphH/2 + 20, node_d);
              g.setColor(Color.BLACK);
              g.fillOval(root.x-2, root.y-2, root.d + 4, root.d + 4);
              g.setColor(Color.RED);
              g.fillOval(root.x, root.y, root.d , root.d);
              //Draw site nodes
              for(int i = 0; i < NODE_COUNT; i++) {
                   double nc = NODE_COUNT;
                   double frac = i/(nc-1);
                   Node node = new Node(i, 3*(graphW)/4, (int)(frac * graphH) + 20 + (int)frac, node_d);
                   nodes.add(i, node);  // An ArrayList that contains all of the Node objects.
              // Populate network with edges from root to site
                   for(Node noodle : nodes) {
                        g.setColor(Color.BLACK);
                        g.drawLine(root.x + root.d/2, root.y + root.d/2, noodle.x + noodle.d/2, noodle.y + noodle.d/2);
                        g.setColor(Color.BLACK);
                        g.fillOval(noodle.x - 2, noodle.y - 2, noodle.d + 4, noodle.d + 4);
                        g.setColor(Color.RED);
                        g.fillOval(noodle.x, noodle.y, noodle.d, noodle.d);
                   g.setColor(Color.BLACK);
                   g.fillOval(root.x - 2, root.y - 2, root.d + 4, root.d + 4);
                   g.setColor(Color.RED);  // Root
                   g.fillOval(root.x, root.y, root.d, root.d);
    class Node {
         protected int d;
         protected int x;
         protected int y;
         protected int node_id;
         public Node(int id, int x, int y, int d) {
              this.node_id = id;
              this.d = d;
              this.x = x;
              this.y = y;
    }

  • Can we add same JPanel twice??.. on JFrame and JDialog together!!

    Hello Frnds,
    my problem is quite weird!! i will try to explain..as much as I can !!
    My requirement is I want to show same JPanel in JDialog and JFrame at once..!!
    I am adding a
    JPanel A ---> JDialog
    JPanel A ---> JScrollPanel B
    JScrollPane B ---> JFrame.. and making frame and dialog visible together.. but JPanel is visible in dialog only..
    if i dont add in JDialog.. then JPanel is visible in frame.. !!.. but why that??
    JFrame fr = new JFrame();
    JPanel np = new JPanel();      // This JPanel is added Twice
    np.setBounds(0, 0, 128, 128);
    JScrollPane scroll=new JScrollPane(np);      // Once JPanel added here..
    scroll.setPreferredSize(new Dimension(385,385));
    fr.add(scroll);
    JDialog dlg=new JDialog(fr, "Another Panel", false);
    dlg.add(np);                        // Second Time JPanel added here..
    dlg.pack();
    dlg.setVisible(true);
    fr.setVisible(true);

    Let's make it very clear : it is NOT possible to add
    the same instance of a component to two different
    containers.
    Is it possible to have frame with component.. but on closing that frame component shifts to another frame.. and vice versa I will add to the above:
    it is NOT possible to add the same instance of a component to two different containers... at the same time. Does that clarify it?
    Why is it so hard to try it yourself?
    Instead of waiting a couple of hours hoping someone answers the question you could have solved your problem in a couple of minutes.

  • Help with adding a JPanel with multiple images to a JFrame

    I'm trying to make a program that reads a "maze" and displays a series of graphics depending on the character readed. The input is made from a file and the output must be placed in a JFrame from another class, but i can't get anything displayed. I have tried a lot of things, and i am a bit lost now, so i would thank any help. The input is something like this:
    20
    SXXXXXXXXXXXXXXXXXXX
    XXXX XXXXXXXXXXX
    X XXXXX
    X X XX XXXXXXXXXXXX
    X XXXXXXXXX XXX
    X X XXXXXXXXX XXXXX
    X XXXXX XXXXX XXXXX
    XX XXXXX XX XXXX
    XX XXXXX XXXXXXXX
    XX XX XXXX XXXXXXXX
    XX XX XXXXXXXX
    XX XXX XXXXXXXXXXXXX
    X XXXXXXXXXXXXX
    XX XXXXXXX !
    XX XXXXXX XXXXXXXXX
    XX XXXXXXX XXXXXXXXX
    XX XXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XX XXXX XXXXXXXXXXXX
    XXXXXXXXXXXXXXXXXXXX
    Generated by the Random Maze Generator
    And the code for the "translator" is this:
    package project;
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    public class Translator extends JFrame {
       private FileReader Reader;
       private int size;
       Image wall,blank,exit,start,step1,step2;
      public Translator(){}
      public Translator(File F){
      try {
           Reader=new FileReader(F);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      try {
      size=Reader.read();
      System.out.write(size);}
      catch (IOException e){
           JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
      Toolkit theKit=Toolkit.getDefaultToolkit();
      wall=theKit.getImage("wall.gif");
      blank=theKit.getImage("blanktile.jpg");
      exit=theKit.getImage("exit.jpg");
      start=theKit.getImage("start.jpg");
      step1=theKit.getImage("start.jpg");
      step2=theKit.getImage("step1.jpg");
      JPanel panel=new JPanel(){
      public void paintComponent(Graphics g) {
      super.paintComponents(g);
      int ch=0;
      System.out.print("a1 ");
      int currentx=0;
      int currenty=0;
      try {ch=Reader.read();
          System.out.write(ch);}
      catch (IOException e){}
      System.out.print("b1 ");
      while(ch!=-1){
        try {ch=Reader.read();}
        catch (IOException e){}
        System.out.write(ch);
        switch (ch){
            case '\n':{currenty++;
                      break;}
            case 'X':{System.out.print(">x<");
                     g.drawImage(wall,(currentx++)*20,currenty*20,this);
                     break;}
           case ' ':{
                     g.drawImage(blank,(currentx++)*20,currenty*20,this);
                     break;}
            case '!':{
                     g.drawImage(exit,(currentx++)*20,currenty*20,this);
                      break;}
            case 'S':{
                     g.drawImage(start,(currentx++)*20,currenty*20,this);
                      break;}
            case '-':{
                     g.drawImage(step1,(currentx++)*20,currenty*20,this);
                      break;}
            case 'o':{
                      g.drawImage(step2,(currentx++)*20,currenty*20,this);
                      break;}
            case 'G':{ch=-1;
                      break;}
                  }//Swith
          }//While
      }//paintComponent
    };//Panel
    panel.setOpaque(true);
    setContentPane(panel);
    }//Constructor
    }//Classforget all those systems.out and that stuff, that is just for the testing
    i call it in another class in this way:
    public Maze(){
        firstFrame=new JFrame("Random Maze Generator");
        firstFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        (...)//more constructor code here
        Translator T=new Translator(savefile);
        firstFrame.add(T);
        firstFrame.getContentPane().add(c);
        firstFrame.setBounds(d.width/3,d.height/3,d.width/2,d.height/4);
        firstFrame.setVisible(true);
        c.setSize(d.width/2,d.height/4);
        c.show();
        }i know it may be a very basic or concept problem, but i can't get it solved
    thanks for any help

    Try this. It's trivial to convert it to use your images.
    If you insist on storing the maze in a file, just read one line at a
    time into an ArrayList than convert to an array and pass that to the
    MazePanel constructor.
    Any questions, just ask.
    import java.awt.*;
    import javax.swing.*;
    public class CFreman1
         static class MazePanel
              extends JPanel
              private final static int DIM= 20;
              private String[] mMaze;
              public MazePanel(String[] maze) { mMaze= maze; }
              public Dimension getPreferredSize() {
                   return new Dimension(mMaze[0].length()*DIM, mMaze.length*DIM);
              public void paint(Graphics g)
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, getSize().width, getSize().height);
                   for (int y= 0; y< mMaze.length; y++) {
                        String row= mMaze[y];
                        for (int  x= 0; x< row.length(); x++) {
                             Color color= null;
                             switch (row.charAt(x)) {
                                  case 'S':
                                       color= Color.YELLOW;
                                       break;
                                  case 'X':
                                       color= Color.BLUE;
                                       break;
                                  case '!':
                                       color= Color.RED;
                                       break;
                             if (color != null) {
                                  g.setColor(color);
                                  g.fillOval(x*DIM, y*DIM, DIM, DIM);
         public static void main(String[] argv)
              String[] maze= {
                   "SXXXXXXXXXXXXXXXXXXX",
                   "    XXXX XXXXXXXXXXX",
                   "X              XXXXX",
                   "X  X XX XXXXXXXXXXXX",
                   "X    XXXXXXXXX   XXX",
                   "X  X XXXXXXXXX XXXXX",
                   "X  XXXXX XXXXX XXXXX",
                   "XX XXXXX XX     XXXX",
                   "XX XXXXX    XXXXXXXX",
                   "XX  XX XXXX XXXXXXXX",
                   "XX  XX      XXXXXXXX",
                   "XX XXX XXXXXXXXXXXXX",
                   "X      XXXXXXXXXXXXX",
                   "XX XXXXXXX         !",
                   "XX  XXXXXX XXXXXXXXX",
                   "XX XXXXXXX XXXXXXXXX",
                   "XX          XXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XX XXXX XXXXXXXXXXXX",
                   "XXXXXXXXXXXXXXXXXXXX"
              JFrame frame= new JFrame("CFreman1");
              frame.getContentPane().add(new MazePanel(maze));
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setResizable(false);
              frame.setVisible(true);
    }

  • Fitting JPanel perfectly inside content pane of JFrame

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

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

  • Issue with adding JPanel objects with layout managers

    Hi. The games I made in the past did not contain any customized menus (ie. not from JOptionPane) different components dividing the display screen... so I thought I would try to on my current game I'm working on. So here's the issue: I'm trying to set the GUI up for the game screen.. but when I try to add in additional JPanel objects into the my main JFrame object, all of the JPanel objects stack up at the very top left corner (their not supposed to because I am using a layout manager). Here's my simplified version of the code:
    public void setUpGame(){
         MainGame game = new MainGame();
         game.setLayout(new BoxLayout(game, BoxLayout.Y_AXIS) );
            playPanel = new PlayPanel(); // don't worry about this.. it's a subclass of JPanel.
         playPanel.setPreferredSize( new Dimension(playPanel.width, playPanel.height) );     
            game.add(playPanel);
            JPanel collections = new JPanel();
            collections.setLayout(new FlowLayout() );
            collections.setPreferredSize( new Dimension( 1280, 256));
            miniMapPanel = new MiniMapPanel(); // subclass of JPanel.
         miniMapPanel.setPreferredSize( new Dimension(miniMapPanel.width, miniMapPanel.height) );
            collections.add(miniMapPanel);
            statsPanel = new StatsPanel();
         statsPanel.setPreferredSize( new Dimension(statsPanel.width , statsPanel.height ) );
            collections.add(statsPanel);
            ... // I do the same thing for StatsPanel and CommandPanel objects
            game.add(collections);
            add(game);
            // referencing to the JFrame object
            this.pack();
            setVisible(true);
            setFocusable(true);
    }Notes:
    -The sum of miniMapPanel.width, statsPanel.width, ... , commandPanel.width add up to 1280 pixels.
    - miniMapPanel.height, statsPanel.height, ... , commandPanel.height all have the same height of 256 pixels.
    - What I'm trying to do is set up a GUI very similar to that of StarCraft, and WarCraft.
    - The game is set up in full screen.
    When I compile the program, I see (and I've tested for it) that all of the JPanel objects that were created are all stacked one on top of each other, in the top left corner of the screen. Any ideas and/or suggestions are welcome.

    Hi weng,
    Try the following code example. I think the issue might be in your overridden methods if you did.
        public static void main(String[] args) {
            JPanel viewPanel = new JPanel();
            viewPanel.setBackground(Color.GREEN);
            viewPanel.add(new JLabel("You see a hut here..."));
            JPanel minimapPanel = new JPanel();
            minimapPanel.setBackground(Color.WHITE);
            minimapPanel.add(new JLabel("Minimap!"));
            JPanel commandPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
            commandPanel.add(new JButton("Characters"));
            commandPanel.add(new JButton("Inventory"));
            commandPanel.add(new JButton("World Map"));
            commandPanel.add(new JButton("Menu"));
            JPanel lifeAndManaPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
            lifeAndManaPanel.add(new JLabel("Life: 999/999"));
            lifeAndManaPanel.add(new JLabel("Mana: 999/999"));
            JPanel statusPanel = new JPanel(new BorderLayout());
            statusPanel.add(commandPanel, BorderLayout.PAGE_START);
            statusPanel.add(lifeAndManaPanel, BorderLayout.CENTER);
            JPanel bottomPanel = new JPanel(new BorderLayout());
            bottomPanel.add(minimapPanel, BorderLayout.LINE_START);
            bottomPanel.add(statusPanel, BorderLayout.CENTER);
            JPanel game = new JPanel(new BorderLayout());
            game.add(viewPanel, BorderLayout.CENTER);
            game.add(bottomPanel, BorderLayout.PAGE_END);
            JFrame frame = new JFrame();
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(game, BorderLayout.CENTER);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(800, 600);
            frame.setVisible(true);
        }

  • How to embed a Jpanel in JFrame

    I have made two JPanel classes
    JPanelclass1
    JPanelclass2
    and a JFrame class
    JFrameclass1
    in netbean 5.5.1
    I want to embed that JPanel in the JFrame and when a button is clicked the ist JPanel dissaper and the second JPanel appears on the same JFrame..... i have tried to declare an object of that JPanel class in the JFrame
    Please Help

    One word: CardLayout

  • How to set an empty JPanel to maximum size?

    Hello!
    I created class extends JFrame.
    I want this maximum size so I set the minimum size as screen size:
    setSize(screenWidth,screenHeight);
    Now I added an empty JPanel,
    and I want it to be the maximum size.
    But the problem is - I don't know what is the maximum of the current size without the frame borders. I mean, after set it to maximum size (I don't know how),
    I could get the width and height of the current size without the frame borders by:
    frame.getContentPane().getSize();
    In conclusion, I want to set an empty JPanel to maximum size and get JFrame size without the frame borders.
    Thanks!

    800512 wrote:
    Now I added an empty JPanel,
    and I want it to be the maximum size.Define "maximum size". You want it to fill the screen or you want it to be the maximum size inside its container (JFrame in this case)?
    You cannot make a component break out of its container, that's for sure. So assuming you want the component to grow to the maximum size inside its container, that should already happen when you add the component to the CENTER position of the JFrame's container. By default it has a BorderLayout.

  • JPanel or JFrame

    Hi,
    Just a quick question, which is better
    public class editor extends JPanel {
    or
    public class editor extends JFrame {
    Thanks
    Ger

    Good book will explain the difference, which you really need so you can understand the level of inheritance from Object class on down. Otherwise you will be doomed to posting meaningless, pointless questions....

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

  • JPanel disappear

    I put a JPanel in a JFrame.After that I created a new JFrame where I put the last JPanel.When I saw the first JFrame the JPanel did not exist anymore.Why?
    Please help!

    A Component can only be in one Container at a time. Sorry.

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

  • Restrictions on JPanel

    Sorry, just deleted the whole post. It was about having trouble calling up a class which extends a JPanel from a class which extends a JFrame. I have messed about a little and came up with this. I have to add my JPanel class to a JFrame, so in my JFrame class (Instead of my JPanel class), when the button is pressed, i have done
         private void CreateAtlDatabase_actionPerformed()
              JFrame frame = new JFrame("MEET_dataTable");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new Meet(), BorderLayout.CENTER);
                    frame.pack();
                    frame.setVisible(true);
              } It works but is it ok doing this?
    Previously, this was in my JPanel class
      private static void createAndShowGUI() {
            JFrame frame = new JFrame("MEET_dataTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Meet(), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
       Edited by: nick2price on Sep 15, 2008 7:19 AM

    Its the tutorials i have followed, but none of them call up a JPanel class from a JFrame class. This is why i done the code above, but i am just not too sure if it is correct. It runs fine, but as i say, if its bad coding i would prefere to remove it.

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

Maybe you are looking for

  • Where is the Phonegap template in Dreamweaver CS6

    Hi just wondering if someone can clear this up for me. I have just downloaded the trial of Dreamweaver CS6 and am wondering where the jQuery mobile (phonegap) template has gone? Is there a way i can get it back? Im just curious as the jQuery mobile t

  • CC desktop application won't launch, can't download from site

    I am a new CC member. I downloaded the application yesterday - it shows on my (Windows) desktop, but nothing happens when I click it. I tried logging into the Adobe website, but when I attempt to download an application, nothing happens again. I've t

  • How do i clear java caches for Mac OS X, version 10.6.8?

    how do i clear java caches for Mac OS X, version 10.6.8?

  • Trying to transfer Time Machine to Computer

    So I recently brought my MacBook Pro (Leopard 10.6.4) to the campus computer store because it was freezing nonstop. They told me they needed to "wipe" the hard drive to better ***** the problem. I had backed up my files w/ Time Machine that day so I

  • Controlling Amplitube in Mainstage

    I am unable to map a Mainstage screen control to any of Amplitube's parameters. Yet I have no problem with Guitar Rig. I do the same procedure for both: click on the screen control, select Map Parameter, move the parameter in Amplitube (e.g. the wah