import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class test extends JFrame
{
JFrame frm;
JButton but1,but2,but3;
JPanel panel,p,pan[];
static int j=0;
Container con;
public test()
{
JFrame.setDefaultLookAndFeelDecorated(true);
frm=new JFrame();
con=frm.getContentPane();
//放置按钮
panel=new JPanel();
but1=new JButton( "三角形 ");
but2=new JButton( "矩形 ");
but3=new JButton( "椭圆形 ");
button bt=new button();
but1.addActionListener(bt);
but2.addActionListener(bt);
but3.addActionListener(bt);
panel.add(but1);
panel.add(but2);
panel.add(but3);
con.add(panel,BorderLayout.NORTH);
//放置窗口下方的面板
p=new JPanel();
p.setLayout(new GridLayout(3,3,1,1));
//在窗口下方的面板上放置9个小面板
pan=new JPanel[9];
for(int i=0;i <9;i++)
{
pan[i]=new JPanel();
pan[i].setLayout(new GridLayout(1,1));
p.add(pan[i]);
}
con.add(p,BorderLayout.CENTER);
frm.setTitle( "绘制图形 ");
frm.setSize(500,400);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setResizable(false);
frm.show();
}
class button implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(j <9){
if(e.getSource()==but1)
{
pan[j].add(new Triangle());
frm.validate(); //刷新窗口,否则图形无法显示
}
else if(e.getSource()==but2)
{
pan[j].add(new rect());
frm.validate();
}
else if (but3==e.getSource())
{
pan[j].add(new Ellipse());
frm.validate();
}
j++;
}
}
}
public static void main(String age[])
{
new test();
}
}
//三个图形类定义在外部
class Triangle extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.cyan);
int a=this.getSize().width;
int b=this.getSize().height;
int xpoints[]={a/2,0,a};
int ypoints[]={0,b,b};
g.fillPolygon(xpoints,ypoints,3);
}
}
class rect extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
// a=pan[j].getSize().width;
// b=pan[j].getSize().height;
// g.fillRect(a-10,b-10,a-60,a-30);
g.fillRect(0,0,this.getSize().width,this.getSize().height);
}
}
class Ellipse extends JPanel
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.blue);
g.fillOval(0,0,this.getSize().width,this.getSize().height);
}
}
________________________________________
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class test extends JFrame
{
JFrame frm;
JButton but1,but2,but3;
JPanel panel,p,pan[];