JAVA入门系列四
窗体程序
在组件中显示信息
例:
import javax.swing.*;
import java.awt.*;
public class TXTDisplay {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
TXTDisplayFrame frame = new TXTDisplayFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class TXTDisplayFrame extends JFrame
{
public TXTDisplayFrame()
{
setTitle("窗口");
setSize(a,b);
TXTDisplayPanel panel = new TXTDisplayPanel();
add(panel);
}
public static final int a=200;
public static final int b=200;
}
class TXTDisplayPanel extends JPanel
{
public void paintComponent(Graphics g)
{
g.drawString("文本部分",start,end);
}
public static final int start = 75;
public static final int end = 100;
}
注:
1.paintComponent方法有一个Graphics类型的参数,这个参数保存着用于绘制图像和文本的设置;在Java中,所有的绘制都必须使用Graphics对象,其中包含了绘制图像和文本的方法。
2.container getContentPane() 返回这个JFrame的内容窗格对象。
3.Component add(Component c) 将一个给定的组件添加到该框架的内容窗格中。
2D图形
Graphics类包含绘制直线,椭圆和矩形等方法。要想使用Java 2D库绘制图形,需要获得Graphics 2D类对象;paintComponent方法会自动获得一个Graphics2D类对象,需要进行一次类型转换:
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
…
}
简单的绘制图形例子:
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DrawTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
public DrawFrame()
{
setTitle("DrawTest");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
DrawComponent component = new DrawComponent();
add(component);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
class DrawComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
double leftX=290;
double topY=190;
double width=280;
double height=180;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
g2.draw(new Line2D.Double(leftX, topY, width, height));
double centerX=rect.getCenterX();
double centerY=rect.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX,centerY,centerX+radius,centerY+radius);
}
}