在這裏,我想在按下按鈕時執行一個動作,這很容易,但主要問題是要在擴展的JPanel中執行。 可能有一個簡單的解決方案,像添加動作偵聽器到特定的按鈕,並調用actionperformed事件,但我的情況是不是這樣,我有4個按鈕(t1,t2,t3,t4)所有這些按鈕將在一個單一ActionPerfomed事件ae(查看代碼段)。後來你可以看到調用另一個JButtons tr和rf的代碼,調用actionlistener和actionperformed事件。在JPanel中執行ActionListener
清晰易懂,你可以在代碼一覽...
class Tracker extends JPanel
{
public static void main(String[] args) {
new Tracker(); }
public Tracker()
{
JButton tr=new JButton("TRACKER APPLET");
tr.setBounds(720,170,100,20);
JButton rf=new JButton("REFRESH");
rf.setBounds(200,170,100,20);
boolean tc1=false,tc2=false,tc3=false,tc4=false;
JButton t1=new JButton(" ");
t1.addActionListener(this);
JButton t2=new JButton(" ");
t2.addActionListener(this);
JButton t3=new JButton(" ");
t3.addActionListener(this);
JButton t4=new JButton(" ");
t4.addActionListener(this);
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==t1)
{
tc1=true;
}
if(ae.getSource()==t2)
{
tc2=true;
}
if(ae.getSource()==t3)
{
tc3=true;
}
if(ae.getSource()==t4)
{
tc4=true;
}
}
tr.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex){}
catch(InstantiationException ex){}
catch(IllegalAccessException ex){}
catch(UnsupportedLookAndFeelException ex) {}
//some food here....
}
});
}
});
rf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
EventQueue.invokeLater(new Runnable() {
@Override
public void run()
{
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException ex){}
catch(InstantiationException ex){}
catch(IllegalAccessException ex){}
catch(UnsupportedLookAndFeelException ex) {}
//some extra work runs here...
}
});
}
});
add(tr);
add(rf);
add(t1);
add(t2);
add(t3);
add(t4);
}
這裏我的問題是我無法實現ActionListener作爲已經擴展JPanel的主類。 我只是想與Jbuttons ::一起按照時間順序按下按鈕(t1 | t2 | t3 | t4)和JButtons(tr | rf)來執行單個動作。
在此先感謝..
參見[*如何使用操作*](HTTP: //docs.oracle.com/javase/tuto里亞爾/ uiswing /雜項/ action.html)。 – trashgod 2013-02-16 13:13:33
實際上是否需要擴展'JPanel'?即你不能簡單地使用一個實例,並添加像這樣的按鈕等 – 2013-02-16 18:57:20