Hint for JTextField / JPasswordField - java

I built a class extending the JTextField class and an own hint function.
package functions;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class TextField extends JTextField {
private String hint;
private Color cForeground;
private Color cHint;
public void setHint(String s) {
hint = s;
cForeground = getForeground();
setText(hint);
cHint = new Color(cForeground.getRed(), cForeground.getGreen(),
cForeground.getBlue(), cForeground.getAlpha() / 2);
addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent arg0) {
if (getText().equals("")) {
setForeground(cHint);
setText(hint);
}
}
#Override
public void focusGained(FocusEvent arg0) {
if (getText().equals(hint)) {
setText("");
setForeground(cForeground);
}
}
});
}
}
1) At the moment my hint only shows up when it's not focused. But I want my hint to be visible when it's empty - also when it's focused. I played around with ActionListener instead of FocusListener, but I didn't get it.
2) I want the same thing for JPasswordField, but I don't want to write the same method in 2 different classes. Is there a way I can point at the same method from both classes while one extends JTextField and the other one JPasswordField?
3) I decide whether the hint shall be shown by calling getText(), but that's not nice in handling with passwords (I don't want to get blamed for logging them...). Is there another way wich would prevent this?
Btw: I know about TextPrompt, but I want to build an own simple solution.

As I understand, you want a thing called placeholder in HTML. Then override paintComponent method like this:
public class STextField extends JTextField{
public static final Color placeholderColor = new Color(cForeground.getRed(), cForeground.getGreen(), cForeground.getBlue(), cForeground.getAlpha() / 2);
public STextField(String placeholder){
this.placeholder = placeholder;
}
protected void paintComponent(final Graphics pG) {
super.paintComponent(pG);
if(placeholder.length() == 0 || getText().length() > 0)
return;
final Graphics2D g = (Graphics2D) pG;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(placeholderColor);
int offset = 4; // This value depends on height of text field. Probably can be calculated from font size.
g.drawString(placeholder, getInsets().left, pG.getFontMetrics().getMaxAscent() + offset);
}
private String placeholder;
}

Related

JFrame help - passing value into PaintComponent()

