简体   繁体   中英

repaint method not working?

Im having trouble redrawing a rectangle in a panel after a button is pushed. Im changing the color and calling the repaint method so im not sure why it isnt repainting after a button is pushed. The "Canvas Panel" is the panel with the rectangle that im trying to redraw is in. The "Whole Panel" is the panel with the buttons that should be responding.

My code:

public WholePanel()
{
//white is the default color
 currentColor = Color.WHITE;

 //default x-y cooridnate, width, and height of a rectangle
 currentWidth = currentHeight = 100;
 x1 = 100; y1 = 100;

//Creating buttons
 fillCheck = new JCheckBox("Filled");
 white=new JRadioButton("white");
 red=new JRadioButton("red");

 //Adds listeners to each button
 white.addItemListener(new ColorListener());
 red.addItemListener(new ColorListener());



 //Adding buttons to buttonGroup so only one can be pressed at a time
 group.add(white);
 group.add(red);


 menuPanel = new JPanel();
 menuPanel.add(fillCheck);
 menuPanel.add(white);
 menuPanel.add(red);



 canvas = new CanvasPanel();

 JSplitPane sPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, menuPanel, canvas);

 setLayout(new BorderLayout());
 add(sPane, BorderLayout.CENTER);

}


 //insert ColorListener and FillListener classes

public class ColorListener implements ItemListener {


        @Override

        public void itemStateChanged(ItemEvent e) {
            Object source=e.getSource();

              if(source==red) {
                currentColor=Color.white;
                repaint();
                }

            else if (source==white) {
                currentColor=Color.white;
                repaint();
                }

        }


 }

 //This method is in a seperate CanvasPanel class where pressed keys will be 
drawn

 //this method draws all characters pressed by a user so far
 public void paintComponent(Graphics page)
  {
   super.paintComponent(page);

   //set color, then draw a rectangle
   page.setColor(currentColor);

   page.drawRect(x1, y1, currentWidth, currentHeight);
  }



  } // end of Canvas Panel Class

   } // end of Whole Pane

I think the flaw is within your itemStateChanged method where you wrote:

if (source==red) { 
    currentColor=Color.white; 
    ... 
}

In both cases of red radio and white radio you are setting the color to white and that's why the color of the rectangle is not changing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM