制作一个Button类(不使用swing)

时间:2016-11-04 22:27:26

标签: java jcomponent

首先,下面的代码按预期工作(除了因为我将在下面说明的原因而无法测试的部分除外)

  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);

我设置好了,当单击按钮时单独悬停按钮将使用changeState()和changeImage()。

在我的每个方法(mousePressed,mouseReleased,mouseEntered和mouseExited)中,我已经设置了这些参数来更改图像,但是由于显而易见的原因,除非我已经定义了一个区域并且我已阅读了,MouseListener可以很好地监听的区域是任何JComponents。这是否意味着我需要使用JLabel(由于默认情况下它主要是交互性质)或者是否有更好的方法来实现可点击区域?

1 个答案:

答案 0 :(得分:0)

看看here之后我会给你一个简单的课,看看如何在JPanel或JComponent上绘制图像,然后你可以尝试使用mouseMotion:

上的示例图片图片" JPanel" :

`import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class DrawOnJ extends JPanel{

    BufferedImage MyImage;

    public ImagePanel() {
       try {                
          MyImage = ImageIO.read(new File("your img path/name"));
       } catch (IOException ex) {
           ex.printStackTrace();
       }
    }

    @Override
    protected void paintComponent(Graphics gr) {
        super.paintComponent(g);
        gr.drawImage(MyImage, 0, 0, this); 
    }

}`

这是用于在上绘制图像" JLabel" :

BufferedImage image = null; // get your buffered image.
ImageIcon icon = new ImageIcon((Image)image);
JLabel label = new JLabel();
label.setIcon(icon);