Results 1 to 11 of 11
  1. #1
    gopher is offline Member
    Join Date
    Feb 2009
    Posts
    4
    Rep Power
    0

    Default Modifying and reloading JPanel component

    I am relatively new to Java, been taking a class for a year now, and I'm currently working on a Mastermind game. I've made it quite fancy and way too complex for my skills, so I've run into a snag.

    I have created JLabels setting a specific icon image for each of the bullets telling users if their selection was right color in right spot or right color. These are all given a specific grid name. When the user presses the "Guess" button, I dynamically create this specific grid value and then try to replace the existing one. I've tried a number of methods including just resetting the icon using the generated name or by cycling through the panel's components. Neither is successful.

    Can anyone offer some suggestions on how to fix this problem? I have both of my solutions here, so it's a little mucked up.

    private void displayGridAnswers(int numBlackDots, int numRedDots)
    {
    for (int i=1; i<=numBlackDots; i++)
    {
    String label = "grid_" + selectedRow + "_answer_" + i;
    JLabel gridAnswer = new JLabel(label);
    gridAnswer.setIcon(tinyRingBullet);

    Component[] components = gamePanel.getComponents();
    Component component = null;
    for (int j = 0; j < components.length; j++)
    {
    component = components[j];
    if (component instanceof JLabel)
    {
    String string = component.toString();
    if (string.indexOf(label) != -1)
    {
    String newString = string.replace("grey", "ring");
    components[j] = new JLabel(newString);
    // components[j] = gridAnswer;
    }
    } // end if
    } // end for

    // Repaint the game panel
    gamePanel.repaint();
    } // end method

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

    Default

    I'm not sure what your code does, but I would take advantage of the fact that JLabels can swap ImageIcons easily. So rather than swapping JPanels (for which I'd use a CardLayout if this were necessary), I'd have each 4 color guess and each 4 peg feedback be demonstrated by swapping ImageIcons in JLabels that are fixed to JPanels.

  3. #3
    gopher is offline Member
    Join Date
    Feb 2009
    Posts
    4
    Rep Power
    0

    Default

    Thank you so much for your help.
    If i simply execute this:

    String label = "grid_" + selectedRow + "_answer_" + i;
    JLabel gridAnswer = new JLabel(label);

    System.out.println("Setting ring bullet for " + label);
    gridAnswer.setIcon(tinyRingBullet);

    I don't see an update either. Or am I misunderstanding what you're saying?

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

    Default

    It's hard to say if you are understanding me or not. Could you possibly post a small example program that demonstrates what you are trying to do, again is very small, but also is compilable and runnable? This way we can see, run, and play with your code. This small program shouldn't have any of the logic of your big program. It should just demonstrate your attempt to change a JLabel's or JPanel's display. If you use images, perhaps you can post them as well.

    Also, if you do post your code, please use code tags so that your code will be well-formatted and readable. To do this, either highlight your code block and press the "code" button at the top above the message block or place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:

    Java Code:
    [cod&#101;]
       // your code block goes here
       // notice that the top and bottom tags are different here
    [/cod&#101;]

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

    Default

    For instance with this code here:
    Java Code:
        		String label = "grid_" + selectedRow + "_answer_" + i;
        		JLabel gridAnswer = new JLabel(label);
        		
        		System.out.println("Setting ring bullet for " + label);
        		gridAnswer.setIcon(tinyRingBullet);
    I'm talking about changing the icon in an existing JLabel object, not creating a new JLabel object.

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

    Default

    I think I'm barking up the wrong tree here. You're not showing white/black pegs to show the player how many colors are correct and how many are correct and in the right place? You're using text instead? If so, then just set the text of your JLabels, not the imageicons. Again, I'll know if I'm right or wrong depending on the code you post.

    Good luck.

  7. #7
    gopher is offline Member
    Join Date
    Feb 2009
    Posts
    4
    Rep Power
    0

    Default

    I think I'm making this as small as possible. I hope:

    Java Code:
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    
    public class ImageSwapperGUI extends javax.swing.JFrame {
    
        // Variables declaration - do not modify
        private javax.swing.JPanel gamePanel;
        private javax.swing.JLabel grid_1_answer_1;
        private javax.swing.JLabel grid_1_answer_2;
        private javax.swing.JLabel grid_1_answer_3;
        private javax.swing.JLabel grid_1_answer_4;
        private javax.swing.JButton guessButton;
        
        protected ImageIcon tinyGreyBullet = new ImageIcon("./images/tiny_grey_bullet.gif");
        protected ImageIcon tinyRedBullet = new ImageIcon("./images/tiny_red_bullet.gif");
        protected ImageIcon tinyRingBullet = new ImageIcon("./images/tiny_ring_bullet.gif");
        
        public ImageSwapperGUI() {
            
            initComponents();
        }
    
        private void initComponents() {
            gamePanel = new javax.swing.JPanel();
            grid_1_answer_1 = new javax.swing.JLabel();
            grid_1_answer_2 = new javax.swing.JLabel();
            grid_1_answer_3 = new javax.swing.JLabel();
            grid_1_answer_4 = new javax.swing.JLabel();
            guessButton = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            gamePanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    
        	grid_1_answer_1.setIcon(tinyGreyBullet);
            grid_1_answer_2.setIcon(tinyGreyBullet);
            grid_1_answer_3.setIcon(tinyGreyBullet);
            grid_1_answer_4.setIcon(tinyGreyBullet);
    
            guessButton.setText("Guess");
            guessButton.setActionCommand("jButton1");
            guessButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    guessButtonActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(grid_1_answer_1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(grid_1_answer_2))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(grid_1_answer_3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(grid_1_answer_4)))
                    .addGap(35, 35, 35)
                    .addComponent(guessButton)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(guessButton)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(grid_1_answer_2)
                                .addComponent(grid_1_answer_1))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(grid_1_answer_3)
                                .addComponent(grid_1_answer_4))))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>
    
        private void guessButtonActionPerformed(java.awt.event.ActionEvent evt) {
        	int selectedRow = 1;
        	
        	for (int i=1; i<=2; i++)
        	{
        		String label = "grid_" + selectedRow + "_answer_" + i;
        		JLabel gridAnswer = new JLabel(label);
        		gridAnswer.setIcon(tinyRingBullet);
        	} // end for
        }
    
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ImageSwapperGUI().setVisible(true);
                }
            });
        }
    }

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

    Default

    You create a new gridAnswer JLabel, but I don't see you placing it in your app anywhere. I think that the solution is to have a gridAnswer already made and placed in your app, and then in your guessButtonActionPerformed method, don't create a new JLabel, but instead set the text in the already existing and laid-out JLabel. HTH.

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

    Default

    An example of using a CardLayout to swap components. Here I'm swapping a JButton for a JPanel.
    Java Code:
    import java.awt.CardLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridLayout;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class SwapComponents
    {
      private static final int GUESS_WIDTH = 40;
      private static final int GUESS_HEIGHT = GUESS_WIDTH;
      private static final Dimension GC_SIZE = new Dimension(GUESS_WIDTH, GUESS_HEIGHT);
      private static final int KEY_WIDTH = 15;
      private static final int KEY_HEIGHT = KEY_WIDTH;
      private static final Dimension KEY_SIZE = new Dimension(KEY_WIDTH, KEY_HEIGHT);
      
      private static final String GUESS_BUTTON = "Guess Button";
      private static final String KEY_PEGS = "Key Pegs";
      private JPanel mainPanel = new JPanel();
      private CardLayout cardLayout = new CardLayout();
      private JPanel swapPanel = new JPanel(cardLayout);
      private JButton guessButton = new JButton("Guess");
      private JPanel keyPegPanel = new JPanel(new GridLayout(2, 2));
    
      public SwapComponents()
      {
        Color[] colors =
        {
          Color.red, Color.blue, Color.orange, Color.green
        };
        JPanel guessPanel = new JPanel(new GridLayout(1, 0));
        guessPanel.setOpaque(false);
        for (int i = 0; i < colors.length; i++)
        {
          GuessCircle guessCirc = new GuessCircle(colors[i], GC_SIZE);
          guessPanel.add(guessCirc.getComponent());
        }
        
        keyPegPanel.add(new GuessCircle(Color.white, KEY_SIZE).getComponent());
        keyPegPanel.add(new GuessCircle(Color.black, KEY_SIZE).getComponent());
        keyPegPanel.add(new JLabel());
        keyPegPanel.add(new JLabel());
        keyPegPanel.setOpaque(false);
        JPanel keyHolder = new JPanel();
        keyHolder.add(keyPegPanel);
        keyHolder.setOpaque(false);
        
        guessButton.addActionListener(new ActionListener()
        {
          public void actionPerformed(ActionEvent e)
          {
            cardLayout.show(swapPanel, KEY_PEGS);
          }
        });
        
        swapPanel.add(guessButton, GUESS_BUTTON);
        swapPanel.add(keyHolder, KEY_PEGS);
        swapPanel.setOpaque(false);
        
        mainPanel.add(guessPanel);
        mainPanel.add(swapPanel);
        mainPanel.setBackground(Color.darkGray);
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }
    
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("MenuInPanel");
        frame.getContentPane().add(new SwapComponents().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }
    
    class GuessCircle
    {
      private JPanel mainPanel = new JPanel()
      {
        @Override
        protected void paintComponent(Graphics g)
        {
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D) g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
          if (color != null)
          {
            Dimension d = getSize();
            g.setColor(color);
            g.fillOval(2, 2, d.width - 4, d.height -4);
          }
        }
      };
      private Color color;
    
      public GuessCircle(Color c, Dimension d)
      {
        this.color = c;
        mainPanel.setPreferredSize(d);
        mainPanel.setOpaque(false);
      }
    
      public JComponent getComponent()
      {
        return mainPanel;
      }  
    }

  10. #10
    gopher is offline Member
    Join Date
    Feb 2009
    Posts
    4
    Rep Power
    0

    Default

    That was an awesome example; thank you. I cut and pasted it, ran it and realized how overly complicated I was making it. I did continue with my code, but added my JLabels to an array where they were declared in initComponents().

    Thank you for all your help. Never would have figured it out without you!

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

Similar Threads

  1. Modifying JSP using IntelliJ IDEA 6.0.5
    By ddeokarb in forum IntelliJ IDEA
    Replies: 0
    Last Post: 11-28-2008, 02:26 PM
  2. how to remove all component in container(Jpanel)
    By SaYuNaRa in forum New To Java
    Replies: 3
    Last Post: 04-17-2008, 05:22 AM
  3. Replies: 1
    Last Post: 03-27-2008, 08:40 PM
  4. Replies: 0
    Last Post: 02-09-2008, 09:22 PM
  5. Same component on all JTabbedPane
    By java_novice in forum AWT / Swing
    Replies: 4
    Last Post: 08-06-2007, 10:09 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
  •