I've been working on a small "game" project for a while now and haven't been able to pass a value into my paintComponent method in any way.
Here's my program. I used a boolean test parameter, but the paintComponent method does not consider test to be true and not paint the blue square.
How can I fix this? Any help would be greatly appreciated.
Class 1 (Swing):
package swing;
import javax.swing.*;
import javax.*;
import java.awt.*;
import java.awt.event.*;
public class swing {
private static draw object = new draw();
public static void main(String[] args) {
JFrame frame = new JFrame("RogueLikeLike MVP");
frame.setVisible(true);
frame.setFocusable(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
frame.add(object);
}
static class Move implements KeyListener{
public boolean isFocusTraversable ( ) {
return true;
}
public void keyPressed(KeyEvent e) {
int x = 10;
int y = 10;
char c = e.getKeyChar();
if(c == 's')
y+=10;
if(c == 'a')
x-=10;
if(c == 'w')
y-=10;
if(c == 'd')
x+=10;
object.setAlignmentX(x);
object.setAlignmentY(y);
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
}
Class 2 (draw):
package swing;
import javax.swing.*;
import java.awt.*;
public class draw extends JPanel
{
boolean test = true;
private static final long serialVersionUID = 1L;
/*public void passMethod(draw object) {
int x = (int) object.getAlignmentX();
int y = (int) object.getAlignmentY();
}*/
public void drawing(draw object){
draw thing = new draw();
thing.setX(object.getAlignmentX());
int x = 55;
repaint();
}
private void setX(float alignmentX) {
setX((int) alignmentX);
}
private void setY(float alignmentY) {
setY((int) alignmentY);
}
public void paintComponent(Graphics g, boolean test){
super.paintComponents(g);
//int x = (int)object.getAlignmentX();
//int y = (int)object.getAlignmentY();
if(test==true)
{
g.setColor(Color.blue);
g.fillRect(getX(),getY(),100,100);
}
}
}
paintComponent can be overloaded, but the overloaded version won't be used to paint the Component. Actually paintComponent isn't called by the user, but by the painting routine. Instead of overloading the method you should consider using a variable for test and reading/updating this variable.
Like this:
private boolean test = true;
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
if(test){
//the rest of the code
}
}
Short answer, you can't. This isn't how method overriding works.
paintComponent is one of the documented methods used by the painting sub system to allow you to plugin custom painting, in order to work it MUST match a very particular method signature, otherwise, how would the API know what to call
Instead, paintComponent should paint the current known state of the component, either directly or indirectly.
What this means is, you component should either have a set of properties which the paintComponent method can access or some other object (ie a model) which it can use to determine the current state of which to paint.
You could use a delegate approach, which would allow to define a contract (maybe via a interface) which paintComponent could call, passing the information you need to these delegates, in order for them to perform the required painting.
See Painting in AWT and Swing and Performing Custom Painting for more details about how painting works
nb:
Add the #Override annotation above your paintComponent method, the compiler will error telling you that their is no matching method which supports your signature
Call super.paintComponent NOT super.paintComponent"s", this would set up a recursive call which would result in a StackOverflowError

Java: Repaint in Swing Not Working

I am learning java swing and am having trouble with the following program. It creates a small frame with a quit button at top. The objective is to display coordinates wherever the mouse is clicked. When I click the mouse 2 unwanted things are happening:
the quit button is overridden by the mouse clicks and it no longer responds (instead of responding to event and quitting, it displays coordinates on top of the quit button).
when I click at a new location, the coordinates from the old location persist.
I used removeAll() and revalidate() before doing repaint() based on this discussion but that has not helped. This code is taken from here and the code to says to research online documentation for why this is happening.
Any pointers?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
public class QuitCoordinateTest {
public static void main(String[] args){
GUI gui = new GUI();
}
}
class MyFrame extends JFrame implements ActionListener{
int clickX;
int clickY;
public void paint(Graphics g){
g.drawString("" + clickX + ", " + clickY, clickX, clickY);
}
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
//=======================================================//
class GUI extends MyFrame {
JButton quitButton = new JButton("Quit");
public GUI(){
MyFrame displayWindow = new MyFrame();
displayWindow.setTitle("Title");
/*
JPanel buttonPanel = new JPanel();
buttonPanel.add(quitButton);
displayWindow.getContentPane().add(buttonPanel,BorderLayout.NORTH);
JPanel textPanel = new JPanel();
*/
displayWindow.getContentPane().add(quitButton,BorderLayout.NORTH);
quitButton.addActionListener(displayWindow);
displayWindow.setSize(201,201);
displayWindow.setVisible(true);
// displayWindow.pack();
displayWindow.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
displayWindow.addMouseListener(new MouseProc(displayWindow));
}//end constructor
}//end class GUI definition
//=======================================================//
//This listener class monitors for mouse presses and
// displays the coordinates of the mouse pointer when the
// mouse is pressed on the source object.
class MouseProc extends MouseAdapter{
MyFrame refToWin;
MouseProc(MyFrame inWin){
refToWin = inWin;
}
//Override the mousePressed method to determine and
// display the coordinates when the mouse is pressed.
public void mousePressed(MouseEvent e){
refToWin.removeAll();
refToWin.clickX = e.getX();
refToWin.clickY = e.getY();
//Force the JFrame object to be repainted in order to
// display the coordinate information.
refToWin.removeAll();
refToWin.validate();
refToWin.repaint();
}
}
repaint() is working fine.
Avoid drawing directly on the JFrame.
Instead draw in the protected void paintComponent(Graphics g) method override of a JPanel that is then displayed in your JFrame.
Be sure to call the super's paintComponent(g) method inside of your paintComponent override -- this will erase the old images and is the reason for one of your problems.
Use reasonable comments in your code. Too many comments and too much text distracts and makes understanding your code harder, not easier.
Calling removeAll() on your JFrame will do just that -- remove all components including your button. Why are you calling this? Are you sure that you want to call this method?
A minor nitpick -- you'll want to avoid directly setting the fields of another class, such as your clickX and clickY fields. Instead, make them private, and only allow outside classes to modify them through public methods. While it may not matter much for this small program, it will matter greatly when you start scaling up your programming and create large programs with complex interactions. The key to success here will be to limit and control all communication between classes to avoid hard to detect side effects.
For example, something like...
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
String str = String.format("[%d, %d]", clickX, clickY);
g.drawString(str, clickX, clickY);
}
public int getClickX() {
return clickX;
}
public void setClickX(int clickX) {
this.clickX = clickX;
}
public int getClickY() {
return clickY;
}
public void setClickY(int clickY) {
this.clickY = clickY;
}
For example
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class DetectClicks extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private int clickX;
private int clickY;
public DetectClicks() {
MyMouseListener mouseAdapter = new MyMouseListener(this);
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter); // to allow dragging!
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
String str = String.format("[%d, %d]", clickX, clickY);
g.drawString(str, clickX, clickY);
}
public int getClickX() {
return clickX;
}
public void setClickX(int clickX) {
this.clickX = clickX;
}
public int getClickY() {
return clickY;
}
public void setClickY(int clickY) {
this.clickY = clickY;
}
private static void createAndShowGui() {
DetectClicks mainPanel = new DetectClicks();
JFrame frame = new JFrame("DetectClicks");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyMouseListener extends MouseAdapter {
private DetectClicks detectClicks;
public MyMouseListener(DetectClicks detectClicks) {
this.detectClicks = detectClicks;
}
#Override
public void mousePressed(MouseEvent evt) {
showPoint(evt);
}
#Override
public void mouseDragged(MouseEvent evt) {
showPoint(evt);
}
private void showPoint(MouseEvent evt) {
detectClicks.setClickX(evt.getX());
detectClicks.setClickY(evt.getY());
detectClicks.repaint();
}
}
Your event is getting consumed by the handler that prints the coordinates, you need to redispatch the event so that the button can see it. You can do it like this, inside the coordinate display event handler:
Component c = e.getComponent();
c.getParent().dispatchEvent( e );
Also, I'd be tempted to use the glass pane of the frame, and put a JLabel on it with the co-ordinates rather than messing with the paint method.
you don't have to use any of repaint(),invalidate() etc.
i highly recommend to use
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//TODO udpdate UI compontents, layouts etc.
}
});
this guarantees that UI components update on real time. Because we don't know when the system update UI hierarchy so we can't force it. This allow system to determine by it's self.

