[英]repaint method not working?
我在按下按鈕后無法在面板上重新繪制矩形。 我更改顏色並調用repaint方法,所以我不確定為什么按下按鈕后就不重繪。 “畫布面板”是帶有我要重繪的矩形的面板。“整個面板”是帶有應該響應的按鈕的面板。
我的代碼:
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;
...
}
在red
收音機和white
收音機中,您都將顏色設置為white
,這就是矩形顏色不變的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.