当我的鼠标悬停在它上面时,我想放大我的JButton图像

时间:2015-07-09 15:45:51

标签: java eclipse image button jbutton

我无法解决这个问题。我想要发生的是当我的鼠标悬停在"开始"菜单中的JButton可以放大50-100像素。有什么方法可以使用我的代码? 提前致谢! "我正在使用java eclipse btw"不知道这是否有帮助

//START_Button
    JButton button = new JButton("Start");
    frame.pack();
    JTextPane TEXT = new JTextPane();
    BufferedImage buttonIcon;
    try {
        buttonIcon = ImageIO.read(new File("C:\\Users\\GOULDEN\\Desktop\\MENU_START.png"));
        button = new JButton(new ImageIcon(buttonIcon));
        button.setBorder(BorderFactory.createEmptyBorder());
        button.setContentAreaFilled(false);
        Container contentPane = frame.getContentPane();
        contentPane.add(button);
        button.setBounds(500,250,300,75);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }
}

1 个答案:

答案 0 :(得分:0)

实施MouseListener并使用mouseEntered()mouseExited()使您的按钮更大。

声明将在instance variables等其他方法中访问的变量,以便能够访问它们。

import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Demo extends JFrame implements MouseListener {

    private static final long serialVersionUID = 1L;    
    private JButton startButton;


    public Demo() {

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(100, 100, 500, 500);
        this.setLayout(null);        

        startButton = new JButton("Start");                                   
        startButton= new JButton(new ImageIcon("path/to/image.jpg"));
        startButton.setBorder(BorderFactory.createEmptyBorder());
        startButton.setContentAreaFilled(false);
        startButton.setBounds(1, 2, 100, 25);
        startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        startButton.addMouseListener(this);

        this.add(startButton);
        this.setVisible(true);
    }

    public static void main(String[] args) {
         new Demo();
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub


    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseEntered(MouseEvent e) {
        startButton.setSize(400, 125);
        this.repaint();
    }

    @Override
    public void mouseExited(MouseEvent e) {
        startButton.setSize(100, 25);
        this.repaint();
    }              
    }

顺便说一句,如果您不打算使用图片属性,则无需使用bufferedImage,因此只需将图片位置直接插入ImageIcon即可删除{{} 1}}阻止

try-catch

查看这些链接,详细了解您的示例中使用的主题。

  1. Variable Scopes
  2. MouseListener implementation
  3. Working With Images