同一个世界
请修改编辑器中的代码,完成一个图形界面程序,实现点击按钮切换背景色并绘制居中文本的功能,具体要求如下: 创建一个窗口,标题为“北京 2008”,大小为 400×250 窗口中包含三个按钮:“Yellow”、“Blue”、“Green” 点击任意按钮,将窗口背景颜色切换为对应颜色 在窗口中央绘制一行中文文本:“同一个世界,同一个梦想!” 使用字体“隶书”,加粗,字号为 27,文本颜色为红色 文本应始终居中显示,不随按钮变化而消失 所有绘图逻辑放在自定义的 JPanel 类中完成 运行后 弹出窗口,界面行为见代码注释;所有绘图逻辑写在自定义的 JPanel 子类中,文字始终居中显示。 说明:本题是图形界面程序,运行后会弹出窗口,控制台上不会有输出。评测按填入的代码文本判分,不比对运行结果。
import java.awt.event.*;
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class Main
{
public static void main(String[] args)
{
FontFrame frame = new FontFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class FontFrame extends ________________
{
public FontFrame()
{
setTitle("北京 2008");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
FontPanel panel = new FontPanel();
Container contentPane = getContentPane();
contentPane.add(_____________________);
}
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 250;
}
class FontPanel extends JPanel
{
public FontPanel()
{
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Green");
add(yellowButton);
add(blueButton);
add(redButton);
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction greenAction = new ColorAction(Color.GREEN);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(greenAction);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
String message = "同一个世界,同一个梦想!";
Font f = new Font("隶书", Font.BOLD, 27);
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));
}
private class ColorAction ____________________ ActionListener
{
public ColorAction(Color c)
{
BackgroundColor = c;
}
public void _____________________ (ActionEvent event)
{
setBackground(BackgroundColor);
}
private Color BackgroundColor;
}
}
控制台
调试终端
