Java sample(BarGraph & MouseDrag)


run

---(Source List)---

//Example16
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
public class Example16 extends JFrame implements MouseListener, MouseMotionListener{
  JTextField[] tf=new JTextField[2];
  static double x1=303,y1=198,x2=343,y2=198;
  static int sw=0;
  //Main
  public static void main(String ar[]){
    JFrame f=new Example16();
    f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    f.setSize(640,400);
    f.setVisible(true);
  }
  //Frame
  Example16(){
    super("BarGraph & MouseDragg");
    int i;
    Container c=getContentPane();
    JPanel p1=new JPanel();
    for(i=0;i<2;i++){
      tf[i]=new JTextField("100",3);
      p1.add(tf[i]);
    }
    c.add(p1,BorderLayout.NORTH);
    addMouseListener(this);
    addMouseMotionListener(this);
  }
  //Paint
  public void paint(Graphics g){
    String rs;
    double hei;
    int i;
    double r=2;
    Graphics2D g2=(Graphics2D) g;
    g.clearRect(0,0,639,399);
    for(i=0;i<2;i++){
      tf[i].repaint();
      rs = tf[i].getText();
      if (rs != null) {
        try {
          hei=Double.parseDouble(rs);
          g2.setPaint(Color.blue);
          g2.fill(new Rectangle2D.Double(300+i*40,300-hei,10,hei));
          g2.setPaint(Color.red);
          g2.fill(new Ellipse2D.Double(305+i*40-r,300-hei-r,2*r,2*r));
          if (i==0) y1=300-hei-r;
          if (i==1) y2=300-hei-r;
        } catch (NumberFormatException e) {}
      }
    }
  }
  public void mousePressed(MouseEvent me){
    double x,y;
    sw=0;
    x=me.getX();
    y=me.getY();
    if (Math.abs(x1-x)<3 && Math.abs(y1-y)<3){
      sw=1;
    }
    if (Math.abs(x2-x)<3 && Math.abs(y2-y)<3){
      sw=2;
    }
  }
  public void mouseDragged(MouseEvent me){
    int y;
    if (sw>0){
      y=me.getY();
      tf[sw-1].setText(""+(298-y));
      repaint();
    }
  }
  public void mouseReleased(MouseEvent me){}
  public void mouseMoved(MouseEvent me){}
  public void mouseEntered(MouseEvent me){}
  public void mouseExited(MouseEvent me){}
  public void mouseClicked(MouseEvent me){}
}