Παρασκευή 14 Φεβρουαρίου 2020

Point JTextField Java


This is an old and 'private' version so you cant easy understand 

See newer,simplest and standalone version 


---------------------------------------------------------------------------



Αντι να εχω 2 JTextField s

για να κουναω ενα Point με
το πληκτρολογιο,,,,

εχω 1 με ποντικι (και πληκτρα) !
------------------------








/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package jim.lib.j;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Point2D;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import jim.Jim;
import jim.lib.a.Dmtn;
import jim.lib.a.Thr;
import jim.lib.d.Path;
import jim.lib.d.Point;
import jim.lib.j.swing.Jfr;
import jim.lib.j.swing.Jspl;
import jim.lib.j.swing.Jtf;
import jim.lib.j.swing.Manager;
import jim.lib.p.PaintNode;

/**
 * created at 14 Φεβ 2020
 * @author jimakoskx
 */
public class JArrows4Tf extends Jtf{
   
    public static void main(String[] args) {
        JArrows4Tf test1=new JArrows4Tf(1,2);
        JArrows4Tf test2=new JArrows4Tf(1.0,3.0,-10,10,1);
        test1.isReversingPaintMode=false;
        test2.isReversingPaintMode=true;
        test1.setName("test1");
        test2.setName("test2");
        test1.cutTextToLong=true;


       
        Jfr jfr=new Jfr(new Jspl(1,test1,test2).q(0.5).qCont());
        jfr.setBounds(0,0,888,222);
    }
   
