监听器的实现不起作用

时间:2015-11-18 04:11:54

标签: java actionlistener onmouseclick

public class ShapeDisplayer implements ActionListener {
    private static final int Width = 50; 
    private static final int Frame_Width = 400;
    private static final int Frame_Height = 600; 
    static JPanel DrawPanel;
    static JButton carButton;
    static JButton eclipseButton;
    static JButton compButton;

    public static void main (String args[])
    {
        // create frame
        JFrame frame = new JFrame("Drawing Applet"); 

        // create panels
        JPanel ButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        DrawPanel = new JPanel(new BorderLayout());

        // create Icons
        CarIcon Acar = new CarIcon(Width);
        EclipseIcon doubleCircle = new EclipseIcon(20);
        CompositeIcon compIcon = new CompositeIcon(50, 60);

        // create buttons
        carButton = new JButton(Acar);
        eclipseButton = new JButton(doubleCircle);
        compButton = new JButton(compIcon);

        // panel config
        ButtonPanel.setBounds(0,0,Frame_Width,100);
        DrawPanel.setBounds(0,100,Frame_Width,Frame_Height-100);

        // add panels'components
        ButtonPanel.add(eclipseButton);
        ButtonPanel.add(carButton);
        ButtonPanel.add(compButton);

        // add frames' components
        frame.add(ButtonPanel);
        frame.add(DrawPanel);

        // frame config
        frame.setSize(Frame_Width, Frame_Height);
        frame.setLayout(new BorderLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == carButton)
        {
            DrawPanel.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) { 
                  CarIcon car = new CarIcon(Width, e.getX(), e.getY());
                  JLabel lable = new JLabel (car);
                  DrawPanel.add(lable);
              } 
            });     
        }

    }
}

我试图在鼠标点击上实现此程序以在面板上绘图,例如,如果按钮是carButton,那么每当我点击面板时,将绘制一个汽车图标。我实现了监听器,但是当我点击面板时,面板上没有任何内容。我在Jframe上添加了监听器,是否需要在Jpanel上添加监听器以使程序正常工作?有人可以帮忙修复这个程序,谢谢你提前。

enter image description here

1 个答案:

答案 0 :(得分:2)

单击按钮时不会调用actionPerformed方法。因为它没有绑定任何按钮。

例如,carButton可以添加一个动作监听器,如下所示。

carButton = new JButton(Acar);
carButton.addActionListener(new ShapeDisplayer());

请注意,由于此代码位于main方法中,因此“this”不能用于添加动作侦听器。需要实例化ShapeDisplayer类的新对象。

此外,DrawPanel可能需要重新绘制才能使更改生效。调用revalidate方法可以做到这一点。

 DrawPanel.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) { 
        CarIcon car = new CarIcon(Width, e.getX(), e.getY());
        JLabel lable = new JLabel (car);
        DrawPanel.add(lable);
        DrawPanel.revalidate();
    } 
});