Create a Swing component based on another but with different API

I would like to create a new Swing JComponent based on an existing one, but with a different API. In other words, I don't want to extend the existing component, because I don't want it's API to be accessible.
Here an example to clarify my needs:
A replacement of the JCheckBox which show two buttons ON/OFF. This could be based on a pre-configured JCommandButtonStrip (some info here) but exposing exactly the same API of JCheckBox. The configuration of the JCommandButtonStrip must not be altered.
What is the best approach for such a problem?
Clarifications:
As someone pointed out, what I wrote about API is not clear.
Of course JComponent have a number of public fields and methods which will be available for each sub-class. Then each sub-class of JComponent may add its own public fields and methods. For example, AbstractButton adds the isSelected() method, while JCommandButtonStrip adds the getButtonCount() method.
So, what I meant is: I want to create a new JComponent sub-class MyJComponent, which is based on an existing one ExistingJComponent. I don't want the public methods of ExistingJComponent, except those of JComponent, to be exposed by my class MyJComponent. Then I want to add some public methods to MyJComponent.
Please note that I'm not looking for an alternative to the JCommandButtonStrip/JCheckBox example. I'm interested in a general approach to such a problem.
You can create a new class which extends JComponent then inside the constructor insert a checkbox into itself.
public class MyCoolCheckbox extends JComponent{
private JCheckBox checkbox;
public MyCoolCheckbox(String label) {
checkbox= new JCheckBox(label);
this.setLayout(new BorderLayout());
this.add(checkbox, BorderLayout.CENTER);
}
}
This is obviously incomplete and you may need to delegate certain methods to the child. It might get messy. IDEs like IntelliJ IDEA will generate all this for you if you hit alt-ins (by default) then delegate, then select the checkbox member and pick the entries you want to delegate. For example:
public void setForeground(Color fg) {
checkbox.setForeground(fg);
}
public void setBackground(Color bg) {
checkbox.setBackground(bg);
}
public Color getForeground() {
return checkbox.getForeground();
}
public Color getBackground() {
return checkbox.getBackground();
}
Keep in mind that because the child is within the Swing component tree, other code will have access to the children even though they are marked private.
((JCheckBox)myCoolCheckbox.getComponents()[0]).setSelected(true);
As shown here, you can use two instances of JToggleButton in a ButtonGroup to "show two buttons ON / OFF." The ButtonGroup causes only one button in the group to be selected at a time. The following change is illustrated:
private final JLabel label = new JLabel(" \u2713 ");
Based on this picture of JCommandButtonStrip:
I think you are looking for JToggleButton as #trashgod suggested, but I'm not sure about buttons group given the current description of your "problem". If you need buttons group then use it.
Anyway my answer points to this line:
This could be based on a pre-configured JCommandButtonStrip (some info
here) but exposing exactly the same API of JCheckBox.
Once again it's not clear if you're trying to do a buttons bar such as JCommandButtonStrip or you want to do something else. However you can make your own component extending from JComponent and delegate only those methods that are needed from the outside. For example let's say you want to do a buttons bar such as JCommandButtonStrip. Then you can have:
One class extending from JComponent: your buttons bar.
Another one providing an API to add "commands" to the buttons bar.
Note: There's already a JToolBar component which can perfectly be used without reinvent the wheel. The example below is just to show you that you can control the API offered to the developers.
MyCommandBar.java
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeListener;
public class MyCommandBar extends JComponent {
private final JPanel content;
private final Map<String, CommandItem> map = new HashMap<>();
public MyCommandBar() {
super();
content = new JPanel(new GridLayout(1, 0));
content.setOpaque(false);
setLayout(new FlowLayout());
add(content);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics graphics = g.create();
graphics.setColor(getBackground());
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.dispose();
}
public void addCommandItem(String actionCommand, CommandItem commandItem) {
if(map.get(actionCommand) != null) {
removeCommandItem(actionCommand);
}
content.add(commandItem.getComponent());
map.put(actionCommand, commandItem);
}
public void removeCommandItem(String actionCommand) {
CommandItem commandItem = map.get(actionCommand);
if(commandItem != null) {
content.remove(commandItem.getComponent());
content.revalidate();
content.repaint();
map.remove(actionCommand);
}
}
public CommandItem getCommandItem(String actionCommand) {
return map.get(actionCommand);
}
public static class CommandItem {
public static final int TOGGLE_BUTTON_STYLE = 0;
public static final int CHECK_BOX_STYLE = 1;
public static final int DEFAULT_BUTTON_STYLE = 2;
private final AbstractButton component;
public CommandItem(String text, boolean state, Icon icon, int style) {
switch(style) {
case TOGGLE_BUTTON_STYLE : component = new JToggleButton(text, icon, state); break;
case CHECK_BOX_STYLE : component = new JCheckBox(text, icon, state); break;
default: component = new JButton(text, icon);
}
}
protected AbstractButton getComponent() {
return component;
}
public void addActionListener(ActionListener listener) {
component.addActionListener(listener);
}
public void addChangeListener(ChangeListener listener) {
component.addChangeListener(listener);
}
public void setAction(Action action) {
component.setAction(action);
}
}
}
Example of use
This code snippet shows how MyCommandBar class should be used:
MyCommandBar commandBar = new MyCommandBar();
commandBar.setBorder(BorderFactory.createLineBorder(Color.black, 1));
commandBar.addCommandItem("BOLD", new MyCommandBar.CommandItem("<html><b>Bold</b></html>", true, null, MyCommandBar.CommandItem.TOGGLE_BUTTON_STYLE));
commandBar.addCommandItem("ITALICS", new MyCommandBar.CommandItem("<html><i>Italics</i></html>", false, null, MyCommandBar.CommandItem.CHECK_BOX_STYLE));
commandBar.addCommandItem("UNDERLINE", new MyCommandBar.CommandItem("<html><u>Underline</u></html>", false, null, MyCommandBar.CommandItem.DEFAULT_BUTTON_STYLE));
And you'll see something like this:
You can create MyJComponent subclass of JComponent with a private field that references a forwarding class for ExistingComponent.
The interactions with ExistingComponent are done with the forwarding class through methods of MyJComponent, and you are free to add more methods to MyJComponent.
Please see Effective Java item 16, for the delegation pattern used with the forwarding class.

