繁体   English   中英

单击时在JButton上绘制一个椭圆

[英]Drawing an oval on JButton when clicked

我已经开始为我的Java类开发一个项目 - LAN gomoku /连续五个。 游戏板由填充有按钮(JButton)的二维阵列表示。 使用事件处理程序(类clickHandler)我想在我单击的按钮上绘制一个椭圆(clickHandler对象的参数)。 我的下面的代码没有工作(我不知道如何摆脱变量g的空值)...我很感激任何建议。 非常感谢。

    class clickHandler implements ActionListener {

        JButton button;
        Dimension size;
        Graphics g;

        public clickHandler(JButton button) {
            this.button = button;
            this.size = this.button.getPreferredSize();
        }

        @Override
        public void actionPerformed(ActionEvent ae) {
                this.g.setColor(Color.BLUE);
                this.g.fillOval(this.button.getHorizontalAlignment(), this.button.getVerticalAlignment(), this.size.width, this.size.height);

                this.button.paint(this.g);
                this.button.setEnabled(false);
        }
    }

(在创建GUI的类中 - 游戏板上装满了按钮 -​​ 我通过这种方式为每个按钮分配一个新的Action Listener - clickHandler实例):

    gButton.addActionListener(new clickHandler(gButton));

你必须:

  • 扩展JButton类,并覆盖paintComponent(Graphics g)方法。
  • 重写getPreferredSize()方法,它将返回Dimension对象,并通过提供一个合适的大小,帮助Layout ManagerJButton放置在Container/Component

  • 在那里制作圈子代码。

  • 添加一个onClickListener,并在单击的按钮上设置一个标志,并调用它进行重绘。


关于Graphics对象:最好将它保存在paintComponent方法中,并且只在那里使用它。 它将永远传递给重画,如果你把它保存在其他时刻,可能会发生奇怪的事情(快乐的实验:))。

一个小例子:

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

public class ButtonExample
{
    private MyButton customButton;

    private void displayGUI()
    {
        JFrame frame = new JFrame("Custom Button Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        customButton = new MyButton();
        customButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                MyButton.isClicked = true;
                customButton.repaint();
            }
        });

        frame.getContentPane().add(customButton, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new ButtonExample().displayGUI();
            }
        });
    }
}

class MyButton extends JButton
{
    public static boolean isClicked = false;

    public Dimension getPreferredSize()
    {
        return (new Dimension(100, 40));
    }

    public void paintComponent(Graphics g)
    {
        if (!isClicked)
            super.paintComponent(g);
        else
        {
             g.setColor(Color.BLUE);
             g.fillOval(getHorizontalAlignment(), getVerticalAlignment(), getWidth(), getHeight());
        }       
    }
}

暂无
暂无

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

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