Results 1 to 6 of 6
  1. #1
    sky
    sky is offline Member
    Join Date
    Nov 2009
    Posts
    96
    Rep Power
    0

    Default Change color of a region

    I have this program, that draws a JPanel with 25*15 red rectangles. Now, when I click in one rectangle, I want to change the color of the rectangle to green (if it was red) and then to red again (if the user clicks again). So far I already calculate the coordinates of the clicked rectangle but I don't know how to get the color of the rectangle and how to change it.

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    
    public class PaintSquares
    {   
        public static void main(String[] args) {
    
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI(); 
                }
            });
        }
    
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("Paint Demo");
            
            JPanel contentPane = (JPanel) frame.getContentPane();
            contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));
            
            JPanel mainPanel = new CustomPanel();
            mainPanel.setOpaque(true);
            mainPanel.setBackground(new Color(255,255,255));
            mainPanel.setPreferredSize(new Dimension(240, 390));
            mainPanel.setBorder(new EtchedBorder());
            contentPane.add(mainPanel, BorderLayout.CENTER);
            
            frame.pack();
            frame.setVisible(true);
        } 
    
    }
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    
    public class CustomPanel extends JPanel
    {
        private int squareX = 10;
        private int squareY = 10;
        private int squareW = 10;
        private int squareH = 10;
    
        public CustomPanel() {
            
            addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    changeColor(e.getX(),e.getY());
                }
            });
            
        }
        
        private void changeColor(int x, int y) {
            
            int squarePosX = (Integer)((x-10)/15);
            int squarePosY = (Integer)((y-10)/15);
            
            squareX = squarePosX*15 + 10;
            squareY = squarePosY*15 + 10;
            
            // Get the color of that rectangle
            // If it is green, change it to red
            // If it is red, change it to green
            
        }
        
    
        public Dimension getPreferredSize() {
            return new Dimension(240,390);
        }
        
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);       
            
            for (int i=0 ; i<25 ; i++) {
                for (int j=0 ; j<15 ;j++) {
                    g.setColor(Color.RED);
                    g.fillRect(squareX,squareY,squareW,squareH);
                    g.setColor(Color.BLACK);
                    g.drawRect(squareX,squareY,squareW,squareH);
                    squareX += 15;
                }
                
                squareX = 10;
                squareY += 15;
            }
        }  
    }
    I also have another problem: when the frame is resized all the rectangles disappear, but I guess that it has something to do with repaint method.

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

    Default

    Possibly the easiest way to solve this is to have your CustomPanel utilize the GridLayout and hold 15 by 25 small JPanels. And then add a mouselistener to each panel that swaps colors on mouse press. For e.g.,
    Java Code:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.*;
    
    public class PaintSquares2 {
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("PaintSquares2 Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new CustomPanel2().getMainPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
    
      }
    }
    
    class CustomPanel2 {
      public static final int MAX_X = 15;
      public static final int MAX_Y = 25;
      private static final int SQR_WIDTH = 11;
      private static final int SQR_HEIGHT = SQR_WIDTH;
      private static final Dimension SQUARE_DIMENSION =  new Dimension(SQR_WIDTH, SQR_HEIGHT);
      private static final int H_GAP = 4;
      private static final int V_GAP = H_GAP;
      private static final Color[] FILL_COLOR = {Color.red, Color.green};
      private static final Color BORDER_COLOR = Color.black;
      private JPanel mainPanel = new JPanel();
      
      public CustomPanel2() {
        int ebGap = 2*H_GAP;
        mainPanel.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
        mainPanel.setBackground(Color.white);
        mainPanel.setLayout(new GridLayout(MAX_Y, MAX_X, H_GAP, V_GAP));
        MyMouseListener mListener = new MyMouseListener();
        for (int row = 0; row < MAX_Y; row++) {
          for (int col = 0; col < MAX_X; col++) {
            JPanel square = new JPanel();
            square.setBackground(FILL_COLOR[0]);
            square.setPreferredSize(SQUARE_DIMENSION);
            square.setBorder(BorderFactory.createLineBorder(BORDER_COLOR));
            square.addMouseListener(mListener);
            mainPanel.add(square);
          }
        }
      }
      
      public JPanel getMainPanel() {
        return mainPanel;
      }
      
      private class MyMouseListener extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent me) {
          JComponent comp = (JComponent) me.getSource();
          Color bkgColor = comp.getBackground();
          Color newColor = (bkgColor == FILL_COLOR[0]) ? FILL_COLOR[1] : FILL_COLOR[0];
          comp.setBackground(newColor);
        }
      }
      
    }

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

    Default

    I also have another problem: when the frame is resized all the rectangles disappear, but I guess that it has something to do with repaint method.
    Indeed it does:

    Java Code:
      protected void paintComponent(Graphics g) {
        super.paintComponent(g);
    
        for (int i = 0; i < 25; i++) {
          for (int j = 0; j < 15; j++) {
            g.setColor(Color.RED);
            g.fillRect(squareX, squareY, squareW, squareH);
            g.setColor(Color.BLACK);
            g.drawRect(squareX, squareY, squareW, squareH);
            squareX += 15;
          }
    
          squareX = 10;
          squareY += 15;
        }
      }
    what's going to happen to squareY each time this panel gets repainted? Your squares are going to march right off the bottom of your screen is what! You could solve this by initializing squareY to 10 at the start of this method.
    Last edited by Fubarable; 11-24-2009 at 01:59 AM.

  4. #4
    sky
    sky is offline Member
    Join Date
    Nov 2009
    Posts
    96
    Rep Power
    0

    Default

    That's exaclty what i wanted. Thank you very much. Now I'm trying to go one step further. When I resize de frame, because it is a GridLayer, the squares get also resized. I want to keep them the same size, so I tried the method setMaximunSize() with the same size as the square size but it doesn't work. So right now I'm going to try creating a new panel with FlowLayout that contains the panel with GridLayout and I let you know how it goes.

  5. #5
    sky
    sky is offline Member
    Join Date
    Nov 2009
    Posts
    96
    Rep Power
    0

    Default

    Adding a panel with flowLayout solved the problem. Now, the code looks like this:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    
    public class PaintSquares
    {   
    
      private static void createAndShowGUI() {
            
        JFrame frame = new JFrame("Paint Demo 3");
            
        JPanel contentPane = (JPanel) frame.getContentPane();
        contentPane.setBorder(new EmptyBorder(6, 6, 6, 6));
        
        contentPane.setLayout(new BorderLayout(6, 6));
        
        JPanel flowPanel = new JPanel();
        flowPanel.setBackground(new Color(255,255,255));
        flowPanel.setPreferredSize(new Dimension(240, 385));
        flowPanel.setBorder(new EtchedBorder());
        contentPane.add(flowPanel, BorderLayout.CENTER);
        
        JPanel mainPanel = new CustomPanel().getMainPanel();
        flowPanel.add(mainPanel);
      
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
    
      }
    }
    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    
    public class CustomPanel{
        
      public static final int MAX_X = 10;
      public static final int MAX_Y = 20;
      private static final int SQR_WIDTH = 11;
      private static final int SQR_HEIGHT = SQR_WIDTH;
      private static final Dimension SQUARE_DIMENSION =  new Dimension(SQR_WIDTH, SQR_HEIGHT);
      private static final int H_GAP = 4;
      private static final int V_GAP = H_GAP;
      private static final Color[] FILL_COLOR = {Color.red, Color.green};
      private static final Color BORDER_COLOR = Color.black;
      private JPanel mainPanel = new JPanel();
      
      public CustomPanel() {
        int ebGap = 2*H_GAP;
        //mainPanel.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
        mainPanel.setBackground(Color.white);
        mainPanel.setLayout(new GridLayout(MAX_Y, MAX_X, H_GAP, V_GAP));
        
        MyMouseListener mListener = new MyMouseListener();
        for (int row = 0; row < MAX_Y; row++) {
          for (int col = 0; col < MAX_X; col++) {
            JPanel square = new JPanel();
            square.setBackground(FILL_COLOR[0]);
            square.setPreferredSize(SQUARE_DIMENSION);
            square.setMaximumSize(SQUARE_DIMENSION);
            square.setBorder(BorderFactory.createLineBorder(BORDER_COLOR));
            square.addMouseListener(mListener);
            mainPanel.add(square);
          }
        }
      }
      
      public JPanel getMainPanel() {
        return mainPanel;
      }
      
      private class MyMouseListener extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent me) {
          JComponent comp = (JComponent) me.getSource();
          Color bkgColor = comp.getBackground();
          Color newColor = (bkgColor == FILL_COLOR[0]) ? FILL_COLOR[1] : FILL_COLOR[0];
          comp.setBackground(newColor);
        }
      }
      
    }
    In that code, I changed the number of rectangles that are created. I'd like to keep the panel with GridLayout containing the squares always in the center of the other panel with FlowLayout, but I cannot use the method setLocationRelativeTo() because is not a frame or dialog. Any idea?

  6. #6
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    6

    Default

    When FlowLayout fails, try Box and BoxLayout. Inserting empty boxes with flexible sizes can take up all the slack outside your desired rectangle.

Similar Threads

  1. Replies: 6
    Last Post: 05-14-2011, 07:48 AM
  2. change Panel Color
    By aadi_j in forum AWT / Swing
    Replies: 2
    Last Post: 11-16-2009, 11:12 AM
  3. Color Change of data
    By Java.child in forum AWT / Swing
    Replies: 20
    Last Post: 02-12-2009, 07:51 AM
  4. How to change string Color
    By Java.child in forum AWT / Swing
    Replies: 3
    Last Post: 01-06-2009, 05:27 AM
  5. How to change TXT color Onclick
    By dave700800 in forum New To Java
    Replies: 1
    Last Post: 12-08-2007, 02:39 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
  •