2016-05-24 66 views
0

我刚做了这个程序,我在面板上添加了一个按钮,但我无法继续使用actionListener来使按钮正常工作。他们应该是面板上出现的图片,当点击该按钮时,图片应该变成另一张图片。请帮助我,谢谢!这是我的代码。简单的GUI程序

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

public class DrawPanelThree extends JPanel 
{ 
    private JButton button; 

    public DrawPanelThree() 
    { 
     button = new JButton(); 
     setLayout(new BorderLayout()); 
     add(button, BorderLayout.SOUTH); 
     button.setText("Start"); 
    } 

    protected void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     g.drawRect(90, 40, 100, 50); 
     g.setColor(Color.RED); 
     g.fillRect(10, 10, 10, 10); 
     g.fillRect(260, 10, 10, 10); 
     g.fillRect(10, 120, 10, 10); 
     g.fillRect(260, 120, 10, 10); 
     g.setColor(new Color(255, 215, 0)); 
     g.fillOval(120, 45, 40, 40); 
    } 

    public static void main(String[] args) 
    { 
     JFrame frame = new JFrame(); 
     frame.setTitle("Rectangle"); 
     frame.setSize(new Dimension(300, 200)); 
     frame.setLocationRelativeTo(null); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     DrawPanelThree panel = new DrawPanelThree(); 
     frame.add(panel); 
     panel.setBackground(Color.CYAN); 

     frame.setVisible(true); 
    } 

    private class ButtonListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent event) 
     { 

     } 
    } 
} 

回答

2

你必须给的ActionListener添加到按钮,像这样:

button.addActionListener(new MyCoolActionListener()); 

您也可以在声明它定义的ActionListener,但这是一般的想法。你想在你的构造函数中声明JButton后立即添加ActionListener。

希望这会有所帮助!