简体   繁体   English

简单的GUI程序

[英]simple GUI program

I just made this program that I add a button on my panel, but I am not able to move on to use actionListener to make the button work. 我刚创建了一个在面板上添加按钮的程序,但是我无法继续使用actionListener使按钮起作用。 Their should be pictures appered on the panel and when the button clicked, the picture should change to another picture. 它们应该是贴在面板上的图片,单击按钮时,该图片应更改为另一张图片。 Please help me, thanks! 请帮助我,谢谢! Here is my code. 这是我的代码。

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)
        {

        }
    }
}

You have to add the ActionListener to the button, like so: 您必须将ActionListener添加到按钮,如下所示:

button.addActionListener(new MyCoolActionListener());

You can also define the ActionListener when you declare it, but that's the general idea. 您也可以在声明ActionListener时定义它,但这是一般的想法。 You want to add the ActionListener soon after you declare the JButton , in your constructor. 您想在构造函数中声明JButton之后立即添加ActionListener。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM