class ColorChooserPanel extends JPanel
{
public ColorChooserPanel()
{
JButton modalButton = new JButton("Modal");
modalButton.addActionListener(new ModalListener());//添加监听事件
add(modalButton);
}
private class ModalListener implements ActionListener//事件具体执行的操作
{
public void actionPerformed(ActionEvent event)
{
Color defaultColor = getBackground();
Color selected = JColorChooser.showDialog(
ColorChooserPanel.this,
"Set background",
defaultColor);
setBackground(selected);
}
}
{
public ColorChooserPanel()
{
JButton modalButton = new JButton("Modal");
modalButton.addActionListener(new ModalListener());//添加监听事件
add(modalButton);
}
private class ModalListener implements ActionListener//事件具体执行的操作
{
public void actionPerformed(ActionEvent event)
{
Color defaultColor = getBackground();
Color selected = JColorChooser.showDialog(
ColorChooserPanel.this,
"Set background",
defaultColor);
setBackground(selected);
}
}
当按钮事件发生和panel事件发生时都去调用这个方法。