Implement MouseListener
and use the mouseEntered()
and mouseExited()
to make your button bigger.
Declare the variables that will be accessed in other methods as instance variables to be able to access them.
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();
}
}
btw, there is really no need to use the bufferedImage
if you aren't going to use your image properties, so just insert the image location directly into ImageIcon
so you can remove the try-catch
block
new JButton(new ImageIcon("path/to/image.jpg"));
Check out these links to read more about the topics used in your example.
- Variable Scopes
- MouseListener implementation
- Working With Images