2011-01-14 67 views
2

我想在另一个按钮上也有一个actionlistener的按钮上做一个actionListener,我只是无法弄清楚它的某种方式。我正在尝试在第二个按钮上进行操作,但我无法弄清楚。如果有人帮助我,我会很感激!这里是下面的代码:ActionListener问题

import java.awt.*; 
import java.awt.event.*; 

import javax.swing.*; 
import java.io.*; 
import java.util.*; 

public class basic implements ActionListener{ 

    public static void main(String[] args) { 
     basic process = new basic(); 
    } 

    public basic(){ 



      JFrame fan = new JFrame("Scheme"); 


      JPanel one = new JPanel(new BorderLayout()); 
      fan.add(one); 

     JPanel uno = new JPanel(); 
      uno.setLayout(new BoxLayout(uno, BoxLayout.Y_AXIS)); 
      JButton addB = new JButton("first choice"); 


     addB.setAlignmentX(Component.CENTER_ALIGNMENT); 
      uno.add(addB); 

      addDButton.setActionCommand("hehe"); 
      addDButton.addActionListener(this); 

     one.add(uno,BorderLayout.CENTER); 

      fan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
      fan.setSize(500,700); 
      fan.setLocationByPlatform(true); 
      fan.setVisible(true); 
} 

      public void actionPerformed(ActionEvent evt) { 

    JPanel markP = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,20)); 
    JDialog dialog = new JDialog((JFrame)null); 
    dialog.getContentPane().add(markP,BorderLayout.CENTER); 

    if (evt.getActionCommand().equals("hehe")) { 


    JLabel title = new JLabel("Proceed"); 
    title.setFont(new Font("Arial",Font.BOLD,15)); 
    markP.add(title,BorderLayout.NORTH); 



    JButton exit = new JButton("Exit"); 
    markP.add(exit); 


//here i want to create another actionListener on the exit button only without affecting the other content which is in the button "addB " so that when i click on the addB button the J dialog pops up, and than when i click on exit button the program will return to the menu.I couldn't figure it out. 



    dialog.toFront(); 
    dialog.setModal(true); 
    dialog.pack(); // 
    dialog.setLocationRelativeTo(null); // 
       dialog.setVisible(true); 

} 

// here the code goes on but the problem is that of the actionListener which is concerned. 

回答

0
JButton exit = new JButton("Exit"); 
exit.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent evt) { 
     // you code here 
    } 
}); 

你应该用更好的变量名。这是不容易跟随你的代码

+0

感谢您的帮助和注释动作的来源,您可以使用相同的ActionListener。有效 ! – thegamer 2011-01-14 09:31:44

0

如果你检查使用

if (evt.getSource().equals(addDButton) { original code } 
else { code for the other button } 
+0

感谢您的帮助! – thegamer 2011-01-14 09:32:02