[英]Making overridden paintComponent editable?
我正在建立一個程序,使用戶可以在地圖上添加“地方”。 該地圖是JPanel中的背景圖像,單擊該程序會創建我的城市類的實例,並在用戶單擊的位置繪制/繪制一個點。
繪制是通過覆蓋paintComponent的; 像這樣:
public void paintComponent(Graphics g) {
super.paintComponent(g);
setCursor(handCursor);
g.setColor(Color.RED);
g.fillOval(0, 0, 15, 15);
g.setColor(Color.GRAY);
g.fillOval(2, 2, 11, 11);
g.setColor(Color.GRAY);
g.drawString(globalString, 0, 25);
g.setColor(Color.RED);
g.drawString(globalString, 1, 26);
bild.setCursor(oldCursor);
bild.removeMouseListener(mln);
}
現在,我想以某種方式使此方法可編輯。
我的目標是讓“城市”對點擊做出反應(已經在城市級別解決),一次點擊使城市“活躍”,另一次使城市“無效”。
我現在的問題是如何在圖形本身中進行更改,即更改:
g.setColor(Color.GRAY);
g.fillOval(2, 2, 11, 11);
至:
g.setColor(Color.WHITE);
g.fillOval(2, 2, 11, 11);
是否可以再次覆蓋paintComponent,還是可以調用已創建的覆蓋版本?
我正在使用兩個boolenas來解決是否選擇了一個城市的問題,只能選擇兩個城市(然后它們可以用於進一步的操作)。
布爾值是sel1和sel2
public void paintComponent(Graphics g) {
if (sel1==false)
{
super.paintComponent(g);
setCursor(handCursor);
g.setColor(Color.RED);
g.fillOval(0, 0, 15, 15);
g.setColor(Color.GRAY);
g.fillOval(2, 2, 11, 11);
g.setColor(Color.GRAY);
g.drawString(globalString, 0, 25);
g.setColor(Color.RED);
g.drawString(globalString, 1, 26);
bild.setCursor(oldCursor);
bild.removeMouseListener(mln);
}
else if(sel1==true)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillOval(0, 0, 25, 25);
g.setColor(Color.WHITE);
g.fillOval(2, 2, 5, 5);
g.setColor(Color.WHITE);
g.drawString(globalString, 0, 25);
g.setColor(Color.BLACK);
g.drawString(globalString, 1, 26);
}
}
該代碼可以進行更改,但僅當創建一個新城市時才進行更改,然后對所有這些進行更改。
抱歉,我對這里的邏輯很新鮮。
嘗試這樣的事情:
public class City extends JComponent{
private boolean active=false;
protected int x;
private int y;
public City(int x, int y){
setBounds(x, y, 20, 20);
setPreferredSize(new Dimension(20,20));
setMaximumSize(new Dimension(20,20));
setMinimumSize(new Dimension(20,20));
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
if(active==true)
active(g);
else if(active==true)
notActive(g);
}
public void active(Graphics g){
g.setColor(Color.RED);
g.fillRect(0,0,getWidth(),getHeight());
}
public void notActive(Graphics g){
g.setColor(Color.BLUE);
g.fillRect(0, 0, getWidth(),getHeight());
}
public boolean clicked(boolean b){
active=b;
repaint(); //repaint whenever the flag active changes
}
public boolean isActive(){
return active;
}
其中x和y是坐標
在您的主類中://應該添加到每個城市對象的偵聽器
public class cityListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
City current=(City)e.getSource();
if(current.active==false)
current.clicked(true);
else if(current.active==true)
current.clicked(false);
}
}
您能否將您的城市放入“活動”或“非活動”的數據結構中,並在上面使用if語句來根據模型狀態更改顯示顏色?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.