How to create a function to remove a button [Beginner]

I am currently using this function to create and display a button.
Button(String nm, int x, int y, int w, int h)
{
super(nm, x, y, w, h);
}
void display()
{
if(currentImage != null)
{
float imgWidth = (extents.y*currentImage.width)/currentImage.height;
pushStyle();
imageMode(CORNER);
tint(imageTint);
image(currentImage, pos.x, pos.y, imgWidth, extents.y);
stroke(bgColor);
noFill();
rect(pos.x, pos.y, imgWidth, extents.y);
noTint();
popStyle();
}
else
{
pushStyle();
stroke(lineColor);
fill(bgColor);
rect(pos.x, pos.y, extents.x, extents.y);
fill(lineColor);
textAlign(CENTER, CENTER);
text(name, pos.x + 0.5*extents.x, pos.y + 0.5* extents.y);
popStyle();
}
}
I would like to create a function such as:
void hide()
so that I could remove or hide the function when I need to, after it is clicked. How should I approach this? am I basically setting everything to null? to remove it?
I can´t be sure now as you haven´t posted the actual class definition but I´m assuing you either extend java.awt.Button or javax.swing.JButton.
In that case, you can just use the setVisible method:
public void hide(){
this.setVisible(false);
}
This works on every GUI-Component that extends java.awt.Component.
In a very simple example (that is a one-way thing since you can´t get the button back ;)) this would look like:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class DemoFrame extends JFrame {
private JButton buttonToHide;
public DemoFrame() {
this.setSize(640, 480);
buttonToHide = new JButton();
buttonToHide.setText("Hide me!");
buttonToHide.addActionListener(new ButtonClickListener());
this.getContentPane().add(buttonToHide);
}
public class ButtonClickListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (buttonToHide.isVisible()) {
buttonToHide.setVisible(false);
}
}
}
public static void main(String[] args){
new DemoFrame().setVisible(true);
}
}
While writing up that example I found that java.awt.Component even defines a method "hide()" but this is marked as deprecated with the hint to use setVisible instead.
I hope this helps!
Maybe a simple boolean show wrapping the display statements... And a key or what ever to toogle it.
like:
void display(){
if(show){
//all stuff
}
}
void toogleShow(){
if(/*something, a key an event...*/){
show = !show;
}
}
You would need to wrap functionality of the button as well.

