Results 1 to 11 of 11
  1. #1
    Chanel is offline Member
    Join Date
    Jul 2010
    Posts
    5
    Rep Power
    0

    Default JPanel Array with Color arrray

    What I am trying to accomplish here is to use borderlayout and place a JButton in the center. Now the other sections of borderlayout are panels that change to the appropriate background color when the center button is pressed.

    This is what I have so far...

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class JColorFrame extends JFrame implements ActionListener
    {
    	private JPanel[] panel = new JPanel[3];
    	private JPanel pane = new JPanel(new BorderLayout());
    	private Color[] colors = new Color[]{Color.PINK, Color.GREEN, Color.BLACK, Color.RED};
    	//private JPanel nb = new JPanel();
    	//private JPanel sb = new JPanel();
    	//private JPanel eb = new JPanel();
    	//private JPanel wb = new JPanel();
    	private JButton cb = new JButton("Change Color");
    	private Container con = getContentPane();
    	
    	public JColorFrame()
    	{
    		super("Color Swtich");
    		//sets close button and sets layout
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		//contains the visible contents, sets and adds them to components
    		add(pane);
    		con.setLayout(new BorderLayout());
    		con.add(panel[0], BorderLayout.NORTH);
    		con.add(panel[1], BorderLayout.SOUTH);
    		con.add(panel[2], BorderLayout.EAST);
    		con.add(panel[3], BorderLayout.WEST);
    		con.add(cb, BorderLayout.CENTER);
    		panel[0].setPreferredSize(new Dimension(50, 50));
    		panel[1].setPreferredSize(new Dimension(50, 50));
    		panel[2].setPreferredSize(new Dimension(50, 50));
    		panel[3].setPreferredSize(new Dimension(50, 50));
    		cb.addActionListener(this);
    	}
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		Object source = e.getSource();
    		if(source == cb)
    		{	
    			for(int x = 0; x < 3; ++x)
    			{
    				panel[x] = new JPanel();
    				pane.add(panel[x]);
    				for(int y = 0; y < 3; ++y)
    					if(x % 4 == 0)
    						panel[x].setBackground(colors[y]);
    			}
    		}
    	}
    	public static void main(String[] args)
       {
       	//instantiates an object      
          JColorFrame aFrame = new JColorFrame();
          //makes the GUI look like java 
          JFrame.setDefaultLookAndFeelDecorated(true);
          //sets the size of the GUI
          final int WIDTH = 300;
          final int HEIGHT = 300;
          //determines where the GUI is on the screen
          aFrame.setBounds(470, 250, WIDTH, HEIGHT);
          //it cant be resized and is visible
          aFrame.setResizable(false);
          aFrame.setVisible(true);
    	}
    }

    It compiles fine but when I try to run the program I receive this error...

    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    	at java.awt.Container.addImpl(Container.java:1041)
    	at java.awt.Container.add(Container.java:927)
    	at JColorFrame.<init>(JColorFrame.java:29)
    	at JColorFrame.main(JColorFrame.java:59)
    Can someone help me or at least steer me in the right direction?
    Last edited by Fubarable; 07-29-2010 at 11:55 PM. Reason: Moderator edit: code tags added

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

    Default

    First of all, welcome to the forum. Hope you don't mind, but I've added code tags to the code pasted in your post to help make it readable.

    Now for your problem, you'll need to tell us which line is throwing the NPE -- line 29 of your JColorFrame.java code. One problem I see though is that you're adding null objects to your contentPane since you don't initialize the JPanels that are held in the JPanel array before adding them to the contentPane.

    So I recommend that you initialize these JPanels and that in your actionPerformed method, you don't create new JPanels and don't add any JPanels into your contentPane, but rather simply change the background color of the existing JPanels held in the array.

  3. #3
    Chanel is offline Member
    Join Date
    Jul 2010
    Posts
    5
    Rep Power
    0

    Question

    Well what I was thinking of doing first is initializing the JPanels separately (I commented them out for now), but by doing that I couldnt figure out how to use one button to do mulitple different things. This is why I created the array of panels. Now with you saying that they are all set to null, Im not completely understanding that part. Would I do something like this...

    Java Code:
    private JPanel[] panel = new JPanel[nb, sb, eb, wb];
    line 29 of your JColorFrame.java code...
    Java Code:
    con.add(panel[0], BorderLayout.NORTH);
    con.add(panel[1], BorderLayout.SOUTH);
    con.add(panel[2], BorderLayout.EAST);
    con.add(panel[3], BorderLayout.WEST);
    This is where the error is at. When I set the individual panels to the content pane, not sure why?

    Thanks for the help!

  4. #4
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Java Code:
    private JPanel[] panel = new JPanel[3];
    you now have an array of JPanels, that are not initialised
    look at this,
    Java Code:
     private int [] myInts=new int [3];
    what are the values of the four ints i just created? think about it.

    Java Code:
    con.add(panel[0], BorderLayout.NORTH);
    		con.add(panel[1], BorderLayout.SOUTH);
    		con.add(panel[2], BorderLayout.EAST);
    		con.add(panel[3], BorderLayout.WEST);
    if myInts above were accesed what would happen e.g.int num= myInts[0]+10;
    what exactly is held by myInts[0]????

    In other words you have an array of JPanels that have been declared but not initialised.

    Java Code:
    //private JPanel nb = new JPanel();
    	//private JPanel sb = new JPanel();
    	//private JPanel eb = new JPanel();
    	//private JPanel wb = new JPanel();
    you know how to initialise a JPanel. You have done it above.

    Btw, JFrame defaults to borderlayout.

  5. #5
    Chanel is offline Member
    Join Date
    Jul 2010
    Posts
    5
    Rep Power
    0

    Default

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class JColorFrame extends JFrame implements ActionListener
    {
    	private JPanel pane = new JPanel(new BorderLayout());
    	private Color[] colors = new Color[]{Color.PINK, Color.GREEN, Color.BLACK, Color.RED};
    	private JPanel nb = new JPanel();
    	private JPanel sb = new JPanel();
    	private JPanel eb = new JPanel();
    	private JPanel wb = new JPanel();
    	private JPanel[] panel = new JPanel[]{nb, sb, eb, wb};
    
    	private JButton cb = new JButton("Change Color");
    	private Container con = getContentPane();
    	
    	public JColorFrame()
    	{
    		super("Color Swtich");
    		//sets close button and sets layout
    		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		//contains the visible contents, sets and adds them to components
    		add(pane);
    		con.setLayout(new BorderLayout());
    		con.add(panel[0], BorderLayout.NORTH);
    		con.add(panel[1], BorderLayout.SOUTH);
    		con.add(panel[2], BorderLayout.EAST);
    		con.add(panel[3], BorderLayout.WEST);
    		con.add(cb, BorderLayout.CENTER);
    		panel[0].setPreferredSize(new Dimension(50, 50));
    		panel[1].setPreferredSize(new Dimension(50, 50));
    		panel[2].setPreferredSize(new Dimension(50, 50));
    		panel[3].setPreferredSize(new Dimension(50, 50));
    		cb.addActionListener(this);
    	}
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		Object source = e.getSource();
    		if(source == cb)
    		{	
    			for(int x = 0; x < 3; ++x)
    			{
    				for(int y = 0; y < 3; ++y)
    					if(x % 4 == 0)
    						panel[x].setBackground(colors[y]);
    			}
    		}
    	}
    	public static void main(String[] args)
       {
       	//instantiates an object      
          JColorFrame aFrame = new JColorFrame();
          //makes the GUI look like java 
          JFrame.setDefaultLookAndFeelDecorated(true);
          //sets the size of the GUI
          final int WIDTH = 300;
          final int HEIGHT = 300;
          //determines where the GUI is on the screen
          aFrame.setBounds(470, 250, WIDTH, HEIGHT);
          //it cant be resized and is visible
          aFrame.setResizable(false);
          aFrame.setVisible(true);
    	}
    }
    Ok I fixed the null JPanel objects but Im still confused on how to get one button to do multiple actions within my algorithm.
    Can anyone help me with that?

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

    Default

    Myself, I'd use an int counter field, say called count and increment it in the actionPerformed method, but if it got to 4 set it back to 0 (the mod operator would work well for this), and then use this field to help rotate the colors around the array. Perhaps you could use count to decide which color to put in the 0th JPanel in the array.

  7. #7
    Chanel is offline Member
    Join Date
    Jul 2010
    Posts
    5
    Rep Power
    0

    Default

    Why is this not working then, if I am using the modulus operator and I am rotating through the colors and panels...
    Java Code:
    public void actionPerformed(ActionEvent e)
    	{
    		Object source = e.getSource();
    		if(source == cb)
    		{	
    			for(int x = 0; x < panel.length; ++x)
    				for(int y = 0; y < colors.length; ++y)
    					if(x % 4 == 0)
    						panel[x].setBackground(colors[y]);
    		}
    	}

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

    Default

    There is no way that this code will change the color placement with each new button press but rather places the same colors in the same JPanels, and if you walk through the logic (step through it as if you were the computer), you'll see why. You still haven't created and used a class-scope counter field.

  9. #9
    Chanel is offline Member
    Join Date
    Jul 2010
    Posts
    5
    Rep Power
    0

    Default

    Java Code:
    public void actionPerformed(ActionEvent e)
    	{
    		Object source = e.getSource();
    
    		if(source == cb)
    		{	
    			panel[counter].setBackground(colors[counter]);
    			counter++;
    		}
    	}
    This is what I got. Now what I need to do is reset the background back to white after all four panels change. So the fifth click of the button would change it to white again.

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,582
    Rep Power
    25

    Default

    would change it to white again
    The colors array doesn't have a Color.WHITE?

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

    Default

    What I was recommending was that you give your class an int counter variable and increment it in the actionPerformed method, like so:

    Java Code:
       public void actionPerformed(ActionEvent e) {
          counter++;
    
          //.... more code goes here
    
       }

    and then loop through your JPanel array, assigning colors from a COLORS array but using the counter variable to shift the colors each time the button is pressed:

    Java Code:
       public void actionPerformed(ActionEvent e) {
          counter++;
          for (int i = 0; i < panels.length; i++) {
             int index = (counter + i);  // shift the COLORS array index counter amount
    
             index = index % COLORS.length; // mod index so it loops back go 0 when it's as big as the COLORS array
    
             panels[i].setBackground(COLORS[index]); // use index to set color
          }
       }

Similar Threads

  1. Replies: 2
    Last Post: 07-24-2010, 10:07 AM
  2. background color with jpanel
    By hannerz06 in forum New To Java
    Replies: 6
    Last Post: 03-31-2010, 03:25 AM
  3. Need help with array list jpanel question!!! Plz help!!!
    By helpmeplease in forum New To Java
    Replies: 17
    Last Post: 12-11-2009, 12:37 PM
  4. How to display image from byte array in JPANEL
    By waqasdaar in forum AWT / Swing
    Replies: 0
    Last Post: 03-22-2009, 12:11 AM
  5. [SOLVED] 2 D Array and JComboBox on a JPanel
    By crazydeo in forum New To Java
    Replies: 7
    Last Post: 05-23-2008, 09:17 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
  •