在Java的GUI编程中,如何在新的框架(frame)中显示消息?
以下示例演示如何通过使用JFrame()
和使用JFrames getContentPanel()
,setSize()
和setVisible()
方法创建一个框架来显示此框架来显示消息。
package com.yiibai;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CreateFrame extends JPanel {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Serif", Font.PLAIN, 48));
paintHorizontallyCenteredText(g2, "Yiibai", 200, 75);
paintHorizontallyCenteredText(g2, "IT", 200, 125);
paintHorizontallyCenteredText(g2, "Yiibai", 200, 175);
}
protected void paintHorizontallyCenteredText(
Graphics2D g2, String s, float centerX, float baselineY) {
FontRenderContext frc = g2.getFontRenderContext();
Rectangle2D bounds = g2.getFont().getStringBounds(s, frc);
float width = (float) bounds.getWidth();
g2.drawString(s, centerX - width / 2, baselineY);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new CreateFrame());
f.setSize(450, 350);
f.setVisible(true);
}
}
上述代码示例将产生以下结果。
示例-2
以下是在新框架中显示消息的另一个示例。
package com.yiibai;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.TextArea;
public class CreateFrame2 {
public static void main(String[] args) {
Frame f = new Frame("标题");
Component text = new TextArea("One of Best IT Tutorails Website.\nYes/No");
Component button = new Button("一个按钮");
f.add(text, BorderLayout.NORTH);
f.add(button, BorderLayout.SOUTH);
int width = 300;
int height = 300;
f.setSize(width, height);
f.setVisible(true);
}
}
上述代码示例将产生以下结果。