Manual Positioning of Image in JFrame

I am trying to create a JFrame that displays an image from a file path onto a particular position on the JFrame. At a later time (when a button is clicked), I want the image to move positions, say, 50 pixles to the left. If a layout manager is necessary, I want to use the null layout, as this is a project for myself and I am not quite ready to learn how to write my own layout manager.
So far, I have managed to display a BufferedImage in a frame, but I do not know how to specify its position.
Is using a BufferedImage even the correct approach? What is the best way to go about doing this?
Update: I tried to follow your suggestion of using mouselistener and it resulted in this:
class ImgComponent extends JComponent implements ChangeListener, MouseListener {
MovableImage mi;
public ImgComponent(MovableImage mi) {
this.mi = mi;
mi.addListener(this);
mi.addListener1(this);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(mi.i, mi.getX(), mi.getY(), null);
}
#Override
public void stateChanged(ChangeEvent e) {
repaint();
}
#Override
public void mouseClicked(MouseEvent e) {
mi.setPos(100, 100);
System.out.println("yay");
}
}
But unfortinely, the mouseClicked event never triggers. I just want that damn image to move, lol.
Here's a complete example that uses the model/view/controller pattern. (Just dump all snippets after each other in a single .java file.)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
// A class encapsulating an image and a x-coordinate (a "model")
class MovableImage {
Image i = new ImageIcon("duke.png").getImage();
private int x = 0;
// Observers that are interested in movements.
List<ChangeListener> listeners = new ArrayList<ChangeListener>();
public void addListener(ChangeListener cl) {
listeners.add(cl);
}
public int getX() {
return x;
}
public void incrementX() {
x += 10;
// Notify those interested.
for (ChangeListener cl : listeners)
cl.stateChanged(null);
}
}
// A graphical component displaying the model.
// Object of this class are interested in movement because when the image moves,
// this component needs to be repainted.
class ImgComponent extends JComponent implements ChangeListener {
// The movable image to present.
MovableImage mi;
public ImgComponent(MovableImage mi) {
this.mi = mi;
mi.addListener(this);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(mi.i, mi.getX(), 10, null);
}
// This method is called from MovableImage when the position changes.
#Override
public void stateChanged(ChangeEvent e) {
repaint();
}
}
// Main class.
public class FrameTestBase extends JFrame {
public static void main(String args[]) {
// Create the "model".
final MovableImage mi = new MovableImage();
FrameTestBase t = new FrameTestBase();
t.setLayout(new BorderLayout());
// Add a component presenting the model.
t.add(new ImgComponent(mi), BorderLayout.CENTER);
// Create a button which increments x when clicked on.
t.add(new JButton(new AbstractAction("Move right") {
#Override
public void actionPerformed(ActionEvent e) {
mi.incrementX();
}
}), BorderLayout.SOUTH);
// Show it.
t.setDefaultCloseOperation(EXIT_ON_CLOSE);
t.setSize(400, 400);
t.setVisible(true);
}
}
Regarding your edit:
You need to add the mouse listener as well. In the constructor:
public ImgComponent(MovableImage mi) {
this.mi = mi;
mi.addListener(this);
mi.addListener1(this);
}
add the following line at the bottom:
addMouseListener(this);

Categories