Σάββατο 12 Νοεμβρίου 2022

English Vocabulary Enrichment from Jwiki_0

 ...













https://en.wikipedia.org/wiki/Web_scraping

https://en.wikipedia.org/wiki/Document_Object_Model

/**

 *

 * @author jimak

 * @date Nov 13, 2022

 */

public class Dom extends Node{

    public static void main(String[] args) {

        JHTMLParserBuilder.main(args);

    }


    public Dom() {

        super();

        getBuffer().append("DOM");

    }

    

    

    public void parse(StringBuffer inputBuf){

        int inputLen=inputBuf.length();

        int inputI=0;

        char ch;

        Node workingNode=this;

        StringBuffer workingBuf=workingNode.getBuffer();

        while(inputI<inputLen){

            ch=inputBuf.charAt(inputI);

            if(ch!='<'){

                workingBuf.append(ch);

            }

            else{

                StringBuffer holeTag=new StringBuffer(" ");

                holeTag.append(ch);

                ++inputI;

                boolean closedok=false;

                String tagName="";

                boolean spaceNotFound=true;

                while(inputI<inputLen){

                    ch=inputBuf.charAt(inputI);

                    ++inputI;

                    holeTag.append(ch);

                    if(ch=='>'){

                        closedok=true;

                        break;

                    }

                    else if(spaceNotFound){

                        if(ch==' '){spaceNotFound=false;}

                        else{tagName+=ch;}

                    }

                }

                //System.out.println(inputI+" , "+tagName+" : "+holeTag);

                if(closedok){

                    boolean isClosingTag=tagName.charAt(0)=='/';

                    //System.out.println("Closing:"+isClosingTag);

                    if(isClosingTag){

                        String realTag=tagName.substring(1);

                        Node firstOpenedParent=workingNode.getFirstParentTag(realTag);

                        if(firstOpenedParent!=null){

                            Node neoNode=new Node();

                            workingNode=(Node)firstOpenedParent.getParent();

                            workingNode.add(neoNode);

                            workingNode=neoNode;

                            workingBuf=workingNode.getBuffer();

                        }

                        else{

                            System.out.println(inputI+" , "+tagName+" : "+holeTag);

                            System.out.println("Didnt find any opening Tag for this ...continueing");

                        }

                    }

                    else{

                        Tag neoTag=new Tag(holeTag,tagName);

                        workingNode.add(neoTag);

                        workingNode=neoTag;

                        workingBuf=workingNode.getBuffer();

                        

                        Node neoNode=new Node();

                        workingNode.add(neoNode);

                        workingNode=neoNode;

                        workingBuf=workingNode.getBuffer();

                    }

                }

                else{

                    workingBuf.append(holeTag);

                }

                

                --inputI;

                

            }

            ++inputI;

            

        }

        

        System.out.println("end main parsing.Now must remove empty nodes");

        

        Vector<Node> toBeRemoved=new Vect<Node>();

        Enumeration en=preorderEnumeration();

        en.nextElement();

        while(en.hasMoreElements()){

            Node n=(Node)en.nextElement();

            StringBuffer nb=n.getBuffer();

            String s=nb.toString().trim();

            //System.out.println(s.length()+">"+s);

            int nbls=s.length();

            if(nbls>0){


            }

            else{

                toBeRemoved.add(n);

            }

        }

        int i=0,l=toBeRemoved.size();

        System.out.println("must remove "+toBeRemoved.size());

        while(i<l){

            Node n=toBeRemoved.get(i);

            //n.getBuffer().append("To Be Removed");

            Node np=(Node)n.getParent();

            int nIndex=np.getIndex(n);

            np.remove(nIndex);

            int chs=n.getChildCount();

            --chs;

            while(chs>-1){

                Node nch=(Node)n.getChildAt(chs);

                np.insert(nch, nIndex);

                --chs;

            }

            ++i;

        }

    }

    


}


Πέμπτη 10 Νοεμβρίου 2022

a vocabulary text day trick ?

     static String days[]={"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THUSDAY","FRIDAY","SATURDAY"};

    

    static Hashtable<String,Integer>hash=new Hashtable<>();

    static{

        int i=0;

        while(i<days.length){

            hash.put(days[i].substring(0,2),i);

            ++i;

        }

    }

    public static void main(String[] args) {

        

        int i=0;

        int l=10000000;

        int r,o;

        

        long ts=System.currentTimeMillis();

        while(i<l){

            r=Rand.sti.nextInt(7);

            o=getIndexOfDay0(days[r]);

            ++i;

        }

        long te=System.currentTimeMillis();

        te-=ts;

        System.out.println("time:"+te);

    }

    static final int[]trick0={

        4,6,5,0,0

       ,3,0,0,0,0

       ,0,0,0,1,0

       ,0,0,0,0,0

       ,2

    } ;

    

    public static int getIndexOfDay1(String someday){

        String key=Character.toUpperCase(someday.charAt(0))+""+Character.toUpperCase(someday.charAt(1));

        return hash.get(key);

    }

    public static int getIndexOfDay0(String someday){

        char ch0=Character.toUpperCase(someday.charAt(0));

        int ch1=Character.toUpperCase(someday.charAt(1));

        ch1&=ch0;

        ch1-=64;

        return trick0[ch1];

    }


Δευτέρα 7 Νοεμβρίου 2022

Java Simple Snake Game


Jar with src (if jdk installed)

https://drive.google.com/file/d/1yNAFEdnr-p5pDZjh0kctfWyVPR0nkLNX/view?usp=sharing



 









(or compile and run ~ 700 lines)


/*

 * 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 jsnake;


import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.GridLayout;

import java.awt.Toolkit;

import java.awt.event.ComponentEvent;

import java.awt.event.ComponentListener;

import java.awt.event.ItemEvent;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.util.Random;

import java.util.Vector;

import javax.swing.JButton;

import javax.swing.JCheckBox;

import javax.swing.JComboBox;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JSpinner;

import javax.swing.SpinnerNumberModel;

import javax.swing.event.ChangeEvent;


/**

 *

 * @author jimak

 */

public class JSnake extends JPanel  implements MouseListener,KeyListener,ComponentListener{


    public static String getHelpString(){

        return ""

                + "Simple Java Snake Options"

                + "\nPress"

                + "\nArrows or W-up S-down A-left D-Right to turn snake's head."

                + "\n\nY/U to decrease/increase snake's speed."

                + "\nG/H to decrease/increase Rows and Cols."

                + ""

                + "\n\nT to change paint type"

                + "\nR to change snake's color."

                + "\nL to just ignore that you just lost.(just not show the red line)"

                + ""

                + "\n\nP to Restart by having almost half being filled."

                + "\n\nEnter to Restart ."

                + ""

                + ""

                + ""

                + ""

                + ""

                + ""

                + ""

                + ""

                + ""

                + ""

                + ""

                + "\n\n\n(you can still play if you loose and have some move to go)";

    }

    static Toolkit tk=Toolkit.getDefaultToolkit();

    static Dimension scr=tk.getScreenSize();

    static Random rand=new Random();