    static ComponentListener CML=new ComponentListener() {
        @Override
        public void componentResized(ComponentEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.resizedArrows4Tf();}
        }
        @Override
        public void componentMoved(ComponentEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.movedArrows4Tf();}
        }

        @Override
        public void componentShown(ComponentEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.shownArrows4Tf();}
        }

        @Override
        public void componentHidden(ComponentEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.hiddenArrows4Tf();}
        }
    };
    static MouseMotionListener MML=new MouseMotionListener() {
        @Override
        public void mouseDragged(MouseEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.draggedArrows4Tf(e);}
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.movedArrows4Tf(e);}
        }
    };
    static MouseListener ML=new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.clickedArrows4Tf(e);}
        }
        @Override
        public void mousePressed(MouseEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.pressedArrows4Tf(e);}
        }
        @Override
        public void mouseReleased(MouseEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.releasedArrows4Tf(e);}
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.enteredArrows4Tf(e); }
        }
        @Override
        public void mouseExited(MouseEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.exitedArrows4Tf(e);}
        }
    };

    static KeyListener KL=new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {}
        @Override
        public void keyPressed(KeyEvent e) {//System.out.println("shifter");
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.klcheckingOneByShift(e);}
        }
        @Override
        public void keyReleased(KeyEvent e) {
            JArrows4Tf src=(JArrows4Tf)e.getComponent();
            if(src!=null){src.klcheckingOneByShift(e);}
        }
    };
    static KeyListener KLparser=new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {}
        @Override
        public void keyPressed(KeyEvent e) {//System.out.println("parser");
            if(e.getKeyCode()==KeyEvent.VK_ENTER){
                JArrows4Tf src=(JArrows4Tf)e.getComponent();
                if(src!=null){src.parseText();}
            }
        }
        @Override
        public void keyReleased(KeyEvent e) {}
    };
   
    /**
     * need low Alpha for the text of JTextField to be visible
     */
    static Color arrowsColorDefault=new Color(143,44,0,90);
   
   
    //System.out.println("l"+SwingConstants.LEFT);
    //System.out.println("r"+SwingConstants.RIGHT);
    //System.out.println("b"+SwingConstants.BOTTOM);
    //System.out.println("t"+SwingConstants.TOP);   
    static final int swUp1=1;
    static final int swLeft2=2;
    static final int swDown3=3;
    static final int swRight4=4;
    static final String swStr[]=new String[]{"Center","Up","Left","Down","Right"};
   
    static long sleepBetweenPointIncDecrCalls=50;//20 frames per second
    static Thr unicMouseTimeMover=new Thr(){
        @Override
        public void doWork() {
            JArrows4Tf src=(JArrows4Tf)workOn.getUserObject();
            //System.out.println("working on "+src.getName());
            while(src.draggedDir4>0){
                //System.out.println("calling for "+swStr[src.draggedDir4]);
                src.applyAgainCurrDirectionToPoint();
                sl(sleepBetweenPointIncDecrCalls);
            }
        }
    }.q("JArrows4Tf.unicMouseTimeMover");
   
    static{
        unicMouseTimeMover.start();
    }   
    ///////////////////////////////////////////////////////////////
    ///////  C L A S S       H E R E   ////////////////////////////
    ///////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////
   

    Point val=new Point(0,0);
    Point stepAbs=new Point(1,1);
    Point min=new Point(Jim.minlong,Jim.minlong);
    Point max=new Point(Jim.maxlong,Jim.maxlong);
    Point temp=new Point(0,0);
   
   
    Path pLeft=new Path();
    PaintNode pnLeft=new PaintNode(pLeft).qfill();
    Path pRight=new Path();
    PaintNode pnRight=new PaintNode(pRight).qfill();
    Path pUp=new Path();
    PaintNode pnUp=new PaintNode(pUp).qfill();
    Path pDown=new Path();
    PaintNode pnDown=new PaintNode(pDown).qfill();
    /**
     * if even w > h may need to draw arrows vertically (or opposite)...may dummy never be used
     */
    boolean isReversingPaintMode=false;
    /**
     * width , w/2 , w/3 , 2*(w/3)
     */
    int w,wd2,wd3,wd32;
    /**
     * height , h/2 , h/3 , 2*(h/3)
     */
    int h,hd2,hd3,hd32;
   
   
    /**
     * if(false) then arrows not showing if mouse is out of JTextField
     */
    boolean arrowsAlwaysOn=true;
    /**
     *  Up0,Left1,Down2,Right3 Point move modes
     */
    /**
     * updated direction on dragging (before releasing mouse button)
     */
    int draggedDir4=-1;
    /**
     * Triggering starts when user press mouse on JTextfield<br>
     * MouseMotionListener and KeyListener will be added
     * Buffer of the static Thread will be filled with a reference to this Object<br>
     */
    int pressedDir4=-1;
    /**
     * According of the mouse button for slow,normal,quick speed of the Point movement
     */
    int multiplier=1;
    /**
     * If user suddenly while moving the Point press shift then we must slow speed<br>
     * to be easy to adjust at exact point
     */
    boolean isShiftDown=false;
    /**
     * One instead of STEP....cancelling step that is usually adjusted with multiplier !
     */
    int one=1;
   
   
    Dmtn buttons=new Dmtn();//MultipliersPerButtons ..binary search just for 1,2,3 values? Answer:...Just easy programming

    /**
     *
     */
    public JArrows4Tf (){
        super("OLA KALA EDO ");
        //setCursor(Cursor.getDefaultCursor());//no text cursor
        setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));//


        painter=new PaintNode();
        painter.q(arrowsColorDefault);
        painter.add(pnDown);
        painter.add(pnLeft);
        painter.add(pnRight);
        painter.add(pnUp);
       
       
        buttons.abin(MouseEvent.BUTTON1).crad(1);
        //buttons.abin(MouseEvent.BUTTON2).crad(1);
        buttons.abin(MouseEvent.BUTTON3).crad(3);
       
       
        addComponentListener(CML);
        addKeyListener(KLparser);
        addMouseListener(ML);
        refreshText();
    }
   
    public JArrows4Tf (double x,double y){
        this();
        val.x=x;
        val.y=y;
        refreshText();
    }
    public JArrows4Tf (double x,double y,double minv,double maxv,double stepv){
        this();
        if( stepv<=0 || (minv>=maxv) || x<minv || y<minv || x>maxv || y>maxv || (maxv-minv<stepv) ){
            throw new IllegalArgumentException("JArrows4Tf NOT if( step<=0 || (min>=max) || x<min || y<min || x>max || y>max || (max-min<step) )");
        }     
        val.x=x;
        val.y=y;
       
        min.x=minv;
        min.y=minv;
       
        max.x=maxv;
        max.y=maxv;
       
        stepAbs.x=stepv;
        stepAbs.y=stepv;
       
        refreshText();
    }
   
   
   
   
   
    /**
     * Override to notify for the new Point
     */
    public void xyChanged(){
        //System.out.println("must implement by class programmer user");
    }
    /**
     * Check limits and if ok sets and calls valuesChanged()
     * @param x
     * @param y
     * @return
     */
    public boolean setxy(double x,double y){
        if( x<min.x || x>max.x || y<min.y || y>max.y  ){
            return false;
        }
        else{
            val.x=x;
            val.y=y;
            xyChanged();
            refreshText();
            return true;
        }
    }
    public void setxyNoCheck(double x,double y){
        val.x=x;
        val.y=y;
        xyChanged();
        refreshText();
    }
    public void setxNoCheck(double x){
        val.x=x;
        xyChanged();
        refreshText();
    }
    public void setyNoCheck(double y){
        val.y=y;
        xyChanged();
        refreshText();
    }

    public boolean checkxy(double x,double y){
        return !( x<min.x || x>max.x || y<min.y || y>max.y );
    }
    public boolean checkx(double x){
        return !( x<min.x || x>max.x);
    }
    public boolean checky(double y){
        return !( y<min.y || y>max.y );
    }

   
   
    public int xi(){return (int)val.x;}
    public int yi(){return (int)val.y;}
    public long xl(){return (long)val.x;}
    public long yl(){return (long)val.y;}
    public double x(){return val.x;}
    public double y(){return val.y;}
   
    public void getxy(Point2D p){
        p.setLocation(val.x,val.y);
    }
    synchronized void parseText(){
        String text=getText();
        Point p=new Point();
        Exception e=jim.lib.d.Point.parsePoint(text, p);
        if(e!=null){
            JOptionPane.showMessageDialog(this, e,"Unable to parse Point from Text",JOptionPane.INFORMATION_MESSAGE);
        }
        else{
            if(setxy(p.x,p.y)){
                //System.out.println("good");
            }
            else{
                JOptionPane.showMessageDialog(this, "attempted to set \n("+p.x+","+p.y+")\nNot allowed because of\nlimitations\n"+getLimitsText(),"Values out of limits",JOptionPane.INFORMATION_MESSAGE);
                refreshText();
            }
        }
    }
    public String getLimitsText(){
        return min.x+" <= x <= "+max.x+" \n"+min.y+" <= y <= "+max.y+" \n";
    }
   
    public void setArrowsPainting(boolean active){
        painter.childrenOn=active;
        repaint();
    }
    public boolean getArrowsPainting(){
        return painter.childrenOn;
    }
    public void setArrowsColor(Color c){
        painter.q(c);
        repaint();
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if(enabled){addMouseListener(ML);}
        else{removeMouseListener(ML);}
    }
   
   
   
   
    boolean isArrowsHorizontal(){
        if(w>=h){
            if(isReversingPaintMode){return false;}
            else{return true;}
        }
        else{
            if(isReversingPaintMode){return true;}
            else{return false;}
        }
    }
    void resizedArrows4Tf(){
        w=getWidth();
        h=getHeight();
        pDown.reset();
        pLeft.reset();
        pRight.reset();
        pUp.reset();
       
       
        wd2=w/2;
        hd2=h/2;
        wd3=w/3;
        wd32=wd3*2;
        hd3=h/3;
        hd32=hd3*2;

        if(w>=h){
            if(isReversingPaintMode){resetingPaintModeVertical();}
            else{resetingPaintModeHorizontal();}
        }
        else{
            if(isReversingPaintMode){resetingPaintModeHorizontal();}
            else{resetingPaintModeVertical();}
        }
    }
    void movedArrows4Tf(){}
    void shownArrows4Tf(){}
    void hiddenArrows4Tf(){}
   
    void resetingPaintModeHorizontal(){
        pDown.moveTo(wd2, h);
        pDown.lineTo(wd3, hd2);
        pDown.lineTo(wd32,hd2);
        pDown.closePath();

        pUp.moveTo(wd2, 0);
        pUp.lineTo(wd32, hd2-1);
        pUp.lineTo(wd3,hd2-1);
        pUp.closePath();

        pLeft.moveTo(0, hd2);
        pLeft.lineTo(wd3, h);
        pLeft.lineTo(wd3,0);
        pLeft.closePath();

        pRight.moveTo(w, hd2);
        pRight.lineTo(wd32, 0);
        pRight.lineTo(wd32,h);
        pRight.closePath();       
    }
    void resetingPaintModeVertical(){
        pDown.moveTo(wd2, h);
        pDown.lineTo(w, hd32);
        pDown.lineTo(0,hd32);
        pDown.closePath();

        pUp.moveTo(wd2, 0);
        pUp.lineTo(0, hd3);
        pUp.lineTo(w,hd3);
        pUp.closePath();

        pLeft.moveTo(0, hd2);
        pLeft.lineTo(wd2-1,hd32);
        pLeft.lineTo(wd2-1,hd3);
        pLeft.closePath();

        pRight.moveTo(w, hd2);
        pRight.lineTo(wd2, hd3);
        pRight.lineTo(wd2,hd32);
        pRight.closePath();       
    }
   
   
   
   
   
   
         
    int getDir4(int ex,int ey){
        if(isArrowsHorizontal()){//System.out.println("Arrows are horizontal");
            if(ex>wd32){//System.out.println("Right");
                return swRight4;
            }
            else if(ex<wd3){//System.out.println("Left");
                return swLeft2;
            }
            else{
                if(ey<hd2){//System.out.println("Up");
                    return swUp1;
                }
                else{//System.out.println("Down");
                    return swDown3;
                }
            }
        }
        else{//System.out.println("Arrows are vertical");
            if(ey>hd32){//System.out.println("Down");
                return swDown3;
            }
            else if(ey<hd3){//System.out.println("Up");
                return swUp1;
            }
            else{
                if(ex<wd2){//System.out.println("Left");
                    return swLeft2;
                }
                else{//System.out.println("Right");
                    return swRight4;
                }
            }
        }
    }
    void clickedArrows4Tf(MouseEvent e){}
    void pressedArrows4Tf(MouseEvent e){
       
        int but=e.getButton();
        Dmtn buttonNode=buttons.abn(but);
        if(buttonNode!=null){
            multiplier=buttonNode.dmtn(0).i();
           
            int ex=e.getX();
            int ey=e.getY();
            pressedDir4=getDir4(ex, ey);
            draggedDir4=pressedDir4;


            isShiftDown=e.isShiftDown();///means NO MULTIPLIER AT ALL ..ONE
            //System.out.println("Pressed "+swStr[pressedDir4]+" mult="+multiplier);

            unicMouseTimeMover.works.crad(this);
            unicMouseTimeMover.interrupt();
            addKeyListener(KL);
            addMouseMotionListener(MML);
        }
        //else{System.out.println("This button is not installed");}
   
    }
    void releasedArrows4Tf(MouseEvent e){
        draggedDir4=0;
        removeMouseMotionListener(MML);
        removeKeyListener(KL);
    }
    void enteredArrows4Tf(MouseEvent e){
        if(!arrowsAlwaysOn){setArrowsPainting(true);}
    }
    void exitedArrows4Tf(MouseEvent e){
        if(!arrowsAlwaysOn){setArrowsPainting(false);}
    }
    void draggedArrows4Tf(MouseEvent e){
       
        isShiftDown=e.isShiftDown();///means NO MULTIPLIER AT ALL ..ONE
       
        int refresh=getDir4(e.getX(), e.getY());
        if(refresh!=draggedDir4){
            draggedDir4=refresh;
            //System.out.println("Dir changed to "+swStr[draggedDir4]);
        }
       
    }
   
    void movedArrows4Tf(MouseEvent e){}
   
   
   
         


    void valuesChanged0(){
        refreshText();
        xyChanged();
    }
    boolean cutTextToLong=false;
    public String getPointText(){
        if(cutTextToLong){return (long)val.x+","+(long)val.y;}
        else{return val.x+","+val.y;}
    }
    void refreshText(){
        setText(getPointText());           
    }


    void klcheckingOneByShift(KeyEvent e) {
        isShiftDown=e.isShiftDown();
    }

   

    void beep(){
        Manager.beep();
    }

    void applyAgainCurrDirectionToPoint(){
        //System.out.println("Going "+swStr[draggedDir4]);
        if(draggedDir4==swDown3){
            temp.y=val.y;
            if(isShiftDown){temp.y+=one;}
            else{temp.y+=stepAbs.y*multiplier;}
            if(temp.y>max.y){beep();}
            else{setyNoCheck(temp.y);}
        }
        else if(draggedDir4==swLeft2){
            temp.x=val.x;
            if(isShiftDown){temp.x-=one;}
            else{temp.x-=stepAbs.x*multiplier;}
            if(temp.x<min.x){beep();}
            else{setxNoCheck(temp.x);}
        }
        else if(draggedDir4==swRight4){
            temp.x=val.x;
            if(isShiftDown){temp.x+=one;}
            else{temp.x+=stepAbs.x*multiplier;}
            if(temp.x>max.x){beep();}
            else{setxNoCheck(temp.x);}
        }
        else if(draggedDir4==swUp1){
            temp.y=val.y;
            if(isShiftDown){temp.y-=one;}
            else{temp.y-=stepAbs.y*multiplier;}
            if(temp.y<min.y){beep();}
            else{setyNoCheck(temp.y);}           
        }
        //else{System.out.println("error 0...expecting 1,2,3,4");}
    }   
   
   
   
   
   
}

