我开发了一个小摆动应用程序,其中有一个正方形在上半部分旋转,下半部分有一个按钮可以停止/运行正方形旋转。 我已经使用GridLayout
来放置旋转的正方形和按钮。 (另一种替代方法是使用2个JPanel
S,一个是带有旋转方和第二包含此按钮显示适当大小的button.Using。)流动布局工作的困惑
下面是代码: -
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
将组件放在一行中,如果空间小于它使用多行。 任何人都可以解决这个我目前无法解决的小笨问题。
请学习Java命名约定并严格遵守 – kleopatra