我正在用 Java 制作一个应该显示旋转文本的程序。但是,我在正确可视化文本时遇到问题。
我制作的一个小测试程序在下一个清单中给出。当按下按钮时,该测试程序应旋转一行文本(以及围绕该行的一个矩形)几次。这就是这个程序所做的,但在大多数情况下,旋转的文本不适合旋转的矩形!
我曾尝试旋转字体等,但失败了。
任何人都可以检查提供的代码并解释这种行为吗?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
public class RotatedTextDrawing implements ActionListener {
private JFrame m_frame;
private JPanel m_graphvisualizationpanel;
private JScrollPane m_javascrollpane;
public void start() {
m_frame = new JFrame();
m_frame.setSize(1200,800);
m_frame.setPreferredSize(new Dimension(1200,800));
m_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
m_frame.setLayout(new FlowLayout());
m_graphvisualizationpanel = new JPanel();
m_graphvisualizationpanel.setSize(3000,3000);
m_graphvisualizationpanel.setPreferredSize(new Dimension(3000,3000));
m_graphvisualizationpanel.setBackground(new Color(255, 255, 255));
m_javascrollpane = new JScrollPane(m_graphvisualizationpanel);
m_javascrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
m_javascrollpane.setPreferredSize(new Dimension(1000, 700));
JButton jb = new JButton("GO");
jb.addActionListener(this);
m_frame.add(jb);
m_frame.add(m_javascrollpane);
m_frame.pack();
m_frame.setVisible(true);
}
public static void main(String args[]) {
RotatedTextDrawing rtd = new RotatedTextDrawing();
rtd.start();
}
public void actionPerformed(ActionEvent e) {
Graphics2D g2d = (Graphics2D) m_graphvisualizationpanel.getGraphics();
AffineTransform oldt = g2d.getTransform();
//Font theFont = g2d.getFont();
g2d.setColor(new Color(0,0,0));
int m_x = 150;
int m_y = 150;
double m_alpha = 10;
String mstring = "STRING VERY LONG STRING VERY VERY LONG";
int m_width = g2d.getFontMetrics().stringWidth(mstring);
int m_height = g2d.getFontMetrics().getHeight();
int centerx = m_x + m_width/2;
int centery = m_y - m_height/2;
g2d.drawRect(m_x,m_y-m_height,m_width,m_height);
g2d.drawRect(centerx,centery,m_width/2,m_height/2);
g2d.drawString(mstring, m_x,m_y);
g2d.setColor(new Color(100,100,100));
for (int br=1; br < 8; br++) {
AffineTransform newt = new AffineTransform();
newt.setToRotation(Math.toRadians(br * m_alpha), centerx,centery);
g2d.transform(newt);
//Font theDerivedFont = theFont.deriveFont(newt);
//g2d.setFont(theDerivedFont);
g2d.drawRect((int)m_x,(int)(m_y-m_height),m_width,m_height);
g2d.drawString(mstring, (int)m_x, (int)m_y);
g2d.setTransform(oldt);
}
//g2d.setFont(theFont);
}
}