    public static Color randColor(){

        return new Color(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255));

    }

    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

    

        try{

            JFrame jfr=new JFrame("Simple Java Snake Game");

            jfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            int insw=scr.width/10;

            int insh=scr.height/10;

            jfr.setBounds(insw,insh,scr.width-2*insw,scr.height-2*insh);

            JSnake jsn=new JSnake();

            jfr.getContentPane().add(jsn);

            jfr.setVisible(true);

            JOptionPane.showMessageDialog(null,getHelpString());

            //throw new IllegalAccessError();

        }catch(Throwable thr){

            try{System.err.println(""+thr);}catch(Throwable thr2){}

            try{JOptionPane.showMessageDialog(null, thr,"will exit app",JOptionPane.ERROR_MESSAGE);}catch(Throwable thr2){}

            try{thr.printStackTrace();}catch(Throwable thr2){}

            System.exit(-1);

        }

        

    }

    

    static int dirs[][]=new int[4][2];

    public static final int dirRight=0;

    public static final int dirDown=1;

    public static final int dirLeft=2;

    public static final int dirUp=3;

    static{

        dirs[dirRight][0]=1;

        dirs[dirRight][1]=0;

        

        dirs[dirDown][0]=0;

        dirs[dirDown][1]=1;

        

        dirs[dirLeft][0]=-1;

        dirs[dirLeft][1]=0;

        

        

        dirs[dirUp][0]=0;

        dirs[dirUp][1]=-1;

    }

    public static int oppositeDir(int some){

        if(some==dirRight){return dirLeft;}

        if(some==dirLeft){return dirRight;}

        if(some==dirDown){return dirUp;}

        return dirDown;

    }

    

    JButton jbFillHalf=new JButton("Restart-Half");

    JButton jbRestart=new JButton("Restart");

    JSpinner jspRowsCols=new JSpinner(new SpinnerNumberModel(12,5,100,1));

    JPanel jpRowsCols=new JPanel(new BorderLayout());

    JSpinner jspMovesPerSecond=new JSpinner(new SpinnerNumberModel(3,1,10,1));

    JPanel jpMovesPerSecond=new JPanel(new BorderLayout());

    JPanel jpOthers=new JPanel(new GridLayout(1,2));

    

    JPanel jpRestartButs=new JPanel(new GridLayout(1,2));

    

    int rows,cols;

    int sqs;

    int headDir=0;

    byte snakex[];

    byte snakey[];

    int snakeLen=0;

    

    Graphics2D g;

    class SnakePainter{

        void paintSnakeSquare(int x,int y){

            g.fillRect(x+1, y+1, sqs-2,sqs-2);

        }

        public String toString(){return "fill Rect";}

    };

    SnakePainter currSnakePainter=new SnakePainter();

    SnakePainter snakePainter[]={

        currSnakePainter

        ,new SnakePainter(){

            void paintSnakeSquare(int x,int y){g.fillOval(x, y, sqs,sqs);}

            public String toString(){return "fill Oval";}

        }

        ,new SnakePainter(){

            void paintSnakeSquare(int x,int y){g.drawRect(x, y, sqs,sqs);}

            public String toString(){return "Quicker";}

        }

        ,new SnakePainter(){

            void paintSnakeSquare(int x,int y){g.drawOval(x, y, sqs,sqs);}

            public String toString(){return "draw Oval";}

        }

        ,new SnakePainter(){

            void paintSnakeSquare(int x,int y){g.drawOval(x, y, sqs,sqs);g.drawRect(x, y, sqs,sqs);}

            public String toString(){return "draws";}

        }

    };

    JComboBox<SnakePainter> jcombPaintType=new JComboBox<>(snakePainter);

    

    JPanel jpPaint=new JPanel(){

        public void paintComponent(Graphics gr){

            super.paintComponent(gr);

            g=(Graphics2D)gr;

            paintSnake();

        }

    };

    Thread thrRepainter=new Thread(){

        @Override

        public void run() { 

            while(true){

                jpPaint.repaint();

                try{sleep(20);}catch(InterruptedException inter){}

            

            }

        }

    };

    long thrMoverSleep=1000/(int)jspMovesPerSecond.getValue();

    boolean thrMoverPaused=false;

    Thread thrMover=new Thread(){

        @Override

        public void run() {

            while(true){

                if(thrMoverPaused){

                    try{sleep(600000);}catch(InterruptedException inter){}

                }

                else{

                    moveSnake();

                    try{sleep(thrMoverSleep);}catch(InterruptedException inter){}

                }

            }

        }

    };

    void thrMoverPause(){

        thrMoverPaused=true;

        thrMover.interrupt();

    }

    void thrMoverUnpause(){

        thrMoverPaused=false;

        thrMover.interrupt();

    }

    Font bigFont=new Font("Dialog",1,24);

    public JSnake(){

        super(new BorderLayout());

        jpPaint.setFont(bigFont);

        

        

        

        jpRestartButs.add(jbRestart);

        jpRestartButs.add(jbFillHalf);

        

        jpRowsCols.add(BorderLayout.WEST,new JLabel("Rows&Cols"));

        jpRowsCols.add(BorderLayout.CENTER,jspRowsCols);

        jpRowsCols.add(BorderLayout.EAST,jpRestartButs);

        

        jpMovesPerSecond.add(BorderLayout.WEST,new JLabel("moves/sec"));

        jpMovesPerSecond.add(BorderLayout.CENTER,jspMovesPerSecond);

        jpMovesPerSecond.add(BorderLayout.EAST,jcombPaintType);

        

        jpOthers.add(jpRowsCols);

        jpOthers.add(jpMovesPerSecond);

        

        add(BorderLayout.CENTER,jpPaint);

        add(BorderLayout.SOUTH,jpOthers);


        

        jspRowsCols(null);

        jbRestart();

        componentResized(null);

        

        

        

        jpPaint.addMouseListener(this);

        jpPaint.addKeyListener(this);

        

        addComponentListener(this);

        jspRowsCols.addChangeListener(e->jspRowsCols(e));

        jspMovesPerSecond.addChangeListener(e->jspMovesPerSecond());

        jbFillHalf.addActionListener(e->jbRestartHalf());

        jbRestart.addActionListener(e->jbRestart());

        jcombPaintType.addItemListener(e->jcombPaintType(e));

        

        

        Thread focuser=new Thread(){

            public void run(){

                try{sleep(1111);}catch(InterruptedException inter){}

                jpPaint.requestFocusInWindow();

                try{sleep(1111);}catch(InterruptedException inter){}

                jpPaint.requestFocusInWindow();

            }

        };

        focuser.setDaemon(true);

        thrMover.setDaemon(true);

        thrRepainter.setDaemon(true);

        

        

        

        thrRepainter.start();

        thrMover.start();

        focuser.start(); 

    }

    void jcombPaintType(ItemEvent e){

        if(e.getStateChange()==ItemEvent.SELECTED){

            currSnakePainter=(SnakePainter)jcombPaintType.getSelectedItem();

            jpPaint.requestFocusInWindow();

        }

    }

    void nextSnakePaintType(){

        int si=jcombPaintType.getSelectedIndex();

        ++si;

        if(si>=snakePainter.length){

            si=0;

        }

        jcombPaintType.setSelectedIndex(si);

    }

    void increaseSpeed(){

        int next=(int)jspMovesPerSecond.getValue();

        next+=1;

        if(next<=(int)((SpinnerNumberModel)jspMovesPerSecond.getModel()).getMaximum()){

            jspMovesPerSecond.setValue(next);

        }

        else{ tk.beep();}

    }

    void decreaseSpeed(){

        int next=(int)jspMovesPerSecond.getValue();

        next-=1;

        if(next>=(int)((SpinnerNumberModel)jspMovesPerSecond.getModel()).getMinimum()){

            jspMovesPerSecond.setValue(next);

        }

        else{tk.beep();}

    }

    void increaseRowsCols(){

        int next=(int)jspRowsCols.getValue();

        next+=1;

        if(next<=(int)((SpinnerNumberModel)jspRowsCols.getModel()).getMaximum()){

            jspRowsCols.setValue(next);

        }

        else{tk.beep();}

    }

    void decreaseRowsCols(){

        int next=(int)jspRowsCols.getValue();

        next-=1;

        if(next>=(int)((SpinnerNumberModel)jspRowsCols.getModel()).getMinimum()){

            jspRowsCols.setValue(next);

        }

        else{tk.beep();}

    }

    void jspMovesPerSecond(){

        long sec=1000;

        sec/=(int)jspMovesPerSecond.getValue();

        thrMoverSleep=sec;

    }

    void jspRowsCols(ChangeEvent e){

        int rc=(int)jspRowsCols.getValue();

        int rcs=rc*rc;

        byte neox[]=new byte[rcs];

        byte neoy[]=new byte[rcs];

        rows=rc;

        cols=rc;

        snakex=neox;

        snakey=neoy;

        jbRestart();

        componentResized(null);

        

    }

    void jbRestartHalf(){

        if(jbFillHalf.isEnabled()){

            thrMoverPause();

            int l=snakex.length;

            int half=l/2;

            int x=2;

            int y=3;

            if(rows<10){

                y=1;

            }

           

            headDir=dirRight;

            snakeLen=1;

            int i=0;

            snakex[i]=(byte)x;

            snakey[i]=(byte)y;

            ++y;

            ++i;

            boolean ystartOdd=y%2==1;

            while(y<rows){

                if(ystartOdd==(y%2==1)){

                    x=2;

                    while(x<cols){

                        snakex[i]=(byte)x;

                        snakey[i]=(byte)y;

                        ++i;++snakeLen;

                        ++x;

                    }

                }

                else{

                    x=cols-1;

                    while(x>1){

                        snakex[i]=(byte)x;

                        snakey[i]=(byte)y;

                        ++i;++snakeLen;

                        --x;

                    }

                    

                }

                ++y;

            }

            lost=false;won=false;

            createNewRandomApple();

            jpPaint.requestFocusInWindow();

            thrMoverUnpause();

            //jbFillHalf.setEnabled(false);

        }else{tk.beep();}

    }

    void jbRestart(){

        setAllEmpty(2,2,0);

    }

    void setAllEmpty(int snakeI,int snakeJ,int dir){

        thrMoverPause();

        jbFillHalf.setEnabled(true);

        

        lost=false;won=false;

        snakeLen=1;

        snakex[0]=(byte)snakeI;

        snakey[0]=(byte)snakeJ;

        headDir=dir;

        createNewRandomApple();

        jpPaint.requestFocusInWindow();

        thrMoverUnpause();

     }

    

    int applei=-1,applej=-1;

    int availables=0;

    void createNewRandomApple(){

        Vector<Integer> avXs=new Vector<>();

        Vector<Integer> avYs=new Vector<>();

        int i=0;

        while(i<rows){

            int j=0;

            while(j<cols){

                int s=0;

                boolean snakeHasThisSquare=false;

                while(s<snakeLen){

                    if(snakex[s]==j && snakey[s]==i){

                        snakeHasThisSquare=true;

                        s=snakeLen;

                    }

                    ++s;

                }

                if(!snakeHasThisSquare){

                    avXs.add(j);

                    avYs.add(i);

                }

                ++j;

            }

            ++i;

        }

        int size=avXs.size();

        availables=size-1;

        won=availables<rows;

        if(size>0){

            int appleIndex=rand.nextInt(size);

            applei=avXs.get(appleIndex);

            applej=avYs.get(appleIndex);

        }

        else{

            System.out.println("You won !!!! ");

            won=true;

        }

        //System.out.println("Availables: "+availables);

        

    }

    boolean snakeContains(int r,int c){

        int i=0;

        while(i<snakeLen){

            if(snakex[i]==r && snakey[i]==c){

                return true;

            }

            i++;

        }

        

        return false;

    }

    void moveSnake(){

        //System.out.println("moviung");

        int i=0;

        int headi=snakex[0];

        int headj=snakey[0];

        

        int nextheadi=headi+dirs[headDir][0];

        int nextheadj=headj+dirs[headDir][1];

        if(nextheadi<0 ||nextheadi>=cols || nextheadj<0 || nextheadj>=rows){

            lost=true;

        }

        else{

            if(snakeContains(nextheadi, nextheadj)){

                lost=true;

            }

            else{

                

                if(nextheadi==applei && nextheadj==applej){

                    //System.out.println("eating increase snake len");

                    int last=snakeLen;

                    while(last>0){

                        snakex[last]=snakex[last-1];

                        snakey[last]=snakey[last-1];

                        --last;

                    }

                    snakeLen++;

                    snakex[0]=(byte)nextheadi;

                    snakey[0]=(byte)nextheadj;

                    createNewRandomApple();

                    jpPaint.repaint();

                }

                else{

                    int last=snakeLen-1;

                    while(last>0){

                        snakex[last]=snakex[last-1];

                        snakey[last]=snakey[last-1];

                        --last;

                    }

                    snakex[0]=(byte)nextheadi;

                    snakey[0]=(byte)nextheadj;

                }

            }

        }

        

    }

    int headDir(){

        int out=-1;

        if(snakeLen>1){

            if(snakex[0]>snakex[1]){

                return dirRight;

            }

            else if(snakex[0]<snakex[1]){

                return dirLeft;

            }

            else if(snakey[0]>snakey[1]){

                return dirDown;

            }

            else{

                return dirUp;

            }

        }

        return out;

    }

    void setDir(int newDir){

        int dirCurr=headDir();

        if(dirCurr>-1){

            if(newDir!=oppositeDir(dirCurr)){

                headDir=newDir;

            }

            else{

                System.out.println("avoid set opposite direction");

            }

        }

        else{

            headDir=newDir;

        }

    }

    Color colSnake=Color.blue;

    Color colSq=Color.white;

    Color colWall=new Color(10,55,88,88);

    boolean lost=false;

    boolean won=false;

    int wall=10;

    int wall2=wall*2;

    void paintSnake(){

        g.setColor(colWall);

        int x=0;

        int y=0;

        g.fillRect(0, 0, wall2+(cols)*sqs,wall);//up wall

        g.fillRect(0, wall+((rows)*sqs),wall2+(cols)*sqs, wall);//down wall

        g.fillRect(x,wall2, wall, (rows)*sqs-wall2);//left wall

        g.fillRect(wall+cols*sqs,wall2, wall, (rows)*sqs-wall2);//right wall

        

        g.setColor(colSq);

        int i=0,j;

        x=wall;

        y=wall;

        while(i<rows){

            j=i%2;

            x=wall+j*sqs;

            while(j<cols){

                g.fillRect(x,y, sqs,sqs);

                j+=2;

                x+=sqs*2;

            }

            y+=sqs;

            ++i;

        }

        

        g.setColor(colSnake);

        i=0;

        

        while(i<snakeLen){

            x=snakex[i];

            y=snakey[i];

            x*=sqs;

            y*=sqs;

            x+=wall;

            y+=wall;

            currSnakePainter.paintSnakeSquare(x, y);

            //g.fillOval(x,y, sqs,sqs);

            //g.fillRect(x,y, sqs,sqs);

            //g.drawRect(x,y, sqs,sqs);

            //g.drawOval(x,y, sqs,sqs);

            ++i;

        }

        

        g.setColor(Color.red);

        g.fillRect(wall+applei*sqs, wall+applej*sqs, sqs,sqs);

        

        i=0;

        x=snakex[i];

        y=snakey[i];

        x*=sqs;

        y*=sqs;

        x+=sqs/2;

        y+=sqs/2;

        x+=wall;

        y+=wall;

        int xn=x+dirs[headDir][0]*sqs;

        int yn=y+dirs[headDir][1]*sqs;

        g.drawLine(x,y,xn,yn);

        

        

        if(lost){

            g.setColor(Color.RED);

            g.drawLine(0,0,1000,1000);

        }

        g.setColor(Color.green);

        g.drawString("Remains = "+availables,1,bigFont.getSize());

        if(won){

            g.setColor(Color.MAGENTA);

            g.translate((cols/2)*sqs, (rows/2)*sqs);

            g.rotate(theta);theta+=Math.toRadians(10);

            g.drawString("You won ",0,0);

        }

    }

    double theta=0;


    @Override

    public void mouseClicked(MouseEvent e) {

    }


    @Override

    public void mousePressed(MouseEvent e) {

        jpPaint.requestFocusInWindow();

    }


    @Override

    public void mouseReleased(MouseEvent e) {

    }


    @Override

    public void mouseEntered(MouseEvent e) {

    }


    @Override

    public void mouseExited(MouseEvent e) {

    }


    @Override

    public void keyTyped(KeyEvent e) {

    }


    @Override

    public void keyPressed(KeyEvent e) {

        int kc=e.getKeyCode();

        if((kc==KeyEvent.VK_UP||kc==KeyEvent.VK_W) && headDir!=dirDown){

            //System.out.println("up");

            setDir(dirUp);            

        }

        else if((kc==KeyEvent.VK_DOWN||kc==KeyEvent.VK_S) && headDir!=dirUp){

            //System.out.println("down");

            setDir(dirDown);

            

        }

        else if((kc==KeyEvent.VK_LEFT||kc==KeyEvent.VK_A) && headDir!=dirRight){

            //System.out.println("left");

            setDir(dirLeft);

            

        }

        else if((kc==KeyEvent.VK_RIGHT||kc==KeyEvent.VK_D) && headDir!=dirLeft){

            //System.out.println("right");

            setDir(dirRight);

            

        }

        else if(kc==KeyEvent.VK_ENTER){

            jbRestart();

        }

        else if(kc==KeyEvent.VK_P){

            jbRestartHalf();

        }

        else if(kc==KeyEvent.VK_Y){

            decreaseSpeed();

        }

        else if(kc==KeyEvent.VK_U){

            increaseSpeed();

        }

        else if(kc==KeyEvent.VK_G){

            decreaseRowsCols();

        }

        else if(kc==KeyEvent.VK_H){

            increaseRowsCols();

        }

        else if(kc==KeyEvent.VK_L){

            lost=false;

        }

        else if(kc==KeyEvent.VK_R){

            colSnake=randColor();

        }

        else if(kc==KeyEvent.VK_T){

            nextSnakePaintType();

        }

    }


    @Override

    public void keyReleased(KeyEvent e) {

    }


    @Override

    public void componentResized(ComponentEvent e) {

        int fitsrows=(jpPaint.getHeight()-wall*2)/(rows);

        int fitscols=(jpPaint.getWidth()-wall*2)/(cols);

        sqs=Math.min(fitscols, fitsrows);

        jpPaint.repaint();

    }


    @Override

    public void componentMoved(ComponentEvent e) {

    }


    @Override

    public void componentShown(ComponentEvent e) {

    }


    @Override

    public void componentHidden(ComponentEvent e) {

    }

    

    

    

    


}


