Java Swing - Clicking on a shape to change its color

Andrei Rosu

I need to make a Java Swing application that displays a rectangle on screen and if it is being clicked, it should change its color to black if it's white or white if it's black. The problem is that it is a class that needs to extend JComponent and override paintComponent. I got everything done except the clicking part. For some reason I cannot make it so that it only changes colors when it is clicked. It also changes colors when the background apart from it is being clicked.

Here is the code:

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


public class RectangleC extends JComponent implements MouseListener{
    private int width, height;
    private Color color;

    public RectangleC(int w, int h, Color c){
        width = w;
        height = h;
        color = c;
        this.addMouseListener(this);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(color);
        g.fillRect(0, 0, width, height);
    }

    @Override
    public void mousePressed(MouseEvent e){
        if(this.contains(e.getPoint())){
            if(color == Color.WHITE) {
                color = Color.BLACK;
            }
            else {
                color = Color.WHITE;
            }
        }
        repaint();
    }

    public void mouseClicked(MouseEvent e){};
    public void mouseReleased(MouseEvent e){};
    public void mouseEntered(MouseEvent e){};
    public void mouseExited(MouseEvent e){};

    public static void main(String args[]){
        JFrame frame = new JFrame("Rectangle Component");
        RectangleC rectangle2 = new RectangleC(300, 500, Color.BLACK);
        frame.add(rectangle2);
        frame.setSize(600,600);;
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

I cannot seem to get it working using the e.getPoint() method. I also tried using coordinates and e.getX() and e.getY() and that works as long as the shape is in its default position. However, if the shape is being moved to the center, it does no longer work.

Here is the method that I tried:

    @Override
public void mousePressed(MouseEvent e)
{
    int currentX = e.getX();
    int currentY = e.getY();
    if(currentX > this.getX() && currentX < this.getX() + width && currentY > this.getY() && currentY < this.getY() + height ){        
        if(color != Color.WHITE)
            color = Color.WHITE;
        else
            color = Color.black;
    }
    repaint();
}

How can I make it so that it only changes colors when it is clicked? I am really out of ideas and I could not find any way to do this.

Aman Chhabra

Ok, so it seems the code shared above is fine with a small issue that you are taking x and y of the component instead of the Rectangle painted on Component while comparing in mousePressed. So what you can do is create two functions to return x and y of rectangle and then use those functions where ever you need to check the coordinates of rectangle.

Please find the updated code below:

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


public class RectangleC extends JComponent implements MouseListener{
    private int width, height;
    int x,y;
    private Color color;

    public RectangleC(int w, int h, Color c){
        width = w;
        height = h;

        //Given x and y some default position. This can be changed as required
        x = 20;
        y = 20;

        color = c;
        this.addMouseListener(this);
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(color);
        g.fillRect(x, y, width, height);
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
        int currentX = e.getX();
        int currentY = e.getY();
        if(currentX > this.getRectX() && currentX < this.getRectX() + width && currentY > this.getRectY() && currentY < this.getRectY() + height ){        
            if(color != Color.WHITE)
                color = Color.WHITE;
            else
                color = Color.black;
        }
        repaint();
    }

    // Function to return rectangle coordinate
    private int getRectX() {
        return this.getX()+x;
    }


    private int getRectY() {
        return this.getY()+y;
    }
public void mouseClicked(MouseEvent e){};
    public void mouseReleased(MouseEvent e){};
    public void mouseEntered(MouseEvent e){};
    public void mouseExited(MouseEvent e){};

    public static void main(String args[]){
        JFrame frame = new JFrame("Rectangle Component");
        RectangleC rectangle2 = new RectangleC(300, 500, Color.BLACK);
        frame.add(rectangle2);
        frame.setSize(600,600);;
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

change color and shape of div on click

分類Dev

change background color of view by its ID in Titanium

分類Dev

Tkinter Checkbutton wont keep its check mark post color change

分類Dev

java / swing:テキスト文字列をShapeに変換する

分類Dev

How do I change the outline color (stroke) of my shape after drawing it?

分類Dev

How could I change my canvas color wheel so that its edges are smooth like the CSS version?

分類Dev

how do I make a hexagon inherited from QraphicsPolygonItem change its color?

分類Dev

Java android change black color in picture to tracspadence and save in file

分類Dev

How to scale a shape from its center as origin?

分類Dev

Block change action on swing controls

分類Dev

Java Swing Font Chooser

分類Dev

Java SwingのIllegalComponentStateException

分類Dev

Java Swing JList

分類Dev

Java Swing:Jtable ArrayIndexOutOfBoundsException

分類Dev

Java Swing + Hibernate + Maven

分類Dev

Java - Swing - JOptionPane padding

分類Dev

Java Swing. PaintingComponent

分類Dev

Java GUI - NOT Swing

分類Dev

Java Swing、ActionListener

分類Dev

Draw node shape and node color by attribute

分類Dev

How to determine shape fill color in AS3?

分類Dev

Google Apps Script to set shape color

分類Dev

How to get a rectangle shape with no background color?

分類Dev

Bootstrap 4 change caret on clicking dropdown

分類Dev

Change css style of an element by clicking another

分類Dev

change uitextview hyperlink color

分類Dev

Change colorControlActivated color programmatically

分類Dev

Change color on click with switch

分類Dev

change header color of jqgrid

Related 関連記事

ホットタグ

アーカイブ