Java之画图

	画图(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);
					
					
				}
			}
		}
	
		
	}

猜你喜欢

转载自blog.csdn.net/a1_s2_c3_/article/details/85218045