Παρασκευή 30 Σεπτεμβρίου 2022

Java Compiler001 not yet ready !! heheheh

 

paste,compile,run and read















/*

 * 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 javacompiler001;


import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Component;

import java.awt.Cursor;

import java.awt.Dimension;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.GridLayout;

import java.awt.LayoutManager;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.ComponentListener;

import java.awt.event.ContainerListener;

import java.awt.event.FocusListener;

import java.awt.event.HierarchyBoundsListener;

import java.awt.event.HierarchyListener;

import java.awt.event.InputMethodListener;

import java.awt.event.KeyListener;

import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

import java.awt.event.MouseWheelListener;

import java.awt.image.BufferedImage;

import java.beans.PropertyChangeListener;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.Enumeration;

import java.util.Hashtable;

import java.util.StringTokenizer;

import java.util.Vector;

import javax.swing.JComponent;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.JSplitPane;

import javax.swing.JTabbedPane;

import javax.swing.JTextArea;

import javax.swing.JTree;

import javax.swing.SwingUtilities;

import javax.swing.event.AncestorListener;

import javax.swing.event.TreeSelectionEvent;

import javax.swing.event.TreeSelectionListener;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;

import javax.swing.tree.TreePath;


/**

 *

 * @author jimak

 */

public class JavaCompiler001 extends Jp implements TreeSelectionListener{


