首页 > 技术文章 > 画图3

zjc-66 2016-08-27 18:50 原文

添加面板容器将窗体分块:JPanel   北,南,东,西,中  5块

北:JPanel  northJP=new JPanel();

   northJP.setPreferredSize(new Dimension(0,50));

northJP.setBackground(Color.gray);

//添加图形按钮:

String[] shapArr = {"自定义图形","直线","矩形","圆"};
String[] iconName = {"my.jpg","line.jpg","rect.jpg","ellipse.jpg"};
for(int i=0; i<shapArr.length; i++){
//添加一个图形按钮到窗体上
ImageIcon icon = new ImageIcon(getClass().getResource("img/"+iconName[i]));
JButton shapButton = new JButton();
//设置按钮的动作命令
shapButton.setActionCommand(shapArr[i]);    ..........让action还能读取文字信息
shapButton.setIcon(icon);
shapButton.setPreferredSize(new Dimension(20,20));
shapButton.addActionListener(drawL);
//添加按钮到面板上
northJP.add(shapButton);        .............添加在北部板块
}

//添加颜色按钮:

Color[] Bcolor={Color.green,Color.red,Color.pink,Color.yellow,Color.black};

for(int j=0;j<Bcolor.length;j++){
JButton Colorbutton=new JButton();
Colorbutton.setPreferredSize(new Dimension(20,20));
Colorbutton.setBackground(Bcolor[j]);
Colorbutton.addActionListener(DrawL);
northJP.add(Colorbutton);
}

//创建下部用于画图板块:

JPanel centerJP=new JPanel();
centerJP.setBackground(Color.white);
centerJP.addMouseListener(DrawL);

//将两个板块添加到窗体:

frame.add(northJP,BorderLayout.NORTH);
frame.add(centerJP);

Graphics g=centerJP.getGraphics();...........绿色部分原来是窗体frame,因为要将图画在下面板块中

监听器中写出:(在ActionPerformed)中

if(action.equals""){

JButton ColorJB=(JButton)e.getSourse();............getSourse是Object格式,强制转换成JButton

Color Curcolor=ColorJB.getBackground();

g.setColor(Curcolor);

}

 

推荐阅读