2012-07-25 58 views
0

我想在JFrame中的兩個按鈕上實現動作偵聽器,但問題是兩個按鈕之一是執行這兩個功能;但我沒有配置它來這樣做。請找到示例代碼: -ActionListener問題(Java)

import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 

public class MyChangingCirlce implements ActionListener{ 
JButton colorButton, labelButton; 
JLabel myLabel; 
MyDrawPanel mdp; 
JFrame frame; 
    public static void main(String [] args) 
    { 
    MyChangingCirlce mcc = new MyChangingCirlce(); 
    mcc.createFrame(); 
    } 

    public void createFrame() 
    { 
frame = new JFrame(); 
colorButton = new JButton("Changing Colors"); 
labelButton = new JButton("Change Label"); 
myLabel = new JLabel("BA"); 
mdp = new MyDrawPanel(); 

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


frame.getContentPane().add(BorderLayout.CENTER, mdp); 
frame.getContentPane().add(BorderLayout.SOUTH,colorButton); 
frame.getContentPane().add(BorderLayout.EAST,labelButton); 
frame.getContentPane().add(BorderLayout.WEST,myLabel); 
colorButton.addActionListener(this); 
labelButton.addActionListener(this);  
frame.setSize(300,300); 
frame.setVisible(true); 

    } // end of createFrame Method 


public void actionPerformed(ActionEvent e) 
{ 
if(e.getSource()== colorButton) 
{ 
frame.repaint();   
} 
else 
{ 
myLabel.setText("AB"); 
} 

} //end of interface method... 

}

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class MyDrawPanel extends JPanel{ 

public void paintComponent(Graphics g) 
{ 
    int red = (int) (Math.random() * 255); 
    int green = (int) (Math.random() * 255); 
    int blue= (int) (Math.random() * 255); 
    Color randomColor = new Color(red,green,blue); 
    g.setColor(randomColor); 
    g.fillOval(20,70,100,100); 
} 

}

回答

2

你覺得按鈕觸發兩個ifelse聲明,但事實並非如此。如果你想通過以下方式調整你的代碼:

  • 添加setColorchangeColor或類似於您MyDrawPanel
  • 調整MyDrawPanel#paintComponent方法使用一個固定的顏色,而不是一個隨機的顏色,而只調整的東西通過在第一步驟中創建的方法的顏色
  • 您的顏色改變按鈕應該使用在第一步驟中創建的方法來調整的MyDrawPanel

的第顏色ing是paintComponent可以由Swing自己調用。當您撥打repaint(這是件好事,或者您爲Swing組件編寫的所有代碼都將充滿repaint調用)時,不僅會調用它。

附註:當覆蓋paintComponent方法時,我建議也可以撥打super.paintComponent