我有一種情況,我把JLabel放在JButton裏面,並且調整了JButton的尺寸 。
這是基本的屬性,默認情況下頂奠定JComponent
消耗的所有事件從Mouse
來到& Keyboard
有兩種方式
編輯
@Mad,
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;
}
}
爲什麼你需要一個在一個按鈕標籤? – MadProgrammer 2013-03-12 07:12:21
你可以在'JButton'上調用'setText',它可以讓你做任何你可以用標籤做的事情。你爲什麼需要標籤? – DaoWen 2013-03-12 07:15:16
要擺脫圍繞文本框點擊按鈕和UI修改 – 2013-03-12 07:23:51