最近接触到Swing,想做一个画板,画版上有3个按钮,一个可以设置笔的粗细,一个可以获取颜色,一个点了以后使用橡皮....
第一次用最简单的想法,就是用JFrame做为画板,然后把三个按钮安置上去,这样确实成功了,但是只要用paint方法,第一次进入肯定看不到三个按钮,要把鼠标挪上去才出来,画出的图,会被按钮事件叫出的窗口给擦去,三个BUTTON也会被擦去
问了一下别人,说是JFrame的paint方法的问题.好,于是我把整个东西搬到一个JPanel上面,然后把JPanel放到JFrame里,结果还是差不多,而且更糟糕,每次使用按钮事件再绘画,按钮的图标就会重叠(也就是说又多出来三个按钮);
下面有我第二次,也就是用JPanel的代码,麻烦高手们给我指点指点,在这里先谢谢各位了.
另外就是,我对paint,repaint,update方法非常陌生,只能搬着用,有高手能给讲解一下吗?还有那个Graphics也是,搞不懂
============================
*这是用来安装JPanel的Frame*/
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.Toolkit;
public class CreateDrawPane extends JFrame
{
DrawPane pane;
public CreateDrawPane()
{
Container conPane = this.getContentPane();
pane = new DrawPane();
this.setTitle( "画板1.01 ");
this.setSize(500,500);
this.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width-
getSize().width)/2,
(Toolkit.getDefaultToolkit().getScreenSize().height-
getSize().height)/2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
conPane.setLayout(null);
conPane.add(pane);
this.setVisible(true);
}
public static void main(String[] args)
{
CreateDrawPane drawpane = new CreateDrawPane();
}
}
/*这是用来画图的JPanel*/
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import java.awt.Color;
import java.awt.Graphics;
public class DrawPane extends JPanel implements ActionListener
{
Color exchangeColor = Color.black;
private int x = -1;
private int y = -1;
private int penH = 2;
private boolean clearFlag = false;
JButton clearBtn;
JButton penBtn;
JButton colorBtn;
Graphics externG;
public DrawPane()
{
this.setLayout(null);
this.setBackground(Color.white);
this.setSize(500,500);
clearBtn = new JButton( "橡皮 ");
penBtn = new JButton( "粗细 ");
colorBtn = new JButton( "颜色调整 ");
clearBtn.setBounds(2,2,60,20);
clearBtn.setVisible(true);
penBtn.setBounds(63,2,60,20);
penBtn.setVisible(true);
colorBtn.setBounds(126,2,60,20);
colorBtn.setVisible(true);
clearBtn.addActionListener(this);
penBtn.addActionListener(this);
colorBtn.addActionListener(this);
this.add(clearBtn);