    /**

     * @param args the command line arguments

     */

    public static void main(String[] args) {

        // TODO code application logic here

        JavaCompiler001 test=new JavaCompiler001();


        

    }

    static Dimension scr=Toolkit.getDefaultToolkit().getScreenSize();

    public static JFrame njfr(Component c){

        JFrame out=new JFrame();

        out.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        out.setBounds(0,0,scr.width/2,scr.height/2);

        out.getContentPane().add(BorderLayout.CENTER,c);

        out.setVisible(true);

        return out;

    }

    

    JFileChooser jfch=new JFileChooser();

    JMenuBar jmb=new JMenuBar();

    JMenuItem jmiOpenFile=new JMenuItem("Open File");

    

    

    Dmtn openedView=new Dmtn("openedView");

    DefaultTreeModel openedModel=new DefaultTreeModel(openedView);

    JTree openedJtr=new JTree(openedModel);

    JScrollPane openedJscr=new JScrollPane(openedJtr);

    

    

    KlassLoader packView=new KlassLoader("packView");

    DefaultTreeModel packModel=new DefaultTreeModel(packView);

    JTree packJtr=new JTree(packModel);

    JScrollPane packJscr=new JScrollPane(packJtr);

    

    Dmtn extView=new Dmtn("extView");

    DefaultTreeModel extModel=new DefaultTreeModel(extView);

    JTree extJtr=new JTree(extModel);

    JScrollPane extJscr=new JScrollPane(extJtr);

    

    JSplitPane jsplPackExt=new JSplitPane(0,packJscr,extJscr);

    JSplitPane jsplOpened=new JSplitPane(0,openedJscr,jsplPackExt);

    

    

    

    

    

    

    

    JTextArea jtaViewClassOriginal=new JTextArea();

    JScrollPane jscrViewClassOriginal=new JScrollPane(jtaViewClassOriginal);

    Jp jpViewClassOriginal=new Jp();

    Jp jpViewClassOriginalHolder=new Jp(new JLabel("ViewClassOriginal"),0,jscrViewClassOriginal,2);

    

    JTextArea jtaNoComments=new JTextArea();

    JScrollPane jscrNoComments=new JScrollPane(jtaNoComments);

    Jp jpNoComments=new Jp();

    Jp jpNoCommentsHolder=new Jp(new JLabel("NoComments"),0,jscrNoComments,2);

    

    JTextArea jtaOneSpacePerMultiSpacesTabsLines=new JTextArea();

    JScrollPane jscrOneSpacePerMultiSpacesTabsLines=new JScrollPane(jtaOneSpacePerMultiSpacesTabsLines);

    Jp jpOneSpacePerMultiSpacesTabsLines=new Jp();

    Jp jpOneSpacePerMultiSpacesTabsLinesHolder=new Jp(new JLabel("OneSpacePerMultiSpacesTabsLines"),0,jscrOneSpacePerMultiSpacesTabsLines,2);

    

    

    

    JTree jtrBlocks=new JTree();

    JScrollPane jtrBlocksJscr=new JScrollPane(jtrBlocks);

    Jp jpBlocks=new Jp(jtrBlocksJscr);

    Jp jpBlocksHolder=new Jp(new JLabel("Blocks"),0,jpBlocks,2);

    

    JTabbedPane jtpViewClass=new JTabbedPane();

    

    

    JSplitPane jsplMain=new JSplitPane(1,jsplOpened,jtpViewClass);

    

    JFrame jfr=null;

    

    public JavaCompiler001() {

        super();

        

        jsplMain.setResizeWeight(0.5);

        jsplOpened.setResizeWeight(0.5);

        jsplPackExt.setResizeWeight(0.5);

        

        

        jtpViewClass.addTab("0", jpViewClassOriginalHolder);

        jtpViewClass.addTab("1", jpNoCommentsHolder);

        jtpViewClass.addTab("2", jpOneSpacePerMultiSpacesTabsLinesHolder);

        jtpViewClass.addTab("3", jpBlocksHolder);

    

        jtpViewClass.setSelectedIndex(3);

        

        cad(jsplMain);

        

        jfch.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        jmb.add(jmiOpenFile);

        nad(jmb);

        

        

        jmiOpenFile.addActionListener(e->jmiOpenFile(e));

        openedJtr.addTreeSelectionListener(this);

        

        //null params means open private frame

        jfr=njfr(this);

        jfr.setTitle("Trying to learn compiling java files");

    

    }


    void jmiOpenFile(ActionEvent e){

        int apro=jfch.showOpenDialog(this);

        if(apro==JFileChooser.APPROVE_OPTION){

            openFile(jfch.getSelectedFile());

        }

    }

