To help learn more about EventListeners
in Java, I've created a simple program that consists of one JFrame
and two JPanels
and all it's supposed to do is toggle a secondary color on the Jpanel
as it is clicked on.
My code changes each JPanel to the new secondary color when it gets clicked but when it gets clicked a second time it does revert back to the original color. What do I need to change to get it to work correctly? I've tried re-writing the code multiple times so I must be missing some concept of how EventListeners or JPanels work.
package com.spencerlarry;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class View extends JFrame{
public static final int OFF = 1;
public static final int ON = 1;
public static final String DARKGRAY = "#696969";
public static final String CYAN = "#00FFFF";
Space top;
Space bottom;
public View(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Window Test");
this.setSize(300, 300);
this.setMinimumSize(getSize());
this.setLayout(new GridLayout(2,1));
add(new Space());
add(new Space());
}
public class Space extends JPanel implements MouseListener{
private String color;
public Space(){
setBackground(Color.decode(DARKGRAY));
addMouseListener(this);
}
public String getColor(String c){
return color;
}
public void setColor(){
if(color == CYAN){
setBackground(Color.decode(DARKGRAY));
}
else{
setBackground(Color.decode(CYAN));
}
}
@Override
public void mouseClicked(MouseEvent e) {
this.setColor();
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
}