基本概念是,您想在按钮“武装”时旋转图像(或采取一些行动)。
实现此目的的一种方法是将 a 添加ChangeListener
到按钮并监视ButtonModel#isArmed
状态。
public class ChangeButton {
public static void main(String[] args) {
new ChangeButton();
}
public ChangeButton() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SlotPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SlotPaneextends JPanel {
private SpinPane spinPane;
private JButton button;
public SlotPane() {
spinPane = new SpinPane();
button = new JButton("Press");
// I've attached directly to the model, I don't
// think this is required, simply attaching a change
// listener to the button achieve the same result.
button.getModel().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
spinPane.setSpinning(button.getModel().isArmed());
}
});
setLayout(new BorderLayout());
add(spinPane);
add(button, BorderLayout.SOUTH);
}
}
public class SpinPane extends JPanel {
private BufferedImage mole;
private Timer timer;
private float angel = 0;
public SpinPane() {
try {
mole = ImageIO.read(new File("mole.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
timer = new Timer(15, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
angel += 15;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
}
@Override
public Dimension getPreferredSize() {
return mole == null ? super.getPreferredSize() : new Dimension(mole.getWidth(), mole.getHeight());
}
public void setSpinning(boolean spinning) {
if (spinning) {
if (!timer.isRunning()) {
timer.restart();
}
} else {
timer.stop();
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mole != null) {
int x = (getWidth() - mole.getWidth()) / 2;
int y = (getHeight() - mole.getHeight()) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angel), getWidth() / 2, getHeight() / 2));
g2d.drawImage(mole, x, y, this);
g2d.dispose();
}
}
}
}