    public void openFile(File f){

        if(f!=null){

            if(jfr!=null){jfr.setTitle("Start reading "+f.getName());}

            Vector<FileSrcClass> newLoads=new Vector<>();

            openingFiles(f,newLoads);

            int newLoadsCount=newLoads.size();

            if(newLoadsCount>0){

                openedJtr.setSelectionPath(newLoads.get(0).ntp());

                System.out.println("Now ...just filling some imports ....and stop writing code for today....(because next is difficult!)");

                int newImports=0;

                int pendingImports=0;

                int totalImports=0;

                int newUserClasses=0;

                int pendingUserClasses=0;

                int i=0;

                while(i<newLoadsCount){

                    FileSrcClass fsc=newLoads.get(i);

                    

                    int importsCount=fsc.vImports.getChildCount();

                    if(importsCount>0){

                        int imi=0;

                        while(imi<importsCount){

                            Dmtn importNode=fsc.vImports.dmtn(imi);

                            String imps=importNode.getUserString();

                            try{

                                Class cl=Class.forName(imps);

                                Klass klimp=new Klass(cl);

                                Klass klFound=packView.loadKlass(klimp);

                                if(klimp==klFound){

                                    importNode.crad(klimp);//to remember if want after

                                    openedModel.nodeStructureChanged(importNode);

                                    packModel.nodeStructureChanged((Dmtn)klFound.dyn.getUserObject());

                                    ++newImports;

                                }

                                else{

                                    //System.out.println("already loaded import thing");

                                    ++totalImports;

                                }

                                

                            }catch(ClassNotFoundException cnfe){

                                ++pendingImports;

                            }

                            ++imi;

                        }

                    }

                    

                    

                    int classesCount=fsc.vClasses.getChildCount();

                    if(classesCount>0){

                        String pack="";

                        if(fsc.vPacks.getChildCount()>0){

                            pack=fsc.vPacks.dmtn(0).getUserString();

                        }

                        int cci=0;

                        while(cci<classesCount){

                            Dmtn clno=fsc.vClasses.dmtn(cci);

                            Klass kl=new Klass(clno.getUserString(), pack);

                            Klass klFound=packView.loadKlass(kl);

                            if(kl==klFound){

                                clno.crad(klFound);//to remember if want after

                                openedModel.nodeStructureChanged(clno);

                                packModel.nodeStructureChanged((Dmtn)klFound.dyn.getUserObject());

                                ++newUserClasses;

                            }

                            else{

                                //System.out.println("Already have this???? "+kl.getNameJava());

                                ++pendingUserClasses;

                            }

                            ++cci;

                        }

                    }

                    

                    ++i;

                }

                

                packModel.nodeStructureChanged(packView);

                JOptionPane.showMessageDialog(this,"Java Files read : "+newLoadsCount

                        + "\nnew Imports (from jdk) : "+newImports+" / "+totalImports+" totals"

                        + "\npending imports (from user or errors) :"+pendingImports

                        + "\n\n"

                        + "\nnew UserClasses on packView :"+newUserClasses

                        + "\nreacalled user classes :"+pendingUserClasses

                        + "\n"

                        + "\n\n...To be a real compiler we want too much work !!! (from Ockt 2022!)"

                ,"jimakoskx.blogspot/hotmail.com",JOptionPane.INFORMATION_MESSAGE);

                

            }

            else{

                JOptionPane.showMessageDialog(this, "Sorry,,couldnt found any .java File to read");

            }

        }

    }

    private void openingFiles(File f,Vector<FileSrcClass> newLoads){

        if(f!=null){

            if(f.isDirectory()){

                File fs[]=f.listFiles();

                if(fs!=null){

                    int i=0;

                    while(i<fs.length){

                        openingFiles(fs[i],newLoads);

                        ++i;

                    }

                }

            }

            else{

                String fname=f.getName();

                int ind=fname.lastIndexOf(".java");

                if(ind>-1){

                    openingJavaFile(f,newLoads);

                }

            }

        }

    }

    

    private void openingJavaFile(File f,Vector<FileSrcClass> newLoads){

        if(f!=null){

            if(jfr!=null){jfr.setTitle("Start reading "+f.getName());}

            //System.out.println(""+f);

            FileSrcClass newSrc=new FileSrcClass(f);

            newLoads.add(newSrc);

            newSrc.readFileBuffer();

            newSrc.parseFile();

            openedView.add(newSrc);

            openedModel.nodeStructureChanged(openedView);

        }

    }

    

    private void viewResultsOf(FileSrcClass fsc){

        jtaViewClassOriginal.setText(fsc.sb.toString());

        jtaNoComments.setText(fsc.sbNoComments.toString());

        jtaOneSpacePerMultiSpacesTabsLines.setText(fsc.sbNoLinesNoSpacesNoTabsOutOfStrings.toString());

        jtrBlocks.setModel(new DefaultTreeModel(fsc.blocks));

    }


    @Override

    public void valueChanged(TreeSelectionEvent e) {

        TreePath tp=e.getNewLeadSelectionPath();

        if(tp!=null){

            Object lpc=tp.getLastPathComponent();

            Object src=e.getSource();

            if(src==openedJtr){

                if(lpc instanceof FileSrcClass){

                    viewResultsOf((FileSrcClass)lpc);

                }

            }

        }

    }

    

    

    


    

    

    

    

    

    

}



class FileSrcClass extends Dmtn{


    

    public static final String strPackage="package";

    public static final String strImport="import";

    public static final String strClass="class";

    public static final String strExtends="extends";

    public static final String strImplements="implements";

    public static String searchForImport(String lineok){

        String out=null;

        lineok=lineok.trim();//no space or tabs

        int ind=lineok.indexOf(strImport);

        if(ind==0){

            int after=strImport.length()+1;

            int inder=lineok.indexOf(";",after);

            if(inder>after){//[package a;]

                String possible=lineok.substring(after,inder).trim();

                String maybeWithStar=possible;

                if(possible.endsWith("*")){

                    possible=possible.substring(0,possible.length()-1);

                }

                if(isJavaIdentifierFullClassName(possible)){

                    out=maybeWithStar;

                }

            }

        }

        return out;

    }

    public static String searchForPackage(String lineok){

        String out=null;

        lineok=lineok.trim();//no space or tabs

        int ind=lineok.indexOf(strPackage);

        if(ind==0){

            int after=strPackage.length()+1;

            int inder=lineok.indexOf(";",after);

            if(inder>after){//[package a;]

                String possible=lineok.substring(after,inder).trim();

                if(isJavaIdentifierFullClassName(possible)){

                    out=possible;

                }

            }

        }

        return out;

    }


    /**

     * will return a node with simpleclassname as userobject

     * <br> that will have 

     * <br>first child with 0.length or extendeing class string

     * <br>second child with 0.length or implementing classes with komma 

     */

    public static Dmtn searchForClass(String lineok){

        Dmtn out=null;

        lineok=lineok.trim();//no space or tabs

        int ind=lineok.indexOf(strClass);

        if(ind>-1){

            int extind=lineok.indexOf(strExtends);

            int implind=lineok.indexOf(strImplements);

            int agiind=lineok.indexOf("{");

            int end=lineok.length();

            if(extind>-1){end=extind;}

            else if(implind>-1){end=implind;}

            else if(agiind>-1){end=agiind;}

            String possible=lineok.substring(ind+strClass.length(),end).trim();

            //System.out.println("possible class : "+possible);

            if(isJavaIdentifierSimpleClassName(possible)){

                out=new Dmtn(possible);

                Dmtn outExt=out.crad("");

                Dmtn outImpls=out.crad("");

                

                

                if(extind>-1){

                    end=lineok.length();

                    if(implind>-1){end=implind;}

                    else if(agiind>-1){end=agiind;}

                    String extMaybe=lineok.substring(extind+strExtends.length(),end).trim();

                    if(isJavaIdentifierFullClassName(extMaybe)){

                        outExt.setUserObject(extMaybe);

                    }

                    else{

                        outExt.setUserObject("?"+extMaybe);

                    }

                }

                

            }

            

        }

        return out;

    }

    

    public static boolean isJavaIdentifierSimpleClassName(String s){

        return isJavaIdentifier(s, false);

    }

    public static boolean isJavaIdentifierFullClassName(String s){

        return isJavaIdentifier(s, true);

    }

    public static boolean isJavaIdentifier(String s,boolean dotAllowed){

        int l=s.length();

        //if(l==0){return false;}

        int i=0;

        char ch;

        boolean prevdot=true;

        while(i<l){

            ch=s.charAt(i);

            if(prevdot && !Character.isJavaIdentifierStart(ch)){

                return false;

            }


            if(!Character.isJavaIdentifierPart(ch)){

                if(ch!='.' || !dotAllowed || prevdot){

                    return false;

                }

                prevdot=true;

            }

            else{

                prevdot=false;

            }

            ++i;

        }

        return !prevdot;

    }

    

    File fsrc;

