Text Field (and mouse listener)

This is a more complex example using a text field and mouse listener to trap stings entered from the keyboard.

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import java.util.*;

public class HitList extends Applet implements ActionListener, MouseListener
{

private ArrayList artists = new ArrayList();
private String text;
private boolean itemSelected = false;
private int indexSelected = -1;
private Button add, remove, insert, right;
private TextField textField;
private Artist artist;
private int stepSize = 40;
private int startY = 60;

public void init()
{

add = new Button("add at end");
add(add);
add.addActionListener(this);
remove = new Button("remove");
add(remove);
remove.addActionListener(this);
insert = new Button("insert");
add(insert);
insert.addActionListener(this);
textField = new TextField("", 15);
add (textField);
addMouseListener(this);
artist = new Artist("Elvis");
boolean result =artists.add(artist);

}
public void actionPerformed(ActionEvent event)
{

text = textField.getText();
if (event.getSource() == add)
add();
if (event.getSource() == remove)
remove();
if (event.getSource() == insert)
insert();
itemSelected = false;
repaint();

}
public void mouseClicked(MouseEvent event)
{

int yCoord = event.getY();
indexSelected = (yCoord - startY)/stepSize;
itemSelected = true;
repaint();

}
public void mouseReleased(MouseEvent mouse)
{
}
public void mousePressed(MouseEvent mouse)
{
}
public void mouseEntered(MouseEvent mouse)
{
}
public void mouseExited(MouseEvent mouse)
{
}
private void add()
{

artist = new Artist(text);
artists.add(artist);

}
private void remove()
{

if (itemSelected)
artists.remove(indexSelected);

}
private void insert()
{

artist = new Artist(text);
if (itemSelected)
artists.add(indexSelected, artist);

}
public void paint(Graphics g)
{

for (int i = 0; i<artists.size(); i++)
{

artist = (Artist) artists.get(i);
int x = 20;
int y = stepSize * i + startY;
if (i == indexSelected && itemSelected)
artist.display(g, x, y, false);
else
artist.display(g, x, y, false);

}

}

}

private int height = 25, width = 100;
private String name;
public Artist(String name)

{

this.name = name;

}

public void display(Graphics g, int x, int y, boolean selected)

{

if (selected)
{

g.setColor(Color.black);
g.fillRect(x, y, width, height);
g.setColor(Color.black);

}
else
g.drawRect (x, y, width, height);
g.drawString(name, x+5, y+20);

}
}

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License