单击绘图区域时,Java背景会发生变化



在此之前,我在使用颜色选择器时无法更改笔的颜色和背景颜色。。现在彩色笔可以改变,但是背景不能改变颜色。它可以改变背景颜色,但我需要点击绘图区域,然后背景就会改变。。当我们选择我们的颜色时,它应该改变背景颜色,对吗?但事实并非如此。。

按钮面板

import java.awt.event.*;
import javax.swing.*;
import javax.swing.JColorChooser;
import java.awt.Color;
public class ButtonPanel extends JPanel implements ItemListener,
    ActionListener
{
    private DrawingArea drawingArea;
        private String tools[] = {"Pencil", "Line", "Circle", "Rectangle", "Filled Circle", "Filled Rectangle", "Round Rectangle", "Filled Round Rectangle"};
        private Color color = (Color.WHITE);
        private JComboBox<String> jcbTool;
    private JButton btnClear;
        private JButton save;
        private JButton infobutton;
        private JButton colorBtn;
        private JButton colorBg;

    public void itemStateChanged(ItemEvent ie)
    {
                if (ie.getSource()==jcbTool)
            {       
                String tool = (String)jcbTool.getSelectedItem();
                drawingArea.setTool(tool);
        }
             //  else  
                //    if (ie.getSource()==eraser)
//{               String tool = (String)eraser.getSelectedItem();
 //              drawingArea.setTool(tool)
        }
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource()==btnClear)
            drawingArea.clear();     
                else if (e.getSource()==infobutton)
                {
            //default title and icon
                JOptionPane.showMessageDialog(this,"Paint java created by bla bla bla bla bla blaa");
                }
                else if  (e.getSource()==colorBtn)
                {
                    color = JColorChooser.showDialog(null,"LOL",color);
                    drawingArea.setColorBtn(color);
                }
                  else if  (e.getSource()==colorBg)
                  {
                    color = JColorChooser.showDialog(null,"LOL",color);
                   drawingArea.setColorBg(color);
                  }
        }
}

只需在DrawingArea:中调用actionPerformed()方法中的repaint()方法

if (e.getSource() == colorBg) {
    color = JColorChooser.showDialog(null, "LOL", color);
    drawingArea.setColorBg(color);
    drawingArea.repaint();
}

因为当你改变画笔颜色并点击鼠标repaint()方法时,

但是当你设置背景颜色时,你也需要强制重新绘制。

最新更新