    StringBuffer sb=new StringBuffer();

    StringBuffer sbNoComments=new StringBuffer();

    StringBuffer sbNoLinesNoSpacesNoTabsOutOfStrings=new StringBuffer();

    

    Dmtn blocks=new Dmtn();

    

    Dmtn vPacks=new Dmtn("packages");

    Dmtn vImports=new Dmtn("imports");

    Dmtn vClasses=new Dmtn("classes");

    public FileSrcClass(File f){

        super(f);

        fsrc=f;

        add(vPacks);

        add(vImports);

        add(vClasses);

    }

    static int counter=0;

    public FileSrcClass(String textOfSomeFile){

        super(new File("testFileData"+(counter++)));

        fsrc=null;

        add(vPacks);

        add(vImports);

        add(vClasses);

        sb.append(textOfSomeFile);

    }

    void readFileBuffer(){

        sb.delete(0, sb.length());

        FileInputStream fin=null;

        try{

            fin=new FileInputStream(fsrc);

            int reads=fin.read();

            while(reads>-1){

                sb.append((char)reads);

                reads=fin.read();

            }

            fin.close();

            fin=null;

        }catch(IOException io){

            io.printStackTrace();

        }

        if(fin!=null){

            try{fin.close();}catch(IOException io){}

        }        

        //readFileBuffer();

        //System.out.println(sb);

    }

    

    void parseFile(){

        

        

        


        parseNoCommentsBuffer();

        //System.out.println(sbNoComments);

        parseNoLinesNoSpacesNoTabsOutOfStringsBuffer();

        //System.out.println(""+sbNoLinesNoSpacesNoTabsOutOfStrings);

        parseBlocks();

        //new Jfr(new Jtr(blocks).jscr());

        vPacks.removeAllChildren();

        vImports.removeAllChildren();

        vClasses.removeAllChildren();

        

        int i=0;

        int l=blocks.getChildCount();

        boolean searchImport=true,searchClass=true;

        String bls;

        while(i<l){

            Dmtn bl=blocks.dmtn(i);

            bls=bl.getUserString();

            searchImport=true;

            searchClass=true;

            if(vPacks.getChildCount()==0){

                String packMaybe=searchForPackage(bls);

                if(packMaybe!=null){

                    vPacks.crad(packMaybe);

                    searchImport=false;

                    searchClass=false;

                }

            }

            if(searchImport){// && vClasses.getChildCount()==0){

                String importMaybe=searchForImport(bls);

                if(importMaybe!=null){

                    vImports.crad(importMaybe);

                    searchClass=false;

                }

            }

            if(searchClass){

                Dmtn classMaybe=searchForClass(bls);

                if(classMaybe!=null){

                    vClasses.add(classMaybe);

                }

            }

            

            ++i;

        }

        

    }

    int readBlocksErrorsUnknown=0;

    void parseBlocks(){

        blocks.removeAllChildren();

        blocks.setUserObject("");

        Dmtn it=blocks.crad("");

        int i=0,l=sbNoLinesNoSpacesNoTabsOutOfStrings.length();

        char ch;

        String buf="";

        boolean outOfString=true;

        while(i<l){

            ch=sbNoLinesNoSpacesNoTabsOutOfStrings.charAt(i);

            if(ch=='\"' && !(i>0 && sbNoComments.charAt(i-1)=='\\')){

                outOfString=!outOfString;

            }

            if(outOfString){

            

                if(ch==';'){

                    buf+=ch;

                    it.setUserObject(buf);

                    buf="";

                    Dmtn nn=it.dmtnPar().crad(buf);

                    it=nn;


                }

                else if(ch=='{'){

                    buf+=ch;

                    it.setUserObject(buf);

                    buf="";

                    Dmtn nn=it.crad(buf);

                    it=nn;


                }

                else if(ch=='}'){

                    //buf+=ch;

                    it.setUserObject(buf);


                    it=it.dmtnPar();

                    while(it!=null && !it.getUserString().endsWith("{")){

                        it=it.dmtnPar();

                    }

                    if(it==null){

                        System.out.println("error at "+fsrc);

                        ++readBlocksErrorsUnknown;

                        return;

                    }

                    buf=it.getUserString()+"}";

                    it.setUserObject(buf);

                    buf="";

                    it=it.dmtnPar().crad(buf);

                }

                else{buf+=ch;}

            }else{buf+=ch;}

            ++i;

        }

    }


    void parseNoCommentsBuffer(){

        sbNoComments.delete(0, sbNoComments.length());

        int i=0;

        int l=sb.length();

        char ch;

        while(i<l){

            ch=sb.charAt(i);

            if(ch=='/' && (i+1<l)){

                int nexti=i+1;

                char nextch=sb.charAt(nexti);

                if(nextch=='/'){

                    //System.out.println("skipping till end of line");

                    i=nexti+1;

                    while(i<l){

                        ch=sb.charAt(i);

                        if(ch=='\n'){

                            break;

                        }

                        ++i;

                    }

                    --i;

                }

                else if(nextch=='*'){

                    //System.out.println("skipping util next */");

                    i=nexti+2;

                    while(i<l){

                        ch=sb.charAt(i);

                        if(ch=='/' && sb.charAt(i-1)=='*'){

                            break;

                        }

                        ++i;

                    }

                }

                else{

                    sbNoComments.append(ch);

                }

            }

            else{

                sbNoComments.append(ch);

            }

            

            ++i;

        }

        

    }

    

    void parseNoLinesNoSpacesNoTabsOutOfStringsBuffer(){

        sbNoLinesNoSpacesNoTabsOutOfStrings.delete(0, sbNoLinesNoSpacesNoTabsOutOfStrings.length());

        int i=0;

        int l=sbNoComments.length();

        char ch;

        boolean prevSLT=false;

        boolean outOfString=true;

        while(i<l){

            ch=sbNoComments.charAt(i);

            if(ch=='\"' && !(i>0 && sbNoComments.charAt(i-1)=='\\')){

                outOfString=!outOfString;

            }

            if(outOfString&&(ch==' '||ch=='\n'||ch=='\t')){

                if(prevSLT){

                    //System.out.println("skipping");

                    ++i;

                    while(i<l){

                        ch=sbNoComments.charAt(i);

                        if(!(ch==' '||ch=='\n'||ch=='\t')){

                            break;

                        }

                        ++i;

                    }

                    prevSLT=false;

                    --i;

                }

                else{

                    //put space if space or line or tab....

                    sbNoLinesNoSpacesNoTabsOutOfStrings.append(' ');

                    prevSLT=true;

                }

            }

            else{

                sbNoLinesNoSpacesNoTabsOutOfStrings.append(ch);

                prevSLT=false;

            }

            

            ++i;

        }

        

    }

    

    

    

    

    

    

    

    

    

    

    

    

    

    

    

    void analyseLine(String line){

        if(line!=null){

            int linelen=line.length();

            if(linelen>6){//[class A]

                if(vPacks.getChildCount()==0){

                    String packfoundnow=searchForPackage(line);

                    if(packfoundnow!=null){

                        vPacks.crad(packfoundnow);

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

                        return;

                    }

                }

                //continue search for import 

            }

        }

        String test="a                                       b";

    }

    

}///end class



class KlassLoader extends Dmtn{

    

    Hashtable<String, Klass> NameJavaToKlass=new Hashtable<>();


    public KlassLoader() {

    }


    public KlassLoader(Object userObject) {

        super(userObject);

    }

    

    

    

    

    public boolean hasKlass(Class cl){

        return hasKlass(new Klass(cl));

    }

    public boolean hasKlass(Klass kl){

        return hasKlass(kl.getNameJava());

    }

    public boolean hasKlass(String NameJava){

        return NameJavaToKlass.get(NameJava)!=null;

    }

    public Klass loadKlass(Klass kl){

        String NameJava=kl.getNameJava();

        Klass found=NameJavaToKlass.get(NameJava);

        if(found!=null){

            return found;

        }

        return loadingKlass(kl, NameJava);

    }

    public Klass loadKlass(Class cl){

        return loadKlass(new Klass(cl));

    }

    

    

    

