プログラムでボタンを押したときにJFrameをアニメーション化して半分のサイズにしたい
したがって、ボタンをクリックすると、ボタンにアクセスできます。次に、次を使用できます。
SwingUtilities.windowForComponent( theButton );
フレームへの参照を取得します。
したがって、Timer の ActionListener を作成するときに、Window で ActionListener の引数として渡すことができます。
編集:
mre による提案はシンプルで単純明快で、多くの場合使いやすい (この場合はおそらくより良い解決策)。
私の提案はもう少し複雑ですが、SwingUtilities メソッドを紹介していました。これにより、最終的には、作成するフレームやダイアログで使用される可能性のある、より再利用可能なコードを記述できるようになります。
簡単な例は次のようになります。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AnimationSSCCE extends JPanel
{
public AnimationSSCCE()
{
JButton button = new JButton("Start Animation");
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
WindowAnimation wa = new WindowAnimation(
SwingUtilities.windowForComponent(button) );
}
});
add( button );
}
class WindowAnimation implements ActionListener
{
private Window window;
private Timer timer;
public WindowAnimation(Window window)
{
this.window = window;
timer = new Timer(20, this);
timer.start();
}
@Override
public void actionPerformed(ActionEvent e)
{
window.setSize(window.getWidth() - 5, window.getHeight() - 5);
// System.out.println( window.getBounds() );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("AnimationSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new AnimationSSCCE() );
frame.setSize(500, 400);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
もちろん、ウィンドウが特定の最小サイズに達したときにタイマーを停止する必要があります。そのコードはあなたに任せます。