I'm trying to actively render and found using JButtons was not very good so I set out to make my own class. I don't have much experience with ActionListeners and am trying to use a demo I found online. I'm making my own version of the second and third class examples posted by Ko Wey https://coderanch.com/t/342333/java/Custom-Buttons .
Everything renders fine but nothing happens when clicked
package com.whycom.engine;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;
import javax.swing.JPanel;
public class Button extends JPanel implements MouseListener
{
private static final long serialVersionUID = 1L;
private int width;
private int height;
private int xPos;
private int yPos;
private String text;
private Color textColor;
private Color bgColor;
private Color borderColor;
private Font font;
private Color hoverColor;
private boolean hover;
private Vector< ActionListener > listeners;
public Button( int xPos, int yPos, int width, int height, String text,
Font font, Color textColor, Color bgColor, Color borderColor,
Color hoverColor )
{
super();
this.width = width;
this.height = height;
this.text = text;
this.textColor = textColor;
this.bgColor = bgColor;
this.borderColor = borderColor;
this.xPos = xPos;
this.yPos = yPos;
this.font = font;
this.hoverColor = hoverColor;
listeners = new Vector< ActionListener >();
addMouseListener( this );
}
public void render( Graphics g )
{
//omitted because it shouldn't be the problem
}
@Override
public void mouseClicked( MouseEvent arg0 )
{
fireEvent( new ActionEvent( this, 0, text ) );
}
@Override
public void mouseEntered( MouseEvent arg0 )
{}
@Override
public void mouseExited( MouseEvent arg0 )
{}
@Override
public void mousePressed( MouseEvent arg0 )
{}
@Override
public void mouseReleased( MouseEvent arg0 )
{}
private void fireEvent( ActionEvent event )
{
for( int i = 0; i < listeners.size(); i++ )
{
ActionListener listener = ( ActionListener ) listeners
.elementAt( i );
listener.actionPerformed( event );
}
}
public void addActionListener( ActionListener listener )
{
listeners.addElement( listener );
}
public void removeActionListener( ActionListener listener )
{
listeners.removeElement( listener );
}
}
When creating my state class I do this
menu1 = new Button( 0, 0, 400, 100, "Test", buttonFont, Color.white,
Color.black, Color.white, Color.blue );
menu1.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
System.out.println( "I am clicked!" );
}
} );
I've had the getPreferredSize method in Button, as well as putting this.add(menu1) in my state constructor since state extends JPanel. Neither did anything for it.
I've managed to strip my project down to 4 classes that replicate the problem https://github.com/CloudyNinja/StackOverflowButtonQ