【问题标题】:JPanel changing colors to draw with mouseJPanel 更改颜色以使用鼠标绘制
【发布时间】:2018-04-07 08:52:55
【问题描述】:

我正在尝试使用JPanel 使用鼠标在画布上绘画。到目前为止一切正常。我能画。我可以将颜色设置为我选择的任何颜色。但是我正在尝试这样做,以便当我单击一个按钮时,它会将颜色更改为按钮所附加的任何颜色。

就像我用黑色画画,然后点击“蓝色”按钮,它会变成蓝色而不是黑色......不过我不确定我哪里出错了。这是我的paintComponent 部分。

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    button1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == button1)
                g.setColor(Color.BLUE);
        }
    });

    for (Point point : points)
        g.fillOval(point.x, point.y, 4 , 4);
}

【问题讨论】:

  • 源代码中的一个空白行是永远需要的。 { 之后或} 之前的空行通常也是多余的。

标签: java swing jpanel awt java-2d


【解决方案1】:

不,不,不。为什么要在paint 方法中的按钮上添加ActionListener?重绘管理器可以快速连续调用paint 方法十几次,现在您有十几个或更多ActionListeners 注册到按钮.. 它们不会做任何事情。

首先创建一个可以存储所需油漆颜色的字段。将ActionListener 注册到您的按钮,可能是通过类构造函数来更改“绘制颜色”并触发新的绘制周期。当paintComponent 调用时,应用所需的油漆颜色

private Color paintColor = Color.BLACK;

protected void setupActionListener() {
    button1.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == button1) {
                paintColor = Color.BLUE;
                repaint();
            }
        }
    });    
}

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.setColor(paintColor);
    for (Point point : points)
        g.fillOval(point.x, point.y, 4 , 4);


}

现在,去阅读 Performing Custom PaintingPainting in AWT and Swing 以更好地了解绘画在 Swing 中的实际工作原理

【讨论】:

  • 谢谢!这帮助了很多!我确定我明显的菜鸟 java 技能显示...大声笑
  • 我可以再问一个问题吗?您提供的这种方法效果很好,但是我将如何做到这一点,以便在更改新颜色时不会更改已经绘制的任何内容?就像我用蓝色画,然后换成红色画,我希望蓝色画还在那儿。但相反,它全部变为红色。
  • 这是一个更大的问题 - 您有两个基本选项。要么记录捕获点时使用的颜色,将它们包装在自定义对象中,要么绘制到后备缓冲区,例如 BufferedImage,然后使用 paintComponent 方法绘制它
  • 好的,谢谢!我会调查这些。再次感谢您的帮助!
猜你喜欢
  • 2011-08-31
  • 2016-02-05
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多