计算机二级大题–实现窗口创建
package AWT二级代码;
import java.awt.Button;
import java.awt.Frame;
import java.awt.GridLayout;
public class ShowGrid extends Frame
{
public ShowGrid()
{
super("GridLayout example");
setLayout(new GridLayout(0,2));
add(new Button("Button 1"));
add(new Button("Button 2"));
add(new Button ("Button 3"));
add(new Button ("Button 4"));
add(new Button ("Button 5"));
add(new Button ("Button 6"));
setSize(240,240);
setVisible(true);
}
public static void main(String args[])
{
ShowGrid gl = new ShowGrid();
}
}
效果如下
创建按钮
package AWT二级代码;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
public class ShowFlow extends Frame
{
public ShowFlow()
{
super("FlowLayout example");
setSize(300,100);
setLayout(new FlowLayout());
add(new Button("Button 1"));
add(new Button("Button 2"));
add(new Button("Button 3"));
setVisible(true);
}
public static void main(String args[])
{
ShowFlow fl = new ShowFlow();
}
}
效果如下
创建一个平面
package AWT二级代码;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
public class ShowBorder extends Frame
{
public ShowBorder()
{
super("BorderLayout example");
setLayout(new BorderLayout());
add("East",new Button("东"));
add("South",new Button("南"));
add("West",new Button("西"));
add("North",new Button("北"));
add(new Button("中"));
setVisible(true);
setSize(300,300);
}
public static void main(String args[])
{
ShowBorder bl = new ShowBorder();
}
}
效果如下
在窗口写字
package 计算机二级考试;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class shige
{
public static void main(String[] args)
{
FontFrame frame = new FontFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class FontFrame extends JFrame
{
public FontFrame()
{
setTitle("沁园春.雪");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
FontPanel panel = new FontPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
class FontPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
String message = "数风流人物,还看今朝!";
Font f = new Font("隶书", Font.BOLD, 24);
g2.setFont(f);
FontRenderContext context = g2.getFontRenderContext();
Rectangle2D bounds = f.getStringBounds(message, context);
double x = (getWidth() - bounds.getWidth()) / 2;
double y = (getHeight() - bounds.getHeight()) / 2;
double ascent = -bounds.getY();
double baseY = y + ascent;
g2.setPaint(Color.RED);
g2.drawString(message, (int)x, (int)(baseY));
}
}
效果如下
|