JLabel を JButton 内に配置し、JButton のサイズを調整するケースがあります。
これは基本的なプロパティです。デフォルトでは、最上位に配置され、 &JComponent
からのすべてのイベントを消費します。Mouse
Keyboard
2つの方法があります
編集
@狂った、
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class JButtonAndIcon {
private JLabel label = new JLabel();
private Random random = new Random();
private ImageIcon image1; // returns null don't worry about in Swing
private ImageIcon image2; // returns null don't worry about in Swing
private Timer backTtimer;
private int HEIGHT = 300, WEIGHT = 200;
public JButtonAndIcon() {
label.setPreferredSize(new Dimension(HEIGHT, WEIGHT));
final JButton button = new JButton("Push");
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setLayout(new BorderLayout());
button.add(label);
button.setMultiClickThreshhold(1000);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (button.getIcon() == image1) {
label.setIcon(image2);
} else {
label.setIcon(image1);
if(backTtimer.isRunning()){
backTtimer.restart();
}
}
}
});
JFrame frame = new JFrame("Test");
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
startBackground();
frame.setVisible(true);
}
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JButtonAndIcon t = new JButtonAndIcon();
}
});
}
private void startBackground() {
backTtimer = new javax.swing.Timer(1500, updateBackground());
backTtimer.start();
backTtimer.setRepeats(true);
}
private Action updateBackground() {
return new AbstractAction("Background action") {
private final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(getImage()));
}
};
}
public BufferedImage getImage() {
int w = label.getWidth();
int h = label.getHeight();
GradientPaint gp = new GradientPaint(0f, 0f, new Color(
127 + random.nextInt(128),
127 + random.nextInt(128),
127 + random.nextInt(128)),
w, w,
new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
g2d.setColor(Color.BLACK);
return bi;
}
}