Τρίτη 15 Οκτωβρίου 2019

Java PreOrder Backward Enumeration Iterator

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>


/*First class on university...6/10 !!!*/
package dim.ds;

import dim.ext.javax.swing.tree.Dmtn;//DefaultMutableTreeNode
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

/**
NOT return ROOT !

 * A Backward Pre Order Enumeration

 * <br>7, 6, 999, 99, some, 3, 2, 1
 * <br> will be given by the following tree
 * <br>0=root
 * <br>--0.1=1
 * <br>--0.2=2
 * <br>--0.3=3
 * <br>--------0.3.0=some
 * <br>----------------0.3.0.0=99
 * <br>----------------0.3.0.1=999
 * <br>--------0.3.1=6
 * <br>--0.4=7
 * @author jimidimi
 */
public class PreBackOrder implements Enumeration<Dmtn>,Iterator<Dmtn>{
    public static void main(String[] args) {
        Dmtn t=new Dmtn("root");
        //7,6,1,2,5,3,2,1
        t.crad(1);
        t.crad(2);
        Dmtn d3=t.crad(3);
            Dmtn d5=d3.crad(5);
                d5.crad(2);
                d5.crad(1);
            Dmtn d6=d3.crad(6);
        t.crad(7);
     
        PreBackOrder pbo=new PreBackOrder(t);
        while(pbo.hasMoreElements()){
            Object o=pbo.nextElement();
            System.out.println(pbo.counter+" : "+o+"  depth = "+pbo.depth);
        }
     
        System.out.println(" -------------- second example ----------- ");
        t.removeAllChildren();
     
        //
        //4,0,450,3,2,1,21
        t.sbad(21).sbad(1);
        t.sbad(21).sbad(2);
        t.sbad(21).sbad(3);
        t.sbad(450).sbad(0);
        t.sbad(450).sbad(4);

     
        pbo.clear();
        while(pbo.hasMoreElements()){
            Object o=pbo.nextElement();
            System.out.println(pbo.counter+" : "+o+"  depth = "+pbo.depth);
        }
     
     
     
    }
 
 
 
 
 
    public Dmtn root,par,it;
 
    /**
     * The current index path
     */
    public Vector<Integer> indexPathStack=new Vector<>();
    /**
     * The current last index of Vector
     */
    public int stackIndex=-1;
    /**
     * The current last Value of Vector
     */
    public int itIndexOnPar;
 
    /**
     * Simple enumeration step counter
     */
    public int counter=-1;
 
 
    /**
     * The previus (from call) stack.size()=stackIndex+1
     */
    int depth=0;

