Java 重绘方法不起作用?
按下按钮后,我在重新绘制面板中的矩形时遇到问题。我正在更改颜色并调用重新绘制方法,因此我不确定为什么在按下按钮后它不会重新绘制。画布面板是带有我试图重画的矩形的面板。整个面板是带有按钮的面板,这些按钮应该是响应的 我的代码:Java 重绘方法不起作用?,java,button,colors,actionlistener,Java,Button,Colors,Actionlistener,按下按钮后,我在重新绘制面板中的矩形时遇到问题。我正在更改颜色并调用重新绘制方法,因此我不确定为什么在按下按钮后它不会重新绘制。画布面板是带有我试图重画的矩形的面板。整个面板是带有按钮的面板,这些按钮应该是响应的 我的代码: public WholePanel() { //white is the default color currentColor = Color.WHITE; //default x-y cooridnate, width, and height of a rectan
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
我认为该漏洞存在于itemStateChanged方法中,您在该方法中写道:
if (source==red) {
currentColor=Color.white;
...
}
在红色和白色两种情况下,您都将颜色设置为白色,这就是矩形颜色不变的原因。为了更快地获得更好的帮助,您应该提供感谢!我不敢相信是什么把我搞砸了。我想我把它调到了正确的颜色。非常感谢你!很高兴这有帮助-