    private Klass loadingKlass(Klass kl,String NameJava){

        NameJavaToKlass.put(NameJava, kl);

        Dmtn klassPackView=sbadDeep(new StringTokenizer(NameJava,"."));

        klassPackView.dyn=new Dmtn(kl);

        kl.dyn=new Dmtn(klassPackView);

        return kl;

    }


}

class Klass extends Dmtn{

    Class clfor;

    Klass(Class cl){

        super();

        clfor=cl;

    }

    String sn="",pn="";

    Klass(String simpleName,String packageName){

        super();

        sn=simpleName;

        pn=packageName;

    }

    

    

    public String getName(){

        String out="";

        if(clfor!=null){

            out=clfor.getName();

        }

        else{

            if(pn.length()>0){

                out=pn+"."+sn;

            }

            else{

                out=sn;

            }

        }

        return out;

    }

    public String getNameJava(){

        return getName()+"~";

    }

    public String getSimpleName(){

        String out="";

        if(clfor!=null){

            out=clfor.getSimpleName();

        }

        else{

            out=sn;

        }

        return out;

    }

    public String getSimpleNameJava(){

        return getSimpleName()+"~";

    }

    

    public String getPackageName(){

        String out="";

        if(clfor!=null){

            Package pack=clfor.getPackage();

            if(pack!=null){

                out=clfor.getPackage().getName();

            }

        }

        else{

            out=pn;

        }

        return out;

    }

    


}



class Dmtn extends DefaultMutableTreeNode{

    /**

     * This 'dyn'amic data field is for programmer purposes

     * <br>A private field for programmer used in many cases

     * <br>Many of this cases is for search/and add methods

     * <br>like sbad

     * <br>if sbad finds the node

     * <br> we can know if its ours if we just check

     * <br>DmtnNode mynew=new Dmtn("basicsearch/order key")

     * <br>if(root.sbad(mynew).dyn!=null) say(Already exists)

     * <br>else mynew.dyn=new Dmtn(with all my app spesific data)

     * <br>with just 2 lines of code

     * <br>-----

     * <br>

     */

    public Dmtn dyn=null;

    /**

     * constructs the dyn(uoOfDyn)

     * @param uoOfDyn

     * @return this

     */

    public Dmtn qdyno(Object uoOfDyn){

        dyn=new Dmtn(uoOfDyn);

        return this;

    }   

    /**

     * Assigns to dyn

     * @param dynToBeAssigned

     * @return this

     */

    public Dmtn qdyn(Dmtn dynToBeAssigned){

        dyn=dynToBeAssigned;

        return this;

    }   


    public Dmtn() {

    }


    public Dmtn(Object userObject) {

        super(userObject);

    }


    public Dmtn(Object userObject, boolean allowsChildren) {

        super(userObject, allowsChildren);

    }

    public String getUserString(){

        return userObject+"";

    }

    

    public Dmtn cr(){

        return new Dmtn();

    }

    /**

     * Will be use from crad

     * <br>Not yet decide 

     * if must use setObject(uo) or protected userObject=uo

     * @param uo

     * @return 

     */

    public Dmtn cr(Object uo){

        Dmtn out=cr();

        out.setUserObject(uo);//or this?

        //out.userObject=uo;//or this?

        return out;

    }

    /**

     * @param uo

     * @return the new child 

     */

    public Dmtn crad(Object uo){

        Dmtn out=cr(uo);

        add(out);

        return out;

    }

    /**

     * Create and adds a new child

     * @param uo

     * @return this to be used continiuslly if need

     */

    public Dmtn cradThis(Object uo){

        crad(uo);

        return this;

    }

    /**

     * 

     * @param uo

     * @param index

     * @return the new child inserted 

     */

    public Dmtn crin(Object uo,int index){

        Dmtn out=cr(uo);

        insert(out,index);

        return out;

    }

    /**

     * 

     * @param uo

     * @param index

     * @return this

     */

    public Dmtn crinThis(Object uo,int index){

        crin(uo,index);

        return this;

    }

    

    

    

    

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

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

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

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

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

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

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

    /**

     * 

     * @param index

     * @return (Dmtn)getChildAt(index)

     */

    public Dmtn dmtn(int index){

        return (Dmtn)getChildAt(index);

    }

    

    public Dmtn dmtnLast(){

        return dmtn(getChildCount()-1);

    }

    

    

    

    public TreePath ntp(){return new TreePath(getPath());}

     /**

     * 

     * @return this or the last parent 

     */

    public Dmtn dmtnRoot(){

        Dmtn out=this;

        Dmtn parit=out.dmtnPar();

        while(parit!=null){

            out=parit;

            parit=out.dmtnPar();

        }

        return out;

    }

    

    

    public Dmtn dmtnPar(){return (Dmtn)parent;}

    public Dmtn qtoparadd(Dmtn parentToBeAdded){parentToBeAdded.add(this);return this;}

    

    public Dmtn firstDmtnAssignableUp(Class cl){

        Dmtn it=this;

        while(it!=null){

            if(cl.isAssignableFrom(it.getClass())){

                return (Dmtn)it;

            }

            it=(Dmtn)it.parent;

        }

        return null;

    }

    /**

     * @param index

     * @return ++index;index=-index;

     */

    public static int sbdecode(int index){++index;index=-index;return index;}

    /**

     * @param index

     * @return index=-index;--index;

     */

    public static int sbencode(int index){index=-index;--index;return index;}

    

    /**

     * 

     * @param toCompare

     * @return index founde OR 

     * <br>the negative-1 insertion position

     * <br> if(sbi()<0){no Found and we can insert at -(++sbi)}

     * <br> else found on position sbi

     */

    public int sbi(Comparable toCompare){

        int lo = 0,hi = getChildCount() - 1,mid,d;Dmtn it;

        while (lo <= hi) {mid = lo + (hi - lo) / 2;

            it=(Dmtn)getChildAt(mid);

            d=toCompare.compareTo(it.userObject);

            if(d<0){ hi = mid - 1;}

            else if (d>0){lo = mid + 1;}

            else {return mid;}

        }return sbencode(lo);

    }

    /**

     * @param toCompare

     * @return the founded or null

     */

    public Dmtn sbn(Comparable toCompare){

        int index=sbi(toCompare);

        if(index>-1){

            return dmtn(index);

        }

        return null;

    }

    public Dmtn sbad(Comparable findOrAdd){

        int foundAt=sbi(findOrAdd);

        if(foundAt<0){return crin(findOrAdd, sbdecode(foundAt));}

        else{return dmtn(foundAt);}

    }

    public Dmtn sbadDeep(Enumeration en){

        Dmtn out=this;

        while(en.hasMoreElements()){

            out=out.sbad((Comparable)en.nextElement());

        }

        return out;

    }

    


    public Dmtn sbadAllowEquals(Comparable findOrAdd){

        int foundAt=sbi(findOrAdd);

        if(foundAt<0){return crin(findOrAdd, sbdecode(foundAt));}

        else{

            return dmtn(foundAt).crad(findOrAdd);

        }

    }


}









class Jp extends javax.swing.JPanel{


    public static Object bl(int code04){

        if(code04<1){return BorderLayout.NORTH;}

        else if(code04<2){return BorderLayout.WEST;}

        else if(code04<3){return BorderLayout.CENTER;}

        else if(code04<4){return BorderLayout.EAST;}

        return BorderLayout.SOUTH;

    }

    

    public void pushWest(JComponent ccFreeClientPropsBorderLayoutClass){

        pushBordered(1,ccFreeClientPropsBorderLayoutClass);

    }

    public void pushEast(JComponent ccFreeClientPropsBorderLayoutClass){

        pushBordered(3,ccFreeClientPropsBorderLayoutClass);

    }