    /**
     *
     * @param theRoot to iterate without ... theRoot !
     * <br>To iterate also to Root use
     * <br>1.Or some level up root
     * <br>2.Or Dmtn temp=new Dmtn("temp");
     * <br>  temp.add(my_root);
     * <br>  new PreBackOrder(temp).iterate.....
     *
     */
    public PreBackOrder(Dmtn theRoot){
        root=theRoot;
        clear();
    }
    /**
     * When called must be synchronized(lock) ????
     */
    public void clear(){
        it=root;
        indexPathStack.clear();
        stackIndex=-1;
        int chc=it.getChildCount();
        itIndexOnPar=chc;
        while(chc>0){
            chc--;
            indexPathStack.add(chc);
            itIndexOnPar=chc;
            ++stackIndex;
            it=it.dmtn(chc);
            chc=it.getChildCount();
        }
        par=it.pardmtn();
        counter=-1;
        depth=stackIndex+1;
    }
 


    @Override
    public boolean hasNext() {
        return it!=null;
    }
    @Override
    public Dmtn next() {
        return nextElement();
    }
 
    /**
     *
     * @return it!=null;
     */
    @Override
    public boolean hasMoreElements() {
        return it!=null;
    }
    /**
     * rolls on the iteration to next stage
     * @return
     */
    @Override
    public Dmtn nextElement() {
        ++counter;//info
        depth=stackIndex+1;//info
        ///////////////////////////////////////
        Dmtn out=it;
        //this missing TAB INSET is missing but class not return ROOT ????!!!???
            --itIndexOnPar;
            //System.out.println("lastchc : "+lastChc);
            indexPathStack.setElementAt(itIndexOnPar, stackIndex);
            //System.out.println(""+itIndex);
            if(itIndexOnPar>=0){
                //System.out.println("Taking brother");
                it=par.dmtn(itIndexOnPar);
                int chc=it.getChildCount();
                while(chc>0){
                    chc--;
                    indexPathStack.add(chc);
                    itIndexOnPar=chc;
                    ++stackIndex;
                    it=it.dmtn(chc);
                    chc=it.getChildCount();
                }
                par=it.pardmtn();
            }
            else{
                //System.out.println("Finished iterate on "+par+" children");
             
                indexPathStack.remove(stackIndex);
                --stackIndex;

                if(stackIndex<0){
                    it=null;
                }
                else{
                    it=par;
                    par=it.pardmtn();
                    itIndexOnPar=indexPathStack.get(stackIndex);
                }
             
            }
        return out;
    }


 
 
 
 
 
 
}

Java Scan-Sarosi- Util Class

Java Scan-Sarosi- Util Class

package dim.games.streetracing;

import dim.ext.java.awt.Erect;

//erase also SarosiBuild class......
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JSplitPane;
import javax.swing.SpinnerNumberModel;







/**
 *
 * @author jimidimi
 */
public class Sarosi extends Erect{//Rectangle
   
    public static void main(String[] args) {
        SarosiBuild.testBuild();
    }


    /**
     * current iterator indexes setted before scan() being called
     */
    public int xScan,yScan;
   
    public int xLimit,yLimit;
    public int xDif=1,yDif=1;
    public int xOneOnly=0,yOneOnly=0;//when some dif=0
    public boolean xInnerWhile=true;
    public Sarosi(int x, int y, int width, int height) {
        super(x, y, width, height);
    }
   
   
   
   
    //OVERRIDE
    public void scan(){}
    public void scanAllFinished(){}
    public void scanAllStarting(){}
   
   


   
    //CLEARing mind

   
    public void scanAll(){
        scanAllStarting();
        if(xDif<0){
            if(yDif<0){//-1x,-1y
                if(xInnerWhile){
                    yScan=y+height-1;
                    yLimit=y-1;
                    xLimit=x-1;
                    int temp=x+width-1;
                    while(yScan>yLimit){
                        xScan=temp;
                        while(xScan>xLimit){scan();//////////////
                            xScan+=xDif;
                        }
                        yScan+=yDif;
                    }
                }
                else{
                    xScan=x+width-1;
                    xLimit=x-1;
                    yLimit=y-1;
                    int temp=y+height-1;
                    while(xScan>xLimit){
                        yScan=temp;
                        while(yScan>yLimit){scan();///////////////
                            yScan+=yDif;
                        }
                        xScan+=xDif;
                    }
                }               
            }
            else if(yDif>0){//-1x,+1y
                if(xInnerWhile){
                    yScan=y;
                    yLimit=y+height;
                    xLimit=x-1;
                    int temp=x+width-1;
                    while(yScan<yLimit){
                        xScan=temp;
                        while(xScan>xLimit){scan();///////////////////
                            xScan+=xDif;
                        }
                        yScan+=yDif;
                    }
                }
                else{
                    xScan=x+width-1;
                    xLimit=x-1;
                    yLimit=y+height;
                    while(xScan>xLimit){
                        yScan=y;
                        while(yScan<yLimit){scan();/////////////////////
                            yScan+=yDif;
                        }
                        xScan+=xDif;
                    }
                }               
            }
            else{//-1x,0y
                xScan=x+width-1;
                xLimit=x-1;
                yScan=yOneOnly;
                while(xScan>xLimit){
                    scan();
                    xScan+=xDif;
                }
               
            }
        }
        else if(xDif>0){
            if(yDif<0){//+1x,-1y
                if(xInnerWhile){
                    yScan=y+height-1;
                    yLimit=y-1;
                    xLimit=x+width;
                    while(yScan>yLimit){
                        xScan=x;
                        while(xScan<xLimit){scan();////////////////////////
                            xScan+=xDif;
                        }
                        yScan+=yDif;
                    }
                }
                else{
                    xScan=x;
                    xLimit=x+width;
                    yLimit=y-1;
                    int temp=y+height-1;
                    while(xScan<xLimit){
                        yScan=temp;
                        while(yScan>yLimit){scan();////////////////////
                            yScan+=yDif;
                        }
                        xScan+=xDif;
                    }
                }               

            }
            else if(yDif>0){//+1x,+1y
                if(xInnerWhile){//System.out.println("+1x,+1y,true");
                    yScan=y;
                    yLimit=y+height;
                    xLimit=x+width;
                    while(yScan<yLimit){
                        xScan=x;
                        while(xScan<xLimit){scan();//////////////////////
                            xScan+=xDif;
                        }
                        yScan+=yDif;
                    }
                }
                else{
                    xScan=x;
                    xLimit=x+width;
                    yLimit=y+height;
                    while(xScan<xLimit){
                        yScan=y;
                        while(yScan<yLimit){scan();////////////////////////
                            yScan+=yDif;
                        }
                        xScan+=xDif;
                    }
                }               
            }
            else{//1x,0y
                xScan=x;
                xLimit=x+width;
                yScan=yOneOnly;
                while(xScan<xLimit){
                    scan();
                    xScan+=xDif;
                }
            }
        }
        else{
            if(yDif<0){//0x-1y
                yScan=y+height-1;
                yLimit=y-1;
                xScan=xOneOnly;
                while(yScan>yLimit){
                    scan();
                    yScan+=yDif;
                }
            }
            else if(yDif>0){//0x+1y
                yScan=y;
                yLimit=y+height;
                while(yScan<yLimit){
                    scan();
                    yScan+=yDif;
                }
            }
            else{//0x 0y disabled?
                //System.out.println("Disabled all ? or just scan()");
                scan();//stupid
            }
           
        }
        scanAllFinished();

    }
   
   
   
   

   
}


