我做的一个代码界面上有两个按钮,分别用于向不同的jList列表框添加数据(没有用到数据库,不牵涉到数据库的绑定),我想让两个按钮点击时都是弹出一个对话框。通过在对话框的文本框内输入要添加的数据,点击对话框的确定按钮就能够添加到对应的jList列表框内。即此时能监听到对话框是由哪个添加按钮激发的?本人对什么action、Listener不是很了解,希望能够给一些解释,如果有代码示范更好。
调试欢乐多
或者为他们注册不同的监听器
import java.awt.event.*;
import javax.swing.*;/**
* @version 1.33 2007-06-12
* @author Cay Horstmann
*/
public class ButtonTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}/**
* A frame with a button panel
*/
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // create buttons
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red"); buttonPanel = new JPanel(); // add buttons to panel
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton); // add panel to frame
add(buttonPanel); // create button actions
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED); // associate actions with buttons
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
} /**
* An action listener that sets the panel's background color.
*/
private class ColorAction implements ActionListener
{
public ColorAction(Color c)
{
backgroundColor = c;
} public void actionPerformed(ActionEvent event)
{
buttonPanel.setBackground(backgroundColor);
} private Color backgroundColor;
} private JPanel buttonPanel; public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}这是《JAVA核心技术》里面对源代码,这个是一个Action的典型用法,自己运行一下看看,应该能理解不少。