    public void pushBordered(Integer bl0134,JComponent ccFreeClientPropsBorderLayoutClass){

        int i=0;

        JComponent foundWithPropertyAtWest=null;

        Component comps[]=getComponents();

        while(i<comps.length){

            if(comps[i] instanceof JComponent){

                JComponent jc=(JComponent)comps[i];

                Object prop=jc.getClientProperty(BorderLayout.class);

                if(bl0134.equals(prop)){foundWithPropertyAtWest=jc;break;}

            }

            ++i;

        }

        if(foundWithPropertyAtWest!=null){

            if(foundWithPropertyAtWest instanceof Jp){

                ((Jp)foundWithPropertyAtWest).pushBordered(bl0134,ccFreeClientPropsBorderLayoutClass);

            }

            else{

                //SOS...the new comp will have centerized property

                ccFreeClientPropsBorderLayoutClass.putClientProperty(BorderLayout.class, 2);

                //the old will remain at ?west?-bl0134

                remove(foundWithPropertyAtWest);

                Jp jpnew=new Jp(foundWithPropertyAtWest,bl0134,ccFreeClientPropsBorderLayoutClass,2);

                jpnew.putClientProperty(BorderLayout.class, bl0134);

                blad(jpnew,bl0134);

            }

        }

        else{

            ccFreeClientPropsBorderLayoutClass.putClientProperty(BorderLayout.class, bl0134);

            blad(ccFreeClientPropsBorderLayoutClass,bl0134);

        }

        valful();

    }


    @Override

    public String toString() {

        String out=super.toString();

        String name=getName();

        if(name!=null){

            out=name;

        }

        return out;

    }

    

    /**

     * 'private' field to be used on possible event handlers

     */

    public boolean isAdjusting=false;

    

    

    

   

    

    public JScrollPane jscr;

    public JScrollPane jscr(){

        if(jscr==null){

            jscr=new JScrollPane(this);

            revalidate();

            repaint();

        }

        return jscr;

    }

    

    //general purpose

    public Dmtn pro=null;

    public Jp qpro(Dmtn some){pro = some;return this;}

    

    public BufferedImage takePhoto(){

        BufferedImage bim=new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_ARGB);

        Graphics2D g=bim.createGraphics();

        //g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f));

        paintAll(g);

        g.dispose();

        return bim;

    }


    

    


    public Jp(LayoutManager layout, boolean isDoubleBuffered) {

        super(layout, isDoubleBuffered);

    }


    public Jp(LayoutManager layout) {

        super(layout);

    }


    public Jp(boolean isDoubleBuffered) {

        super(isDoubleBuffered);

    }


    

    public Jp() {

        super(new BorderLayout());

    }

    public Jp(Component centered){

        this(centered,2);

    }

    public Jp(Component ca,int a){

        this();

        super.add(ca,bl(a));

    }

    

    public Jp(Component ca,int a,Component cb,int b){

        this(ca,a);

        super.add(cb,bl(b));

    }

    public Jp(Component ca,int a,Component cb,int b,Component cc,int c){

        this(ca,a,cb,b);

        super.add(cc,bl(c));

    }

    public Jp(Component ca,int a,Component cb,int b,Component cc,int c,Component cd,int d){

        this(ca,a,cb,b,cc,c);

        super.add(cd,bl(d));

    }

    public Jp(Component ca,int a,Component cb,int b,Component cc,int c,Component cd,int d,Component ce,int e){

        this(ca,a,cb,b,cc,c,cd,d);

        super.add(ce,bl(e));

    }


    


    public Jp qaddto(Jp jpanel){

        jpanel.add(this);

        return this;

    }

    

    

    public void blad(Component c,int pos){

        add(c,bl(pos));

        validate();

        repaint();

    }

    public void nad(Component c){ blad(c,0); }

    public void wad(Component c){ blad(c,1); }

    public void cad(Component c){ blad(c,2); }

    public void ead(Component c){ blad(c,3); }

    public void sad(Component c){ blad(c,4); }

    

    

    

    

    

    

    

    

    

    public Jp(int rows,int cols){

        super(new GridLayout(rows, cols));

    }

    public Jp(int rows,int cols,Component c0){

        this(rows, cols);

        add(c0);

    }

    public Jp(int rows,int cols,Component c0,Component c1){

        this(rows, cols);

        add(c0);add(c1);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2){

        this(rows, cols);

        add(c0);add(c1);add(c2);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3,Component c4){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);add(c4);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3,Component c4,Component c5){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);add(c4);add(c5);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3,Component c4,Component c5,Component c6){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);add(c4);add(c5);add(c6);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3,Component c4,Component c5,Component c6,Component c7){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);add(c4);add(c5);add(c6);add(c7);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3,Component c4,Component c5,Component c6,Component c7,Component c8){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);add(c4);add(c5);add(c6);add(c7);add(c8);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3,Component c4,Component c5,Component c6,Component c7,Component c8,Component c9){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);add(c4);add(c5);add(c6);add(c7);add(c8);add(c9);

    }

    public Jp(int rows,int cols,Component c0,Component c1,Component c2,Component c3,Component c4,Component c5,Component c6,Component c7,Component c8,Component c9,Component c10){

        this(rows, cols);

        add(c0);add(c1);add(c2);add(c3);add(c4);add(c5);add(c6);add(c7);add(c8);add(c9);add(c10);

    }

    public void resetGridOnRows(){

        resetGrid(new GridLayout(getComponentCount(),1));

    }

    public void resetGridOnColumns(){

        resetGrid(new GridLayout(1,getComponentCount()));

    }

    public void resetGrid(int newRows,int newCols){

        resetGrid(new GridLayout(newRows, newCols));

    }

    public void resetGrid(GridLayout gl){

        setLayout(gl);

        validate();

        repaint();

    } 







    //public Jp q(ActionListener l) {super.addActionListener(l); return this; }

    public Jp q(AncestorListener l) {super.addAncestorListener(l); return this; }

    //public Jp q(ChangeListener l) {super.addChangeListener(l); return this; }

    public Jp q(ComponentListener l) {super.addComponentListener(l); return this; }

    public Jp q(ContainerListener l) {super.addContainerListener(l); return this; }

    public Jp q(FocusListener l) {super.addFocusListener(l); return this; }

    public Jp q(HierarchyBoundsListener l) {super.addHierarchyBoundsListener(l); return this; }

    public Jp q(HierarchyListener l) {super.addHierarchyListener(l); return this; }

    public Jp q(InputMethodListener l) {super.addInputMethodListener(l); return this; }

    //public Jp q(ItemListener l) {super.addItemListener(l); return this; }

    public Jp q(KeyListener l) {super.addKeyListener(l); return this;  }

    public Jp q(MouseListener l) {super.addMouseListener(l); return this;  }

    public Jp q(MouseMotionListener l) {super.addMouseMotionListener(l); return this; }

    public Jp q(MouseWheelListener l) {super.addMouseWheelListener(l); return this; }

    public Jp q(PropertyChangeListener l) {super.addPropertyChangeListener(l); return this; }




    public Jp q(Cursor cursor) {super.setCursor(cursor); return this;}

    public Jp qCursorCrossHair() {super.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); return this;}

    public Jp qCursorHand() {super.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); return this;}

    public Jp qCursorMove() {super.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); return this;}

    public Jp qCursorText() {super.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); return this;}

    public Jp qCursorWait() {super.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); return this;}

    public Jp qMax(Dimension maximumSize) {super.setMaximumSize(maximumSize); return this; }

    public Jp qMin(Dimension minimumSize) {super.setMinimumSize(minimumSize); return this; }

    public Jp qPref(Dimension preferredSize) {super.setPreferredSize(preferredSize); return this; }

    public Jp q(Font f) {super.setFont(f); return this; }

    public Jp qFont(int size) {Font f=getFont();super.setFont(new Font(f.getName(), f.getStyle(), size)); return this; }

    public Jp qb(Color c) {super.setBackground(c); return this; }

    public Jp qf(Color c) {super.setForeground(c); return this; }

    public Jp qe(boolean b) {setEnabled(b); return this; }

    public Jp qn(String name) {super.setName(name); return this;  }

    public Jp qtt(String tooltip) {super.setToolTipText(tooltip); return this;  }

    public Jp qcp(Object key,Object prop){super.putClientProperty(key, prop);return this;}

    public Object gcp(Object key){return getClientProperty(key);}

    

    

    

    public void allCompsSetEnabled(boolean enabled){

        Component comps[]=getComponents();int i=0;

        while(i<comps.length){comps[i++].setEnabled(enabled);}

    }

    

    public Jp valful(){

        validate();

        revalidate();

        invalidate();

        repaint();

        return this;

    }

    public Jp valrep(){

        validate();

        repaint();

        return this;

    }

    

    


}