class SarosiBuild{
    static int rows=3;
    static int cols=7;
    static JPanel jpGrid=new JPanel(new GridLayout(rows,cols));
    static JRadioButton comps[][]=new JRadioButton[rows][cols];
    static JSpinner jslXdif=new JSpinner(new SpinnerNumberModel(1,-101,101,1));
    static JSpinner jslYdif=new JSpinner(new SpinnerNumberModel(1,-101,101,1));
    static Sarosi testInit=new Sarosi(0,0,cols,rows){
        public void scan(){
            //System.out.println(xScan+" , "+yScan);
            comps[yScan][xScan]=new JRadioButton(xScan+" , "+yScan,false);
            jpGrid.add(comps[yScan][xScan]);
        }
    };
    static Sarosi testReset=new Sarosi(0,0,cols,rows){
        public void scan(){
            comps[yScan][xScan].setSelected(false);
        }
    };
    static Sarosi testAct=new Sarosi(0,0,cols,rows){
        public void scan(){
            comps[yScan][xScan].setSelected(true);
            Toolkit.getDefaultToolkit().beep();
            try{Thread.currentThread().sleep(500);}catch(InterruptedException inter){}
        }
    };

    static void testBuild(){
        JPanel jpButs=new JPanel(new GridLayout(4,1));
       
       
        JButton jbRestart=new JButton("Restart");
        jpButs.add(jbRestart);
       
       
        JPanel jpX=new JPanel(new BorderLayout());
        jpX.add(jslXdif,BorderLayout.CENTER);
        jpX.add(new JLabel(" X dif "),BorderLayout.WEST);
        jpButs.add(jpX);
       
        JPanel jpY=new JPanel(new BorderLayout());
        jpY.add(jslYdif,BorderLayout.CENTER);
        jpY.add(new JLabel(" Y dif "),BorderLayout.WEST);
        jpButs.add(jpY);

        JRadioButton jrbInnerWhile=new JRadioButton("X Inner While",true);
        jpButs.add(jrbInnerWhile);
       
       

       
        testInit.scanAll();
       
        JSplitPane jspl=new JSplitPane(1,jpButs,jpGrid);
       
       
       
        JFrame jfr=new JFrame("testing "+Sarosi.class);
        Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
        jfr.setBounds(screen.width/4,screen.height/4,screen.width/2,screen.height/2);
        jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jfr.getContentPane().add(jspl,BorderLayout.CENTER);
        jfr.setVisible(true);
       
        jbRestart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Thread thr=new Thread(){
                    public void run(){
                        testReset.scanAll();
                        try{Thread.currentThread().sleep(1234);}catch(InterruptedException inter){}
                        testAct.xDif=(Integer)jslXdif.getValue();
                        testAct.yDif=(Integer)jslYdif.getValue();
                        testAct.xInnerWhile=jrbInnerWhile.isSelected();
                        testAct.scanAll();
                       
                    }
                };
                thr.setDaemon(true);
                thr.start();
            }
        });
       
   
    }

}

Παρασκευή 13 Σεπτεμβρίου 2019

Xonly Function Parser Mononym as Polyonym

package dim.math.func;

import dim.A;
import dim.ext.javax.swing.tree.Dmtn;//DefaultMutableTreeNode
import java.lang.reflect.Constructor;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Vector;


/**
 *
 * @author jimidimi
 */
public class Parser extends Dmtn{
    public static Parser main=new Parser();
 
    public static void main(String[] args) {
        //test1();
        build();
    }
    static void test1(){
        Mononymo m=new Mononymo(8);
        m.xDyn=2.0;
        System.out.println(""+m.f(2));
        m.addDia(new Mononymo(2));
        System.out.println(""+m.f(2));
        m.addDia(new Mononymo(4));
        System.out.println(""+m.f(2));


        System.out.println(""+m);

     
    }
    static void build(){
        String testBrack="5x+(x-3-pe)+pow(x+3,sum(1,2pow(2,x+1),3x+1))";
        testBrack="geom(0,e,44)";
        Parser t=new Parser();
        t.parse(testBrack);
        //new Efr(new Etr(t)).setBounds(0,0,400,700);
     
    }
 
    protected Hashtable<Character, Double> statheres=new Hashtable<>();
    protected String telestes="+-/*%^,";
    protected Vector<String> funks=new Vector<>();
    protected Vector<Constructor> funksCons=new Vector<>();
    public Parser(){
        super("Function Parser version 1 - only x");
     
        statheres.put('p',Math.PI);
        statheres.put('e',Math.E);
        statheres.put('f',(1.0+Math.sqrt(5.0))/2.0);
             
        //0 params
        putClass(Rand.class);

     
        //1 params
        putClass(Abs.class);
        putClass(Sqrt.class);
        putClass(Cbrt.class);
        putClass(Ceil.class);
        putClass(Floor.class);
        putClass(Exp.class);
        putClass(Ln.class);
        putClass(Log.class);
        putClass(Rint.class);
        putClass(Round.class);
        putClass(Signum.class);
        putClass(Rad.class);
        putClass(Deg.class);
        putClass(Sin.class);
        putClass(Cos.class);
        putClass(Tan.class);
        putClass(Asin.class);
        putClass(Acos.class);
        putClass(Atan.class);
        putClass(Sinh.class);
        putClass(Cosh.class);
        putClass(Tanh.class);
         
     
        //2 params
        putClass(Min.class);
        putClass(Max.class);
        putClass(Pow.class);
        putClass(Atanpol.class);
        putClass(Hypot.class);
        putClass(Rem.class);
     
 
     
        //3 params
        putClass(Geom.class);
     
        //multi params
        putClass(Sum.class);
        putClass(Mul.class);
        putClass(Div.class);
     
     
     
    }
    protected synchronized Constructor putClass(Class cl){
        String cln=cl.getSimpleName().toLowerCase();
        Constructor con=null;
        try{
            con=cl.getConstructor(A.azcl);
            funks.add(cln);
            funksCons.add(con);
            //System.out.println(cln+" = "+con);
        }catch(NoSuchMethodException nsme){
            nsme.printStackTrace();
        }
        return con;
    }

