File "DrawPanel.java"
Full Path: /home/analogde/www/Ebook/Informatique/JAVA/Source_TLS/Move/DrawPanel.java
File size: 2.35 KB
MIME-type: text/x-c
Charset: utf-8
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawPanel extends JFrame
{
private DrawObjects panel = new DrawObjects();
private JPanel BPanel = new JPanel();
private JFrame window = new JFrame();
//constructor
DrawPanel(){
buildGUI();
}
void buildGUI(){
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(2,2));
window.add(panel);
window.add(BPanel);
BPanel.setBackground(Color.blue);
//define buttons and add to panel
JButton rect = new JButton("Rect");
JButton oval = new JButton("Oval");
BPanel.add(rect);
BPanel.add(oval);
rect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
panel.setType(1);
}
});
oval.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
panel.setType(2);
}
});
window.setVisible(true);
window.setSize(1024, 800);
}
public static void main(String[] args)
{
//create this object
new DrawPanel();
}
}//end class
class DrawObjects extends JPanel
{
public int x1,x2,y1,y2;
public int type = 1;//default draw type
public DrawObjects()
{
init();
}
public void init(){
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent m)
{
x1 = m.getX();
y1 = m.getY();
repaint();
}
public void mouseReleased(MouseEvent m)
{
x2 = m.getX();
y2 = m.getY();
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent m)
{
x2 = m.getX();
y2 = m.getY();
repaint();
}
});
}
public void setType(int arg){
if(arg == 1){
type = 1;
}else if(arg == 2){
type = 2;
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(type == 1)
{
g.drawRect(x1,y1,x2,y2);
}
else if (type == 2)
{
g.drawOval(x1,y1,x2,y2);
}
}
}