画图(P267)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class drawgraph implements ActionListener{
JFrame frame = new JFrame("Drawing example");
MyButton button = new MyButton("Draw");
MyPanel panel= new MyPanel();
int tag = 1;
public static void main(String [] arg)
{
drawgraph de= new drawgraph();
de.go();
}
public void go()
{
button.addActionListener(this);
frame.getContentPane().add(button, "South");
frame.getContentPane().add(panel, "Center");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(360, 200);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(tag == 0)
{
tag = 1;
button.setText("Draw");
}
else
{
tag = 0;
button.setText("Clear");
}
panel.repaint();
}
class MyButton extends JButton
{
MyButton(String text)
{
super(text);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
int width = getWidth();
int height = getHeight();
g.drawOval(4, 4, width - 8, height - 8);
}
}
class MyPanel extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(tag == 0)
{
g.setColor(Color.BLUE);
g.drawLine(40, 25, 30, 50);
g.setColor(Color.green);
g.drawRect(100, 50, 100, 46);
}
}
}
}
Java之画图
最新推荐文章于 2025-09-29 21:35:12 发布
本文介绍了一个使用Java进行图形绘制的示例程序。通过自定义按钮和面板类,实现了图形的绘制与清除功能。程序中包含了按钮点击事件的监听与响应,以及图形界面的更新。适合初学者了解Java图形编程的基础。
487

被折叠的 条评论
为什么被折叠?



