Results 1 to 2 of 2
  1. #1
    AMCNovember is offline Member
    Join Date
    Nov 2011
    Posts
    7
    Rep Power
    0

    Default JPanel not displaying after adding JMenu logic

    I was able to get a version of this program working that just used a JPanel.
    I changed the logic to use JFrame so I could add a JMenu and display the
    panel, but the JPanel with my shapes isn't displaying now. Thanks for your help

    Java Code:
    // Filename: ColorChooserFrame.java
    // Program: ColorChooser
    // Written by: 
    // Description:
    // This program declares a subclass of JPanel called MyColorChooser that
    // provides three JSlider objects and three JTextField objects.  Each JSlider
    // represents the values from 0 to 255 for the red,green and blue parts of a
    // color.  These values are the arguments to the Color constructor to create a
    // new Color object.  The current value of each JSlider is displayed in the
    // corresponding JTextField.  When the user changes the value of the JSlider,
    // the JTextField is changed accordingly.  The current color value can be
    // drawn in a filled/unfilled shape the user can choose from a JComboBox.  If
    // the user updates the value in the JTextField, the corresponding slider is
    // updated with the changed value.  Also the user can drag the mouse across the
    // drawing panel to draw a shape in the current color.  The user can also
    // terminate the application by clicking the close box on the window that is
    // displayed and by selecting Exit from a File menu.
    //
    //
    // Difficult aspects: Adding the Menu bar
    //
    // Time Spent: 8.0 hours
    //
    //                   Revision History
    // Date:                   By:               Action:
    // ---------------------------------------------------
    // 12/17/2011             ()              Created
    
    //package guiPrograms
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JMenuBar;
    
    public class ColorChooserFrame extends JFrame
    {
        public JDesktopPane theDesktop;
        public ColorChooserFrame()
        {
            super( "Color Chooser");
    
            JMenuBar bar = new JMenuBar();
            JMenu fileMenu = new JMenu( "File" ); // create file menu
            JMenuItem exitItem = new JMenuItem( "Exit" ); // create exit item
    
            fileMenu.add( exitItem ); // add exit item to file menu
            bar.add( fileMenu); // add File menu to menu bar
            setJMenuBar( bar ); // set menu bar for this application
    
            MyColorChooser colorChooserPanel = new MyColorChooser();
            add(colorChooserPanel); //add to frame     
    
            exitItem.addActionListener(
                    new ActionListener() //anonymous inner class
                    {
                    // terminate application when user clicks exitItem
                    public void actionPerformed( ActionEvent event )
                       {
                       System.exit( 0 ); // exit application
                       }  // end method actionPerformed
                    } // end anonymous inner class
          ); // end call to addActionListener
    
        }// end Menu Frame Constructor
    
    }// end class MenuFrame
    
    class MyColorChooser extends JPanel
       {
        //Create the GUI Compoenents
        //Labels:
        private JLabel redLabel,greenLabel,blueLabel;
        //Sliders:
        private JSlider redSlider,greenSlider,blueSlider;
        //TextFields:
        private JTextField redTextField,greenTextField,blueTextField;
        //Panels:
        private static JPanel redPanel,greenPanel,bluePanel,choicePanel,colorPanel,
                              colorChooserPanel;
        //ComboBox for shapes:
        private JComboBox shapeComboBox;
        //CheckBox for fill option:
        private JCheckBox fillJCheckBox;
        //array to determine shape options for comboBox:
        private static final String[] shapes = { "rectangle","square", "oval","circle",
                                                 "line", "rounded rectangle"};
        private static int choice = 0; //initialize to a default value
        private int solid; // stores the fill type
        private int nbr1,nbr2,nbr3; //convert textfield value to integer
        private int holdNbr1,holdNbr2,holdNbr3; //held value of textfield
        private int holdSlider1,holdSlider2,holdSlider3; // held value of sliders
        //set up variable for free-form drawing portion:
        private int pointCount = 0;// count number of points
        // array of 10000 java.awt.Point references
        private Point[] points = new Point[ 10000 ];
    
        public MyColorChooser()
           {
    
            setBackground( Color.WHITE);
            // set up mousehandler for draging the mouse events
            MouseHandler mouseHandler = new MouseHandler();
            addMouseListener( mouseHandler );
            addMouseMotionListener( mouseHandler );
            // build choicePanel:
            // set up comboBox for shape choices and register its handlers
            shapeComboBox = new JComboBox( shapes);
            ShapeHandler shapeHandler = new ShapeHandler();
            shapeComboBox.addItemListener( shapeHandler);
    
            // set up fillCheckbox and register its event handler
            fillJCheckBox = new JCheckBox( "Filled");
            CheckBoxHandler checkBoxHandler = new CheckBoxHandler();
            fillJCheckBox.addItemListener( checkBoxHandler);
    
            choicePanel = new JPanel();
            choicePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            choicePanel.add( shapeComboBox);
            choicePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
            choicePanel.add( fillJCheckBox);
    
            // set up labels
            redLabel = new JLabel( "Red:");
            greenLabel = new JLabel( "Green");
            blueLabel = new JLabel( "Blue");
    
            // set up sliders and register their event handler:
            redSlider = new JSlider(SwingConstants.HORIZONTAL,0,255,50);
            redSlider.setMajorTickSpacing( 10 ); // create tick every 10
            redSlider.setPaintTicks( true ); // paint ticks on slider
            greenSlider = new JSlider(SwingConstants.HORIZONTAL,0,255,100);
            greenSlider.setMajorTickSpacing( 10 ); // create tick every 10
            greenSlider.setPaintTicks( true ); // paint ticks on slider
            blueSlider = new JSlider(SwingConstants.HORIZONTAL,0,255,200);
            blueSlider.setMajorTickSpacing( 10 ); // create tick every 10
            blueSlider.setPaintTicks( true ); // paint ticks on slider
    
            // slider event handling:
            SliderHandler sliderHandler = new SliderHandler();
            redSlider.addChangeListener( sliderHandler);
            greenSlider.addChangeListener( sliderHandler);
            blueSlider.addChangeListener( sliderHandler);
    
             // set up textFields and register their event handler:
            redTextField = new JTextField( 3);
            redTextField.setText("50"); //initialize
            holdNbr1 = 50;
            greenTextField = new JTextField( 3);
            greenTextField.setText("100"); //initialize
            holdNbr2 = 100;
            blueTextField = new JTextField( 3);
            blueTextField.setText("200"); //initialize
            holdNbr3 = 200;
            TextFieldHandler handler = new TextFieldHandler();
            redTextField.addActionListener( handler);
            greenTextField.addActionListener( handler);
            blueTextField.addActionListener( handler);
    
            // build colorPanel:
            // build redPanel:
            redPanel = new JPanel();
            redPanel.setLayout( new FlowLayout( FlowLayout.LEFT));
            redPanel.add(redLabel);
            redPanel.setLayout( new FlowLayout( FlowLayout.CENTER));
            redPanel.add(redSlider);
            redPanel.add(redTextField);
            // build greenPanel:
            greenPanel = new JPanel();
            greenPanel.setLayout( new FlowLayout( FlowLayout.LEFT));
            greenPanel.add(greenLabel);
            greenPanel.setLayout( new FlowLayout( FlowLayout.CENTER));
            greenPanel.add(greenSlider);
            greenPanel.add(greenTextField);
            // build bluePanel:
            bluePanel = new JPanel();
            bluePanel.setLayout( new FlowLayout( FlowLayout.LEFT));
            bluePanel.add(blueLabel);
            bluePanel.setLayout( new FlowLayout( FlowLayout.CENTER));
            bluePanel.add(blueSlider);
            bluePanel.add(blueTextField);
            colorPanel = new JPanel();
            colorPanel.add(redPanel);
            colorPanel.add(greenPanel);
            colorPanel.add(bluePanel);
            
            solid = 2;  // initialize to unfilled shape
    
           }// end MyColorChooser constructor
    
     private class MouseHandler extends MouseAdapter
        {
            //store drag coordinates and repaint
            public void mouseDragged( MouseEvent event)
                   {
                     if ( pointCount < points.length )
                       {
                           points[ pointCount] = event.getPoint();
                           pointCount++;
                           repaint();
                       }//end if
                  }//end method mouseDragged
        }//end class MouseHandler
    
        private class ShapeHandler implements ItemListener
        {
               //respond to JComboBox events
               public void itemStateChanged( ItemEvent event )
               {
                   choice = shapeComboBox.getSelectedIndex();
                   repaint();
               }//end method itemStateChanged
    
        }//end private inner class ShapeHandler
    
         private class CheckBoxHandler implements ItemListener
        {
               //respond to Checkbox events
               public void itemStateChanged( ItemEvent event )
               {
                   //determine whether item selected
                   if ( event.getStateChange() == ItemEvent.SELECTED )
                       solid = 1;  //fill shape
                   else
                       solid = 2;  //draw shape
    
                   repaint();
    
               }//end method itemStateChanged
        }//end private inner class CheckBoxHandler
    
         //private inner class for event handling
         private class TextFieldHandler implements ActionListener
           {
             // respond to textField events
             public void actionPerformed( ActionEvent event )
             {
                 String inputNbr1 = redTextField.getText();
                 int nbr1 = Integer.parseInt( inputNbr1 );
                 String inputNbr2 = greenTextField.getText();
                 int nbr2 = Integer.parseInt( inputNbr2 );
                 String inputNbr3 = blueTextField.getText();
                 int nbr3 = Integer.parseInt( inputNbr3 );
    
                 if (nbr1 != holdNbr1)
                    {
                     redSlider.setValue(nbr1);  // update red slider
                     holdNbr1 = nbr1;
                     }// end if
                 else if (nbr2 != holdNbr2)
                      {
                       greenSlider.setValue(nbr2); // update green slider
                       holdNbr2 = nbr2;
                      }// end if
                 else if (nbr3 != holdNbr3)
                      {
                       blueSlider.setValue(nbr3); // update blue slider
                       holdNbr3 = nbr3;
                      } // end if
                 repaint();
             }// end method actionPerformed
          }// end private inner class TextFieldHandler
    
         // private innter class for slider events:
         private class SliderHandler implements ChangeListener
           {
             // respond to slider events
             public void stateChanged( ChangeEvent e )
               {
                 if (holdSlider1 != redSlider.getValue());
                   {
                     holdSlider1 = redSlider.getValue();
                     holdNbr1 = redSlider.getValue();
                     redTextField.setText("" + redSlider.getValue()); // update redTextField
                   }// end if
    
                 if (holdSlider2 != (greenSlider.getValue()));
                   {
                     holdSlider2 = greenSlider.getValue();
                     holdNbr2 = greenSlider.getValue();
                     greenTextField.setText("" + greenSlider.getValue());// update greenTextField
                   }// end if
                 if (holdSlider3 != (blueSlider.getValue()));
                   {
                     holdSlider3 = blueSlider.getValue();
                     holdNbr3 = blueSlider.getValue();
                     blueTextField.setText("" + blueSlider.getValue());// update greenTextField
                   }// end if
                 //update value for color here:
                 repaint();
    
               }// end method stateChanged
           }// end anonymous inner class
    
        public void paintComponent ( Graphics g )
        {
            super.paintComponent( g ); //call superclass's paintComponent
    
              g.setColor( new Color( holdNbr1,holdNbr2,holdNbr3 ) );
    
              //using index from jcombobox, decide which shape to draw
              switch ( choice )
              {
                case 0:  //draw rectangle
                if (solid == 2)
                     g.drawRect(350, 150, 300, 120 );
                   else
                    g.fillRect(350, 150, 300, 120 );
                break;
                case 1:  //draw square
                if (solid == 2)
                     g.drawRoundRect(350, 150, 140, 140, 0, 0 );
                   else
                    g.fillRoundRect(350, 150, 140, 140, 0, 0 );
                break;
                 case 2:  //draw oval
                if (solid == 2)
                     g.drawOval(300, 160, 280, 125 );
                   else
                    g.fillOval(300, 160, 280, 125 );
                break;
                 case 3:  //draw circle
                if (solid == 2)
                     g.drawRoundRect(320, 130, 240, 240, 240, 240 );
                   else
                    g.fillRoundRect(320, 130, 240, 240, 240, 240 );
                break;
                case 4:  //draw line
                     g.drawLine(500, 200, 340, 40);
                break;
                 case 5:  //draw rounded rectangle
                if (solid == 2)
                     g.drawRoundRect(300, 110, 290, 255, 240, 280 );
                   else
                    g.fillRoundRect(300, 110, 290, 255, 240, 280 );
                break;
              }//end switch
    
        //     draw all points in array if mouse was dragged to draw
                  for ( int i = 0; i< pointCount; i++)
                    g.fillOval( points[ i ].x, points[i].y, 4, 4);
    
        }//end method paintComponent
    
    public static void main( String args[])
           {
        ColorChooserFrame colorChooserFrame = new ColorChooserFrame();
        colorChooserFrame.add( choicePanel);
        
        colorChooserFrame.add(colorPanel,BorderLayout.SOUTH);
        colorChooserFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        colorChooserFrame.setSize( 900, 500);  //set width and height;
        colorChooserFrame.setVisible( true );  //display GUI, Automatically calls paintComponent
           }// end main method
    } //end class MyColorChooser

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: JPanel not displaying after adding JMenu logic

    Suggestions:
    • Get rid of all static variables -- There's no reason your program should have these as they'll only mess things up.
    • Read about layouts, and about default layouts in particular. There you'll see that a JFrame (its contentPane actually) uses BorderLayout by default, and why this effects you when you add more than one component to the JFrame's BorderLayout.CENTER position (its default position).

Similar Threads

  1. Adding a JPanel to a JMenu - Focus issues
    By snoopygee in forum AWT / Swing
    Replies: 9
    Last Post: 05-06-2011, 10:53 AM
  2. Displaying text in a JPanel
    By DrKilljoy in forum New To Java
    Replies: 7
    Last Post: 04-15-2011, 08:28 PM
  3. Adding a jpanel to a customized Jpanel Class
    By trishtren in forum AWT / Swing
    Replies: 7
    Last Post: 04-05-2011, 07:52 PM
  4. Adding Jpanel ontop of another Jpanel
    By Manfizy in forum AWT / Swing
    Replies: 4
    Last Post: 03-05-2011, 11:34 PM
  5. Replies: 3
    Last Post: 01-06-2008, 12:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •