1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| package net.sm.window.button;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JPanel;
import net.sm.main.SM;
import net.sm.window.ImageSM;
import net.sm.window.Tools;
public class Button extends JPanel implements ButtonInterface, MouseListener{
protected String name;
protected Image img;
protected int randColor;
public Button(String name){
this(name, 0, 0);
}
public Button(String name, int x, int y){
this(name, x, y, null);
}
public Button(String name, int x, int y, ImageSM img){
this.name = name.toUpperCase();
this.setLocation(x, y);
this.setSize(200, 30);
this.img = SM.images.get(img);
this.randColor = new Random().nextInt(SM.colors.length);
this.addMouseListener(this);
}
public void paint(Graphics g){
if(this.img == null){
g.setColor(SM.colors[randColor]);
g.fillRect(this.getX(), this.getY(), this.getWidth(), this.getHeight());
Tools.drawContourRect(g, Color.DARK_GRAY, this.getX(), this.getY(), this.getWidth(), this.getHeight());
}
else{
g.drawImage(img, this.getX(), this.getY(), null);
}
FontMetrics fm = g.getFontMetrics();
Font font = new Font("Arial", Font.BOLD, 17);
g.setFont(font);
g.setColor(Color.black);
int widthName = fm.stringWidth(name);
g.drawString(name, this.getX()+ this.getWidth() /2 - widthName/2, this.getY() + 20);
}
public boolean inCollision(Point point) {
if(point.getX() >= this.getX() && point.getX() <= this.getX()+this.getWidth() &&
point.getY() >= this.getY() && point.getY() <= this.getY()+this.getHeight()){
return true;
}
return false;
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouseClicked");
}
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouseEntered");
}
@Override
public void mouseExited(MouseEvent e) {
System.out.println("mouseExited");
}
@Override
public void mousePressed(MouseEvent e) {
System.out.println("mousePressed");
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println("mouseReleased");
}
} |
Partager