-1
首先,下面的代碼按預期工作(除了我一直無法測試的原因,我將在下面註明的部分)製作Button類(沒有用擺動)
public class Button implements MouseListener {
String function;
int currentState;
int[] pos;
int[] size;
private BufferedImage normal;
private BufferedImage hover;
private BufferedImage click;
BufferedImage currentImage;
public Button(String func, String location, int[] position,int[] dimensions){
function = func;
//State 0 means not interacted with, State 1 means hovered and state 2 means clicked
currentState = 0;
pos = position;
size = dimensions;
String dpath = "/Images/";
String npath = dpath+location+".png";
String hpath = dpath+location+"h.png";
String cpath = dpath+location+"c.png";
try{
normal =ImageIO.read(getClass().getResource(npath));
hover =ImageIO.read(getClass().getResource(hpath));
click =ImageIO.read(getClass().getResource(cpath));
}catch(Exception e){
System.err.println("Error loading button image: "+ e);
}
currentImage = normal;
}
private void changeState(int c){
currentState = c;
changeImage();
}
private void changeImage(){
if (currentState == 0){
currentImage = normal;
}else if (currentState == 1){
currentImage = hover;
}else if (currentState == 2){
currentImage = click;
}
public int getX(){
return pos[0];
}
public int getY(){
return pos[1];
}
public BufferedImage getSprite(){
return currentImage;
}
這是畫在使用
g.drawImage(but.getSprite(), but.getX(), but.getY(), null);
我有它設置所以單擊按鈕時徘徊,獨自離開了按鈕,將使用改變狀態()和changeImage()從不同的類中的畫面。在我的每個方法(mousePressed,mouseReleased,mouseEntered和mouseExited)中,我已經設置了這些參數來改變圖像,但由於顯而易見的原因,除非我定義了一個區域和我所擁有的區域,否則這些參數都不會被激活。閱讀,MouseListener可以聽到的區域是任何JComponents。這是否意味着我需要使用JLabel(由於默認情況下它主要是交互式的),還是有更好的方法來實現可點擊區域?