【发布时间】:2014-05-23 11:06:00
【问题描述】:
这是我当前的代码:
package Calendar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Clock extends JLabel {
private String pattern;
private Timer timer;
public Clock(String pattern){
this.pattern = pattern;
createTimer();
timer.start();
}
public Clock(){
pattern = "hh:mm:ss a";
createTimer();
timer.start();
}
private void createTimer(){
timer = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setText(new SimpleDateFormat(pattern).format(new Date()));
}
});
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
frame.setContentPane(contentPane);
Clock digitalClock = new Clock();
contentPane.add(digitalClock);
frame.setVisible(true);
}
}
我终其一生都无法弄清楚如何旋转它。我查看了其他几个论坛,但没有其他人与此问题有关。
据我所知,没有办法旋转 JPanel 或 JFrame,所以我不走运吗?
这就是现在的样子:
我想得到它,使文本旋转 90 度。基本上是垂直的。
编辑:解决方案:
package Calendar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JLabel;
import javax.swing.Timer;
import java.awt.*;
import java.awt.geom.*;
public class Clock extends JLabel {
private String pattern;
private Timer timer;
public Clock ()
{
super();
pattern = "hh:mm:ss a";
createTimer();
timer.start();
}
public Clock(String pattern)
{
super (pattern);
this.pattern = pattern;
createTimer();
timer.start();
}
private void createTimer(){
timer = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setText(new SimpleDateFormat(pattern).format(new Date()));
}
});
}
public void paint (Graphics g)
{
if (g instanceof Graphics2D) {
Graphics2D g2 = (Graphics2D) g;
AffineTransform flipTrans = new AffineTransform();
double widthD = (double) getWidth();
flipTrans.setToRotation(-Math.PI / 2.0, getWidth() / 2.0, getHeight() / 2.0);
g2.setTransform(flipTrans);
super.paint(g);
} else {
super.paint(g);
}
}
}
【问题讨论】:
-
这只是一个简单的数字时钟,在 JPanel 的 JFrame 中显示时间。现在文本是水平的,我想将它旋转 90 度。
-
@DavidWallace 鉴于示例代码,我会说that this 更像是重复...只是说;)
-
很抱歉这是重复的。没有意识到这会被标记为旋转摆动文本
标签: java rotation jframe jpanel