旋转UI构件的思路就是画图,大家都知道,UI构件是用java2D画出来的,那么只要我们旋转绘制它们的Graphics2D类,就可以达到旋转构件的目的.
有时候我们想在一个有画图的JPanel里加入控件,也会出现一些问题,这个程序也可以解决它.下面给出一个旋转JButton的程序,这个程序并不是很模块化,只是为了给大家提供一点思路,不过我觉得旋转面板也没有多少用,只是好玩罢了.如果你对java2D不是很了解的,这个程序或许可以给你一点点启发吧.当然,java2D范围很广,这儿用到的只是很小很小的一部分.
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.*;
import javax.swing.*;
public class PaintButton extends JPanel implements MouseMotionListener,Runnable,MouseListener{
/**
* @author hoverlees(好棒)
*/
JButton jb=new JButton("一个按钮");
Area area=new Area(new Rectangle2D.Float(0F,0F,100F,80F));
double theta=2.1;//度数,这里应为弧度表示
AffineTransform at;
int start=0;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFrame jf=new JFrame();
jf.setSize(400,400);
jf.setDefaultCloseOperation(3);
jf.setContentPane(new PaintButton());
jf.setVisible(true);
}
public PaintButton(){
jb.setBounds(area.getBounds()); //设置区域
this.addMouseMotionListener(this);
this.addMouseListener(this);
/new Thread(this).start();
at=AffineTransform.getRotateInstance(theta,100,100);//取得旋转实例
area.transform(at);
}
public void paintComponent(Graphics g){
Graphics2D g2=(Graphics2D) g;
//下面一句只是画点其它的东西而已,这儿画的是一个渐变
g2.setPaint(new GradientPaint(new Point2D.Float((float)start,
(float)this.getHeight()/2),Color.black,
new Point2D.Float((float)this.getWidth(),
(float)this.getHeight()/2),Color.white));
g2.fillRect(0, 0, this.getWidth(), this.getHeight());
at.setToRotation(theta, 100D, 100D);
g2.setTransform(at);
jb.paint(g); //在这个面板里画按钮
}
public void mouseDragged(MouseEvent arg0) {
}
public void mouseMoved(MouseEvent e) {
if(area.contains(e.getX(),e.getY()) && !jb.getModel().isRollover()){
jb.getModel().setRollover(true);
}
else if(!area.contains(e.getX(),e.getY())) jb.getModel().setRollover(false);
repaint();
}
public void run() {
while(true){
theta+=0.1D;
start-=10;
if(start<-2000) start=0;
area.transform(at);
repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void mouseClicked(MouseEvent e) {
doAction(e.getX(),e.getY());
}
private void doAction(int x,int y){ //其实这个方法就是执行按钮按下时.
if(area.contains(x,y))
JOptionPane.showMessageDialog(new JFrame(), "按下去了!");
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent e) {
if(area.contains(e.getX(),e.getY())){
jb.getModel().setSelected(true);
repaint();
}
else{
}
}
public void mouseReleased(MouseEvent e) {
if(area.contains(e.getX(),e.getY())){
jb.getModel().setSelected(false);
repaint();
}
}
}