【问题标题】:repaint method not working?重绘方法不起作用?
【发布时间】:2018-08-04 20:13:16
【问题描述】:

按下按钮后,我无法在面板中重绘矩形。我更改颜色并调用重绘方法,所以我不确定为什么按下按钮后它不重绘。 “画布面板”是带有我试图重绘的矩形的面板。“整个面板”是带有应该响应的按钮的面板。

我的代码:

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

【问题讨论】:

标签: java button colors actionlistener


【解决方案1】:

我认为缺陷在你写的 itemStateChanged 方法中:

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

red 收音机和white 收音机的两种情况下,您都将颜色设置为white,这就是矩形颜色没有改变的原因。

【讨论】:

  • 谢谢!我不敢相信是什么让我搞砸了。我以为我将它设置为正确的颜色。非常感谢!
  • 很高兴这有帮助 ;-)
猜你喜欢
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 2014-05-13
相关资源
最近更新 更多