的基本概念是,你要旋轉的圖像(或者採取一些行動),而按鈕是「武裝」。
您可以實現此目的的一種方法是將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();
}
}
}
}
你能後紡紗的公司嗎? – Mordechai
1)AWT,SWT,Swing,JavaFX ..? 2)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –
發佈的代碼與您的問題有什麼關係? – Mordechai