    public Mononymo parse(String text){
        Mononymo m=null;
        try{
            Dmtn it,out=parseLevel1(text);
            Object uo;
            Enumeration en=out.depthFirstEnumeration();
            HashSet<Class> hs=new HashSet();
            while(en.hasMoreElements()){
                it=(Dmtn)en.nextElement();
                uo=it.getUserObject();
                if(uo instanceof String){
                    //System.out.println("Mononymizing : "+uo);
                    m=mononimize(it);
                    m.setUserObject(uo);
                    it.setUserObject(m);
                    //System.out.println("-----------");
                }
                hs.add(uo.getClass());
            }
            A.enln(hs.iterator());
         
            //new Efr(new Etr(m).scr()).q(600, 400, 230, 333).qExitOnClose();
            System.out.println("f(-2) = "+m.f(-2));
            System.out.println("f(-1) = "+m.f(-1));
            System.out.println("f(0) = "+m.f(0));
            System.out.println("f(1) = "+m.f(1));
            System.out.println("f(2) = "+m.f(2));
        }catch(Exception e){
            e.printStackTrace();
        }
        return m;
    }
 
    protected Mononymo mononimize(Dmtn level2){
        return mononimize(level2,new Mononymo(1),0,level2.getChildCount());
    }
    protected Mononymo mononimize(Dmtn level2,Mononymo theOut,int i ,int l){
        Mononymo out=theOut;
        if(l>0){
            Dmtn it;
            Object ito;
            char ch,prevch='*';
            double d;
            Func fn;
            if(level2.dmtn(i).getUserObject().equals('-')){
                //System.out.println("-------------");
                out.c=-out.c;
                ++i;
            }
            while(i<l){
                it=level2.dmtn(i);
                ito=it.getUserObject();
                if(ito instanceof Double){
                    d=(Double)ito;
                    if(prevch=='*'){out.c*=d;}
                    else if(prevch=='/'){out.c/=d;}
                    else if(prevch=='%'){out.c%=d;}
                    else if(prevch=='+'){System.err.println("Error +");}
                    else if(prevch=='-'){System.err.println("Error -");}
                }
                else if(ito instanceof Character){
                    ch=(Character)ito;
                    if(ch=='x'){out.xDyn+=1.0;}
                    else if(ch=='*'){prevch=ch;}
                    else if(ch=='/'){prevch=ch;}
                    else if(ch=='%'){prevch=ch;}
                    else if(ch=='+'){prevch='*';
                        Mononymo nm=new Mononymo(1.0);
                        theOut.addSum(nm);
                        out=nm;
                    }
                    else if(ch=='-'){prevch='*';
                        Mononymo nm=new Mononymo(-1.0);
                        theOut.addSum(nm);
                        out=nm;
                    }
                 
                }
                else if(ito instanceof Func){
                   fn=(Func)ito;
                   if(fn.getChildCount()>0){
                       System.err.println("Error on level for "+it);
                   }
                   else{
                       int j=0,k=it.getChildCount();Dmtn fch;Object fo;
                       System.out.println(fn+" ...Functioning "+k+" with ,kommas");
                       int flushedj=0;
                       while(j<k){
                           fch=it.dmtn(j);
                           fo=fch.getUserObject();
                           if(fo.equals(',')){
                               System.out.println("\t"+fo.getClass().getSimpleName()+" = "+fo);
                               fn.add(mononimize(it,new Mononymo(1.0),flushedj,j));
                               flushedj=j+1;
                           }
                           ++j;
                       }
                       fn.add(mononimize(it,new Mononymo(1.0),flushedj,j));
                   }
                    if(prevch=='*'){out.addGin(fn);}
                    else if(prevch=='/'){out.addDia(fn);}
                    else if(prevch=='%'){out.addYpol(fn);}
                    else if(prevch=='+'){out.addSum(fn);}
                    else if(prevch=='-'){System.err.println("Must Mononymo");out.addSum(fn);}
                 
                }
             
                ++i;
            }
        }
     
        return theOut;
    }
 
    protected Dmtn parseLevel1(String text)throws Exception{
        int l=text.length();
        int i=0,j,jl;
        Dmtn out=crad(text);
        char ch;
        String buf;
        Double d;
        while(i<l){
            ch=text.charAt(i);
            if(ch=='('){
                ++i;
                int opened=1;
                buf="";
                while(i<l){
                    ch=text.charAt(i);
                    if(ch=='('){++opened;buf+=ch;}
                    else if(ch==')'){
                        --opened;
                        if(opened<1){break;}
                        else{buf+=ch;}
                    }
                    else{buf+=ch;}
                    ++i;
                }
                //System.out.println("Anadromic parse = "+buf);
                out.add(parseLevel1(buf));
            }
            else if(ch==')'){
                //System.out.println("Closed error?");
                throw new Exception("Brackets closed without opened");
            }
            else if(Character.isLetter(ch)){
                //System.out.println("Initilising constants and ending function names");
                buf=""+ch;
                ++i;
                while(i<l){
                    ch=text.charAt(i);
                    if(Character.isLetter(ch)){buf+=ch;}
                    else{--i;break;}
                    ++i;
                }
                buf=buf.toLowerCase();
                //System.out.println("Hole String = "+buf);
                jl=buf.length();
                Constructor methFound=null;
                if(jl>1){//if more than one char find function from end
                    j=0;
                    jl=funks.size();
                    String meth;
                    while(j<jl){
                        meth=funks.get(j);
                        if(buf.endsWith(meth)){
                            methFound=funksCons.get(j);
                            buf=buf.substring(0,buf.length()-meth.length());
                            break;
                        }
                        ++j;
                    }
                }
                j=0;jl=buf.length();
                //check every char(before function founded or not if it is constant
                while(j<jl){
                    ch=buf.charAt(j);
                    if(ch=='x'){out.crad('x');}
                    else{
                        d=statheres.get(ch);
                        if(d!=null){out.crad(d);}
                        else{throw new IllegalArgumentException("Unknown char = "+ch); }
                    }
                    ++j;
                }
                if(methFound!=null){
                    Func newf=(Func)methFound.newInstance(A.azo);
                    out.crad(newf);
                    //System.out.println("new "+newf.getClass().getSimpleName());
                }
             
            }
            else if(Character.isDigit(ch)||ch=='.'){
                //System.out.println("Initilising numbers");
                buf=""+ch;
                ++i;
                while(i<l){
                    ch=text.charAt(i);
                    if(Character.isDigit(ch)||ch=='.'){buf+=ch;}
                    else{--i;break;}
                    ++i;
                }
                d=Double.parseDouble(buf);
                out.crad(d);//double
            }
            else{
                if(telestes.contains(ch+"")){
                    out.crad(ch);//char
                }
                else{
                    throw new IllegalArgumentException("Unknown char = "+ch);
                }
            }

            ++i;
        }
        //return out;
        return parseLevel2(out);
    }
 
