簡體   English   中英

如何使用jbutton和actionlistener繪制橢圓形?

[英]How can I draw an oval using jbuttons and actionlistener?

我調查了可能已經回答的其他一些問題,但沒有發現任何與我有關的問題,或者至少沒有我所了解的問題。

我正在嘗試創建一個交通信號燈,而我遇到的問題是單擊按鈕時紅色,綠色和黃色圓圈的實際繪制。 一個快速的答案將不勝感激,謝謝。

public class TrafficLight extends JApplet implements ActionListener {

   private Image Hayden;

    JButton btn1;

    JButton btn2;

    JButton btn3;

    int x;

public void init() {

    setLayout(new FlowLayout());

    btn1 = new JButton("Stop");

    btn2 = new JButton("Wait");

    btn3 = new JButton("Go");

    Boolean Answer;

    add(btn1);

    btn1.addActionListener(this);

    add(btn2);

    btn2.addActionListener(this);

    add(btn3);

    btn3.addActionListener(this);

    Hayden = getImage(getDocumentBase(), "49.jpg");
}

public void actionPerformed(ActionEvent event){

    if (event.getSource()==btn1){
        boolean one = true;
    }
    if (event.getSource()==btn2){
        boolean two = true;
    }
    if (event.getSource()==btn3){
        boolean three = true;
    }
    repaint();

}
public void paint(Graphics g) {

    super.paint(g);

    g.setColor(Color.black);

    g.drawRect(0, 400, 700, 200);//creating the rectangle
    g.fillRect(0, 400, 700, 200);

    g.setColor(Color.black);
    g.drawRect(645, 0, 55, 155);//creating the rectangle
    g.fillRect(645, 0, 55, 155);

    g.setColor(Color.white);
    g.drawOval(650, 5, 45, 45);//creating the oval
    g.fillOval(650, 5, 45, 45);

    g.setColor(Color.white);
    g.drawOval(650, 55, 45, 45);//creating the oval
    g.fillOval(650, 55, 45, 45);

    g.setColor(Color.white);
    g.drawOval(650, 105, 45, 45);//creating the oval
    g.fillOval(650, 105, 45, 45);
    if (one == true){
        g.setColor(Color.red);
        g.drawOval(650,5,45,45);
    }
    else if (two == true){
        g.setColor(Color.red);
        g.drawOval(650,55,45,45);
    }
    else if (three == true){
        g.setColor(Color.red);
        g.drawOval(650,105,45,45);
    }
    g.drawImage(Hayden, 0, 500, 150, 100, this);//create the image

}


}

isSelected()方法與切換按鈕更為相關。 在您的情況下,在actionPerformed()內部,任何條件都不會返回true。 快速而骯臟的解決方法可能是檢查事件的來源,即:

if (event.getSource() == btn1){
    x = 5;
}

清潔將是:

btn1.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e) {
        x = 5;
    }
});

另一個注意事項是,您是否在JPanel或JComponent上自定義繪畫,然后將該組件添加到JApplet的內容窗格中。 有關詳細信息,請參見課程:執行自定義繪畫

另外,建議使用布局管理器而不是絕對布局。 請查看《布局管理器視覺指南》以獲取更多信息。

確保閱讀“ 如何制作小程序”教程以獲取一般指導。

編輯:關於

減少一點,希望不會更糟}

您上一次編輯不正確,無法編譯。 您在聲明局部變量boolean one = true; 並嘗試在另一種方法中使用它。 使boolean one班級成員。 twothree變量相同。

您需要警惕的一件事是可變范圍。 布爾值1、2和3在其各自的if語句中具有范圍。 如果您使這些布爾實例變量(在類的頂部創建像int x和您的按鈕這樣的變量),則它們的作用域就是整個類,並且可以在每個方法中引用它們。

JButton btn2;
JButton btn3;
boolean one, two three;

截至目前,這些布爾值不能由任何不在其if語句中的東西(包括paint方法)訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM