我开发了一个小型摆动应用程序,其中上半部分有一个正方形旋转,下半部分有一个按钮可以停止/运行正方形旋转。我用GridLayout
来放置旋转方块和按钮。(另一种选择是使用 2 JPanel
s,一个是旋转正方形,第二个包含按钮。使用此按钮会显示适当的大小。)
这是代码:-
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
将组件放在一行中,如果空间小于它使用多行。谁能解决我目前无法解决的这个愚蠢的小问题。