    protected Dmtn parseLevel2(Dmtn out){
        //System.out.println("replace ^ with pow()");
        int l=out.getChildCount();
        Dmtn it;Object uo;
        --l;
        char ch;
        while(l>=0){
            it=out.dmtn(l);
            uo=it.getUserObject();
            if(uo instanceof Character){
                ch=(Character)uo;
                if(l>0&&ch=='^'){
                    //System.out.println("Replacing ^ with pow");
                    Dmtn prev=out.dmtn(l-1);
                    Dmtn aft=out.dmtn(l+1);
                    Dmtn newPow=new Dmtn(new Pow());
                    newPow.add(prev);
                    newPow.add(it);
                    newPow.add(aft);
                    it.setUserObject(',');
                    out.insert(newPow, l-1);
                    --l;
                }
            }
            else if(uo instanceof Func){
                if(it.getChildCount()==0){
                    Dmtn aft=out.dmtn(l+1);
                    if(aft.getUserObject() instanceof String){
                        //System.out.println("Transferring parameters inside");
                        out.remove(l+1);
                        int jl=aft.getChildCount()-1;
                        while(jl>=0){
                            it.insert(aft.dmtn(jl), 0);
                            --jl;
                        }
                    }
                }
            }
            --l;
        }
     
     
        return out;
    }
 
}


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

public class Mononymo extends Func{

    double c=1.0;
    double xDyn=0.0;

    public Mononymo(String sometext) {
        super();
        setUserObject(sometext);
    }
    public Mononymo(double ac){
        c=ac;
    }
    public Mononymo(double ac,Double axpow){
        c=ac;
        xDyn=axpow;
    }

    @Override
    public Dmtn cr() {
        return new Mononymo("");
    }
    
    

    public String toString(){
        String out="";
        if(c<0.0){out+=c+"";}
        else{out+="+"+c;}
        if(xDyn!=0.0){
            out+="x";
            if(xDyn!=1.0){
                out+="^("+xDyn+")";
            }
        }
        //return getUserObject().toString();
        return out+" @ "+getUserObject();
    }
    public boolean hasX(){
        if(xDyn!=0.0){
            return true;
        }
        return super.hasX();
    } 
    
    
    
    private int gin=0,dia=0,ypol=0,sum=0;
    public int gins(){return gin;}
    public int dias(){return dia-gin;}
    public int ypols(){return ypol-dia;}
    public int sums(){return sum-ypol;}
    public double f(double x){
        double out=c;
        out*=Math.pow(x, xDyn);
        int i=0;
        while(i<gin){
            out*=func(i).f(x);
            ++i;
        }
        while(i<dia){
            out/=func(i).f(x);
            ++i;
        }
        while(i<ypol){
            out%=func(i).f(x);
            ++i;
        }
        while(i<sum){
            out+=func(i).f(x);
            ++i;
        }
        return out;
    }
    
    public void addGin(Func f){
        insert(f, gin);
        gin++;
        dia++;
        ypol++;
        sum++;
    }
    public void addDia(Func f){
        insert(f, dia);
        dia++;
        ypol++;
        sum++;
    }
    public void addYpol(Func f){
        insert(f, ypol);
        ypol++;
        sum++;
    }
    public void addSum(Func f){
        add(f);
        ++sum;
    }

}








class Func extends Dmtn{
    public Func(){}
    public String toString(){
        return getClass().getSimpleName();
    }
    public double f(double x){
        return x;
    }
    public Func func(int index){
        return (Func)getChildAt(index);
    }
    public boolean hasX(){
        int l=getChildCount();
        if(l>0){
            int i=0;
            while(i<l){
                if(func(i).hasX()){return true;}
                ++i;
            }
        }
        return false;
    } 

}
class Pow extends Func{
    public Pow() {}
    public double f(double x){
        return Math.pow(func(0).f(x),func(1).f(x));
    }
}
class Min extends Func{
    public Min() {}
    public double f(double x){
        return Math.min(func(0).f(x),func(1).f(x));
    }
}
class Max extends Func{
    public Max() {}
    public double f(double x){
        return Math.max(func(0).f(x),func(1).f(x));
    }
}
class Abs extends Func{
    public Abs() {}
    public double f(double x){
        return Math.abs(func(0).f(x));
    }
}
class Rad extends Func{
    public Rad() {}
    public double f(double x){
        return Math.toRadians(func(0).f(x));
    }
}
class Deg extends Func{
    public Deg() {}
    public double f(double x){
        return Math.toDegrees(func(0).f(x));
    }
}
class Sin extends Func{
    public Sin() {}
    public double f(double x){
        return Math.sin(func(0).f(x));
    }
}
class Asin extends Func{
    public Asin() {}
    public double f(double x){
        return Math.asin(func(0).f(x));
    }
}
class Sinh extends Func{
    public Sinh() {}
    public double f(double x){
        return Math.sinh(func(0).f(x));
    }
}
class Cos extends Func{
    public Cos() {}
    public double f(double x){
        return Math.cos(func(0).f(x));
    }
}
class Acos extends Func{
    public Acos() {}
    public double f(double x){
        return Math.acos(func(0).f(x));
    }
}
class Cosh extends Func{
    public Cosh() {}
    public double f(double x){
        return Math.cosh(func(0).f(x));
    }
}
class Tan extends Func{
    public Tan() {}
    public double f(double x){
        return Math.tan(func(0).f(x));
    }
}
class Atan extends Func{
    public Atan() {}
    public double f(double x){
        return Math.atan(func(0).f(x));
    }
}
class Tanh extends Func{
    public Tanh() {}
    public double f(double x){
        return Math.tanh(func(0).f(x));
    }
}
class Atanpol extends Func{
    public Atanpol() {}
    public double f(double x){
        return Math.atan2(func(0).f(x),func(1).f(x));
    }
}


class Sqrt extends Func{
    public Sqrt() {}
    public double f(double x){
        return Math.sqrt(func(0).f(x));
    }
}
class Cbrt extends Func{
    public Cbrt() {}
    public double f(double x){
        return Math.cbrt(func(0).f(x));
    }
}
class Ceil extends Func{
    public Ceil() {}
    public double f(double x){
        return Math.ceil(func(0).f(x));
    }
}
class Floor extends Func{
    public Floor() {}
    public double f(double x){
        return Math.floor(func(0).f(x));
    }
}
class Rem extends Func{
    public Rem() {}
    public double f(double x){
        return Math.IEEEremainder(func(0).f(x),func(1).f(x));
    }
}
class Exp extends Func{
    public Exp() {}
    public double f(double x){
        return Math.exp(func(0).f(x));
    }
}
class Hypot extends Func{
    public Hypot() {}
    public double f(double x){
        return Math.hypot(func(0).f(x),func(1).f(x));
    }
}

class Ln extends Func{
    public Ln() {}
    public double f(double x){
        return Math.log(func(0).f(x));
    }
}
class Log extends Func{
    public Log() {}
    public double f(double x){
        return Math.log10(func(0).f(x));
    }
}
class Rand extends Func{
    public Rand() {}
    public double f(double x){
        return Math.random();
    }
}
class Rint extends Func{
    public Rint() {}
    public double f(double x){
        return Math.rint(func(0).f(x));
    }
}
class Round extends Func{
    public Round() {}
    public double f(double x){
        return Math.round(func(0).f(x));
    }
}
class Signum extends Func{
    public Signum() {}
    public double f(double x){
        return Math.signum(func(0).f(x));
    }
}

