上半分に回転する四角形があり、下半分に四角形を停止/実行して回転させることができるボタンがある小さなスイングアプリケーションを開発しました。を使用しGridLayoutて、回転する正方形とボタンを配置しました。(別の方法として、2 つJPanelの s を使用することもできます。1 つは回転する正方形で、2 番目にはボタンが含まれます。このボタンを使用すると、適切なサイズで表示されます。)
ここにコードがあります:-
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Rotation {
JButton jbtn=new JButton("Stop");
component jpn2=new component();    //created a JPanel named jpn2 and got a reference to its timer object.
Timer timer=jpn2.timer;
Rotation()
{
    JFrame jfrm=new JFrame("Rotating a square about a center");
    jfrm.setSize(400,400);
    jfrm.setLayout(new GridLayout(2,1));
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //JPanel jpnl=new JPanel();
    //jpnl.add(jbtn);
    jbtn.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){
        if(e.getActionCommand().equals("Stop"))
        {
            timer.stop();
            jbtn.setText("Spin");
        }
        if(e.getActionCommand().equals("Spin"))
        {
            timer.start();
            jbtn.setText("Stop");
        }
    }});
    jfrm.add(jpn2);
    jfrm.add(jbtn);
    //jfrm.add(new JButton("Click"));
    jfrm.setVisible(true);
    //jfrm.setOpacity(0.8f);
}
public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
{
    //JFrame.setDefaultLookAndFeelDecorated(true);
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    SwingUtilities.invokeLater(new Runnable(){public void run(){new Rotation();}});
}
}
class component extends JPanel implements ActionListener
{
Timer timer;
int theta=0;
component()
{
    timer=new Timer(10,this);
    timer.start();
}
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D)g;
    g2.rotate(theta,100,100);
    g2.fillRect(50, 50, 100,100);
}
public void actionPerformed(ActionEvent e)
{
    //Changing a global variable and then drawing the rectangle again and hence indirectly the square rotates.
    theta=theta+10;
    if(theta==360)
        theta=0;
    repaint();
}
}
出力は次のとおりです。

しかし、私の混乱は、ボタンだけを取得し、回転する正方形を取得しないFlowLayout代わりに、使用することにしたときです。GridLayout私が読んだ限りでは、FlowLayoutコンポーネントを行に配置し、スペースが少ない場合は複数の行を使用します。現在私が解決できないこの小さな愚かな問題を誰かが解決できますか。

