我在使用paintComponent方法将String文本放入框架时遇到了问题。
看起来像是:
我不知道为什么它不想把String放在适当的位置,因为我甚至算过像素。
import java.awt.EventQueue;
import javax.swing.JFrame;
public class FrameMain {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new DrawFrame();
frame.setVisible(true);
}
});
}
public class DrawFrame extends JFrame {
public DrawFrame()
{
setTitle("Frame with a component containing String");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds (100, 100, 300, 300 );
DrawComponent draw = new DrawComponent();
add(draw);
}
public class DrawComponent extends JComponent {
public void paintComponent(Graphics g) {
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
final int WIDTH = 175;
final int HEIGHT = 200;
}
答案 0 :(得分:3)
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
//final int WIDTH = 175;
//final int HEIGHT = 200;
使用后永远不要定义变量。 WIDTH和HEIGHT是来自其他Swing类的变量,默认为0。
final int WIDTH = 175;
final int HEIGHT = 200;
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
编辑:
我希望String在给定框架大小的位置设置位置,而不是它的位置。
不要做自定义绘画。使用JLabel。
JLabel label = new JLabel("centered");
label.setHorizontalAlignment( JLabel.CENTER );
frame.add(label);
答案 1 :(得分:2)
问题是你有
final int WIDTH = 175;
final int HEIGHT = 200;
在 drawString(..., WIDTH, HEIGHT)
正在发生的事情是JComponent
还有一个HEIGHT
和WIDTH
,因此drawString
正在使用WIDTH
和HEIGHT
JComponet
而不是你声明的那些。
如果您想使用自己的,只需将放在 drawString
final int WIDTH = 175;
final int HEIGHT = 200;
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
<强>更新强>
要使文字居中,您需要使用FontMetrics
。见这里
public void paintComponent(Graphics g) {
super.paintComponent(g);
String message = "First string in component located in frame";
Font font = new Font("impact", Font.PLAIN, 14);
g.setFont(font);
FontMetrics fm = g.getFontMetrics(font);
int stringWidth = fm.stringWidth(message);
int height = fm.getAscent();
int x = getWidth()/2 - stringWidth/2;
int y = getHeight()/2 + height/2;
g.drawString(message, x, y);
}