class Sum extends Func{
    public Sum() {}
    public double f(double x){
        int l=getChildCount();
        double out=0.0;
        if(l>0){
            int i=0;
            Func it=func(i);
            out=it.f(x);
            ++i;
            while(i<l){
                out+=func(i).f(x);
                ++i;
            }
        }
        return out;
    }
}
class Mul extends Func{
    public Mul() {}
    public double f(double x){
        int l=getChildCount();
        double out=0.0;
        if(l>0){
            int i=0;
            Func it=func(i);
            out=it.f(x);
            ++i;
            while(i<l){
                out*=func(i).f(x);
                ++i;
            }
        }
        return out;
    }
}
class Div extends Func{
    public Div() {}
    public double f(double x){
        int l=getChildCount();
        double out=0.0;
        if(l>0){
            int i=0;
            Func it=func(i);
            out=it.f(x);
            ++i;
            while(i<l){
                out/=func(i).f(x);
                ++i;
            }
        }
        return out;
    }
}
class Poly extends Func{
    public Poly() {}
    public double f(double x){
        int l=getChildCount();
        double out=0.0;
        if(l>0){
            int i=0;
            Func it=func(i);
            out=it.f(x);
            ++i;
            while(i<l){
                out+=Math.pow(func(i).f(x),i+1);
                ++i;
            }
        }
        return out;
    }
}
class Geom extends Func{
    public Geom() {}
    public double f(double x){
        int l=getChildCount();
        double out=0.0;
        if(l>0){
            int i=0;
            double startFrom=func(i).f(x);
            double lamda=0.5;
            double times=10;
            
            ++i;
            if(i<l){
                lamda=func(i).f(x);
            }
            ++i;
            if(i<l){
                times=func(i).f(x);
            }
            
            
            out=startFrom;
            
            i=0;
            while(i<times){
                startFrom*=lamda;
                out+=startFrom;
                ++i;
            }
        }
        return out;
    }
}


Τρίτη 20 Αυγούστου 2019

java.awt.Splitpane

/*
updated 2/4/2021 simplest version
 */
package jim3d;

import java.awt.Color;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 *
 * @author jimakoskx
 */
public class Spl extends Panel implements ComponentListener,MouseListener,MouseMotionListener,KeyListener{
    public static void main(String[] args) {
        Frame fr=new Frame();
        fr.setBounds(0,0,555,555);
        fr.setVisible(true);
        
        Spl s=new Spl();
        fr.add(s);
        fr.validate();
        
        TextField tf=new TextField("hfgh");
        TextArea ta=new TextArea("Area");  
        s.add(tf);
        s.add(ta);
        s.resetLayout();
        
        s.setDividerSize(6);
    }
    private int orientation=1;
    private double divloc=0.2;
    
    private int firstsize=1;
    private int divsizehalf=5;
    private int secondsize=1;
    
    

    public Spl() {
        super();
        super.setBackground(Color.red);
        super.setLayout(null);
        super.addComponentListener(this);
        super.addMouseListener(this);
        super.addMouseMotionListener(this);
        super.addKeyListener(this);
        
    }
    public int getOrientation(){
        return orientation;
    }
    public Spl setOrientation(int i01){
        orientation=Math.abs(i01)%2;
        resetLayout();
        return this;
    }
    public Spl setDividerLocation(double middle){
        if(middle<0.0){middle=0.0;}
        else if(middle>0.99){middle=0.99;}
        divloc=middle;
        resetLayout();
        return this;
    }
    public Spl setDividerSize(int uptocurrsize){
        if(orientation==0){
            uptocurrsize=Math.min(getHeight(), uptocurrsize);
        }
        else{
            uptocurrsize=Math.min(getWidth(), uptocurrsize);
        }
        if(uptocurrsize<2){
            uptocurrsize=2;
        }
        divsizehalf=uptocurrsize/2;
        resetLayout();
        return this;
    }
    public void switchOrientation(){
        setOrientation(getOrientation()+1);
    }
    
    public void switchComponents(){
        Component cs[]=getComponents();
        if(cs.length>1){
            removeAll();
            add(cs[1]);
            add(cs[0]);
            int i=2;
            while(i<cs.length){
                add(cs[i]);
                ++i;
            }
        }
        resetLayout();
    }
    protected void resetLayout(){
        Component cs[]=getComponents();
        if(cs.length>0){
            int w=getWidth();
            int h=getHeight();
            if(cs.length==1){
                cs[0].setBounds(0,0,w,h);
            }
            else {
                if(orientation==0){
                    firstsize=(int)(divloc*h)-divsizehalf-1;
                    secondsize=h-firstsize-divsizehalf-divsizehalf-1;
                    cs[0].setBounds(0, 0,w, firstsize);
                    cs[1].setBounds(0, firstsize+divsizehalf+divsizehalf,w, secondsize);
                }
                else{
                    firstsize=(int)(divloc*w)-divsizehalf-1;
                    secondsize=w-firstsize-divsizehalf-divsizehalf-1;
                    cs[0].setBounds(0, 0,firstsize, h);
                    cs[1].setBounds(firstsize+divsizehalf+divsizehalf,0,secondsize,h);
                }
                //System.out.println(w+" , "+h);  
                //System.out.println(divloc+"  +2*"+divsizehalf);
                //System.out.println(firstsize+" - "+secondsize);
                //System.out.println(""+cs[0].getBounds());
                //System.out.println(""+cs[1].getBounds());
                //System.out.println("");
            }
        }  
        validate();
        repaint();
    }

    @Override
    public void componentResized(ComponentEvent e) {
        resetLayout();
    }

    @Override
    public void componentMoved(ComponentEvent e) {
    }

    @Override
    public void componentShown(ComponentEvent e) {
    }

    @Override
    public void componentHidden(ComponentEvent e) {
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }
    @Override
    public void mousePressed(MouseEvent e) {
        requestFocus();
    }

    @Override
    public void mouseReleased(MouseEvent e) {
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if(orientation==0){
            int h=getHeight();
            double dif=e.getY();
            dif/=h;
            setDividerLocation(dif);
            
        }
        else{
            int w=getWidth();
            double dif=e.getX();
            dif/=w;
            setDividerLocation(dif);
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int kc=e.getKeyCode();
        if(kc==KeyEvent.VK_F2){
            VK_F2();
        }
        else if(kc==KeyEvent.VK_F3){
            VK_F3();
        }
        else if(kc==KeyEvent.VK_F4){
            VK_F4();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public void VK_F2(){
        switchOrientation();
    }
    public void VK_F3(){
        setDividerLocation(0.5);
    }
    public void VK_F4(){
        switchComponents();
    }
    

}