简体   繁体   English

JPanel更改颜色以使用鼠标绘制

[英]JPanel changing colors to draw with mouse

I am trying to use JPanel to paint on the canvas using the mouse. 我正在尝试使用JPanel使用鼠标在画布上绘画。 So far everything works fine. 到目前为止,一切正常。 I can draw. 我能画。 and I can set the color to be whatever I choose. 然后我可以将颜色设置为我选择的颜色 However I am trying to make it so that when I click a button, it changes the color to whatever the button is attached to. 但是,我试图做到这一点,以便当我单击按钮时,它将颜色更改为按钮所附加的颜色。

Like if I draw with black, then hit the "Blue" button, it changes to blue instead of black...I'm not sure on where I'm going wrong though. 就像我用黑色绘制,然后单击“蓝色”按钮一样,它变为蓝色而不是黑色...虽然我不确定我要去哪里。 Heres my paintComponent part. 这是我的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);
}

No, no, no. 不不不。 Why are you adding a ActionListener to a button inside a paint method? 为什么要在paint方法内的按钮上添加ActionListener The paint method could be called a dozen times in quick succession by the repaint manager, now you have a dozen or more ActionListener s registered to the button .. which aren't going to do anything. 重新绘制管理器可以快速连续地调用一次paint方法,现在您已经在按钮上注册了十几个或更多的ActionListener ,这将无济于事。

Start by creating a field which can store the desired paint color. 首先创建一个可以存储所需油漆颜色的字段。 Register a ActionListener to your buttons, probably via the classes constructor, which change the "paint color" and trigger a new paint cycle. 可能通过类构造函数将ActionListener注册到您的按钮,这将更改“绘制颜色”并触发新的绘制周期。 When paintComponent called, apply the desired paint color 调用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);


}

Now, go and read Performing Custom Painting and Painting in AWT and Swing to gain a better understand into how painting actually works in Swing 现在,去阅读《 在AWT和Swing中 执行自定义绘画绘画》以更好地了解绘画在Swing中的实际工作方式

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

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