あなたがそのようなあなたがすべてのレンダリングの上に多くの制御を必要とするゲームとして洗練された何かを作っている場合を除き。そうでない場合は、独自のレンダリングループを実装する代わりに、javax.swing.timer
をフルに使用できます。
EDTでレンダリングループまたはスリープを適用しないでください。 actionPerformed
内のアクションは、通常、「1回限り」のアクションです。
この場合はボタンであなたのactionPerformedが故にあなたがする必要があるすべては、それがクリックされたときに(アニメーションを制御)、タイマーをオン/オフすることで、単に「オン/オフ」ボタンのように動作します:
class DrawingSpace extends JPanel{
private JButton button;
private Timer timer;
private int idx;
private Color[] colors;
public DrawingSpace(){
setPreferredSize(new Dimension(200, 200));
initComponents();
add(button);
}
public void initComponents(){
idx = 0;
colors = new Color[]{Color.RED, Color.YELLOW, Color.ORANGE, Color.MAGENTA, Color.BLUE, Color.CYAN, Color.GREEN};
button = new JButton("Let the colors rock!");
timer = new Timer(100, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
//Change color every (approx) 100 milliseconds
idx = (idx + 1) % colors.length; //cycle through the colours
setBackground(colors[idx]);
}
});
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
if(!timer.isRunning())
timer.start();
else
timer.stop();
}
});
}
}
コードを実行するランナークラス:
class RainbowRunner{
public static void main(String[] args){
// Run the GUI code on the EDT
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Rainbow Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DrawingSpace());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
'try..catch'は、任意の有用な警告を抑制したり、あなたが得るかもしれないエラーであることを。 – usr2564301
InterruptedExceptionにprintステートメントを入れて、何が起こるかを見てください。 :) – DejaVuSansMono
このコードをどのように実行しますか? 'AneurysmMode'はボタンであることを意図していますか? – ItamarG3