레이블이 java인 게시물을 표시합니다. 모든 게시물 표시
레이블이 java인 게시물을 표시합니다. 모든 게시물 표시

2022년 4월 30일 토요일

[Java] how to embed JavaScript

Embed JavaScript (J2v8)

if( ((String)langCombo.getSelectedItem()).equalsIgnoreCase("javascript") ) {
    SwingUtilities.invokeLater(() -> {
        try {
            boolean useNodeJS = false;
            V8 v8;
            if( useNodeJS ) {
                NodeJS nodeJS = NodeJS.createNodeJS();
                v8 = nodeJS.getRuntime();
            } else {
                v8 = V8.createV8Runtime();
            }
            v8.registerJavaMethod(j8print, "write"); 
            v8.registerJavaMethod(j8println, "writeln"); 
            outputPrintLn("<START Javascript>");
            v8.executeObjectScript(textTab.getSelectedTextView().getText());
            outputPrintLn("<END Javascript>");
        } catch (Exception e) {
            e.printStackTrace();
            outputPrintLn("error\n" + e.getMessage());
        }  
    });
}  

JavaVoidCallback j8print = new JavaVoidCallback() {
  public void invoke(final V8Object receiver, final V8Array parameters) {
    if (parameters.length() > 0) {
      Object arg1 = parameters.get(0);
      outputPrint((String)arg1);
      if (arg1 instanceof Releasable) {
        ((Releasable) arg1).release();
      }
    }
  }
 };

JavaVoidCallback j8println = new JavaVoidCallback() {
    public void invoke(final V8Object receiver, final V8Array parameters) {
        if (parameters.length() > 0) {
            Object arg1 = parameters.get(0);
            outputPrintLn((String)arg1);
            if (arg1 instanceof Releasable) {
                ((Releasable) arg1).release();
            }
        }
    }
}; 

[Java] how to embed JRuby

Embed JRuby

if( ((String)langCombo.getSelectedItem()).equalsIgnoreCase("ruby") ) {
    SwingUtilities.invokeLater(() -> {
        try {
            if( rubyScript == null ) {
                rubyScript = new ScriptingContainer();
                rubyWriter = new StringWriter();
                rubyScript.setOutput(rubyWriter);
                rubyScript.runScriptlet("def write(text) print(text) end\n");
                rubyScript.runScriptlet("def writeln(text) print(text + \"\\n\") end\n");
            }
            outputPrintLn("<START Ruby>");
            rubyScript.runScriptlet(textTab.getSelectedTextView().getText());
            outputPrint(rubyWriter.toString());
            rubyWriter.getBuffer().setLength(0);
            rubyWriter.getBuffer().trimToSize();
            outputPrintLn("<END Ruby>");
        } catch (Exception e) {
            e.printStackTrace();
            outputPrintLn("error\n" + e.getMessage());
        } 
    });
}

[Java] how to embed Jython

Embed Jython

if( ((String)langCombo.getSelectedItem()).equalsIgnoreCase("python") ) {
    SwingUtilities.invokeLater(() -> {
        try {
            PythonInterpreter pythonScript;   
            System.setProperty("python.import.site","false");
            pythonScript = new PythonInterpreter();
            pythonScript.set("instance", this);
            pythonScript.exec("def write(text): instance.outputPrint(text)\n");
            pythonScript.exec("def writeln(text): instance.outputPrintLn(text)\n");
            outputPrintLn("<START Python>");
            pythonScript.exec(textTab.getSelectedTextView().getText());
            outputPrintLn("<END Python>");
        } catch (Exception e) {
            e.printStackTrace();
            outputPrintLn("error\n" + e.getMessage());
        }  
    });
}

[Java] how to embed Lua script

Embed Lua Script

if( ((String)langCombo.getSelectedItem()).equalsIgnoreCase("lua") ) {
    SwingUtilities.invokeLater(() -> {
        try {
            ScriptEngine luaScript; 
            luaScript = new ScriptEngineManager().getEngineByName("luaj");
            luaScript.put("write", new print());
            luaScript.put("writeln", new println());
            outputPrintLn("<START Lua>");
            luaScript.eval(textTab.getSelectedTextView().getText());
            outputPrintLn("<END Lua>");
        } catch (Exception e) {
            e.printStackTrace();
            outputPrintLn("error\n" + e.getMessage());
        }  
    });
}

public void outputPrint(String text) {
    SwingUtilities.invokeLater( () -> {
        output.append(text );
    });
}    

public void outputPrintLn(String text) {
    SwingUtilities.invokeLater( () -> {
        output.append(text + "\n");
    });
}
 
class print extends OneArgFunction {
    @Override
    public LuaValue call(LuaValue lv) {
        outputPrint(lv.checkstring().tojstring());
        return LuaValue.valueOf(0);
    }
}   
class println extends OneArgFunction {
    @Override
    public LuaValue call(LuaValue lv) {
        outputPrintLn(lv.checkstring().tojstring());
        return LuaValue.valueOf(0);
    }
}    

[Java] How to embed Bean Shell

Embed Bean Shell

if( ((String)langCombo.getSelectedItem()).equalsIgnoreCase("java") ) {
    SwingUtilities.invokeLater( () -> {
        try {
            bsh.Interpreter bshScript;
            bshScript = new bsh.Interpreter();
            bshScript.set("instance", this);
            bshScript.eval("void write(text) { instance.outputPrint(text); }");
            bshScript.eval("void writeln(text) { instance.outputPrintLn(text); }");
            outputPrintLn("<START Java>");
            bshScript.eval(textTab.getSelectedTextView().getText());
            outputPrintLn("<END Java>");
        } catch (Exception e) {
            e.printStackTrace();
            outputPrintLn("error\n" + e.getMessage());
        }   
    }); 
}

2022년 2월 19일 토요일

Java Swing -- Screen Capture

 Java Swing -- Screen Capture

package jlib5.demo;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class ScreenCapture {
    public static void main(String[] args) {
        JFrame capture = new JFrame();
        capture.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Toolkit kit = Toolkit.getDefaultToolkit();
        final Dimension d = kit.getScreenSize();
        capture.setSize(d);

        Rectangle rect = new Rectangle(d);
        try {
            Robot robot = new Robot();
            final BufferedImage image = robot.createScreenCapture(rect);
            image.flush();
            JPanel panel = new JPanel() {
                    private static final long serialVersionUID = 1L;
                    public void paintComponent(Graphics g) {
                            g.drawImage(image, 0, 0, d.width, d.height, this);
                    }
            };
            panel.setOpaque(false);
            panel.prepareImage(image, panel);
            panel.repaint();
            capture.getContentPane().add(panel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        capture.setVisible(true);
    }
}

Java Swing - Toast

 Java Swing - Toast

import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.RoundRectangle2D;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Toast {
    public static void main(String[] args) throws InterruptedException {
        ToastMessage toast = new ToastMessage("Toast Demo");
        toast.show();
        toast.showToMousePos();

        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        frame.setLocation(600,600);
        frame.setVisible(true);
        toast.showToCenter(frame);
        
        toast.close();
    }
}

class ToastMessage {
    JFrame frame;
    public ToastMessage(final String message) {
        frame = new JFrame();
        frame.setUndecorated(true);
        frame.setLayout(new GridBagLayout());
        frame.setBackground(new Color(240,240,240,250));
        frame.setLocationRelativeTo(null);
        frame.setSize(300, 50);
        frame.add(new JLabel(message));
        frame.addComponentListener(new ComponentAdapter() {
           @Override
           public void componentResized(ComponentEvent e) {
              frame.setShape(new  RoundRectangle2D.Double(0,0,frame.getWidth(),frame.getHeight(), 20, 20));                      
           }
        });        
    }

    public void show() {
        try {
            frame.setOpacity(1);
            frame.setVisible(true);
            Thread.sleep(1000);
            for (double d = 1.0; d > 0.2; d -= 0.1) {
               Thread.sleep(100);
               frame.setOpacity((float)d);
            }
            frame.setVisible(false);
        }catch (Exception ignore) {
        }
    }
    
    public void show(int x, int y) {
        frame.setLocation(x, y);
        show();
    }
    
    public void showToMousePos() {
        Point p = MouseInfo.getPointerInfo().getLocation();
        show( p.x, p.y );
    }
    
    public synchronized void showToCenter(Component comp) {
        frame.setLocationRelativeTo(SwingUtilities.getRoot(comp));
        show();
    }
    
    public void close() {
        frame.dispose();
    }
}

Java Swing - Notification

 Java Swing - Notification


package com.backup.swing;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

public class Notification {
	public static void show(String title, String message) {
		JFrame frame = new JFrame(); 
		frame.setUndecorated(true);
		frame.setSize(300,125); 
		frame.setAlwaysOnTop(true);
		frame.setLayout(new GridBagLayout()); 
		
		Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();// size of the screen 
		Insets toolHeight = Toolkit.getDefaultToolkit().getScreenInsets(frame.getGraphicsConfiguration());// height of the task bar 
		frame.setLocation(scrSize.width - frame.getWidth(), scrSize.height - toolHeight.bottom - frame.getHeight()); 
		
		GridBagConstraints constraints = new GridBagConstraints(); 
		constraints.gridx = 0; 
		constraints.gridy = 0; 
		constraints.weightx = 1.0f; 
		constraints.weighty = 1.0f; 
		constraints.insets = new Insets(5, 5, 5, 5); 
		constraints.fill = GridBagConstraints.BOTH; 
		JLabel headingLabel = new JLabel(title); 
		headingLabel.setIcon(new ImageIcon("/res/About32.png")); 
		headingLabel.setOpaque(false); 
		frame.add(headingLabel, constraints); 
		constraints.gridx++; 
		constraints.weightx = 0f; 
		constraints.weighty = 0f; 
		constraints.fill = GridBagConstraints.NONE; 
		constraints.anchor = GridBagConstraints.NORTH; 
		JButton closeButton = new JButton( new AbstractAction() {
	        @Override public void actionPerformed(final ActionEvent e) { 
	               frame.dispose(); 
	        }});
		closeButton.setText("X");
		closeButton.setMargin(new Insets(1, 4, 1, 4)); 
		closeButton.setFocusable(false); 
		frame.add(closeButton, constraints); 
		constraints.gridx = 0; 
		constraints.gridy++; 
		constraints.weightx = 1.0f; 
		constraints.weighty = 1.0f; 
		constraints.insets = new Insets(5, 5, 5, 5); 
		constraints.fill = GridBagConstraints.BOTH; 
		JLabel messageLabel = new JLabel("<html>"+message); 
		//messageLabel.setBackground(Color.YELLOW);
		frame.add(messageLabel, constraints); 
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		//frame.setBackground(Color.YELLOW);
		frame.setVisible(true); 
		
		new Thread(){ 
		      @Override 
		      public void run() { 
		           try { 
		                  Thread.sleep(5000); // time after which pop up will be disappeared. 
		                  frame.dispose(); 
		           } catch (InterruptedException e) { 
		                  e.printStackTrace(); 
		           } 
		      }; 
		}.start(); 
		
	}
	
	public static void main(String[] args) {
		String title = "This is header of notification message"; 
		String message = "You got a new notification message. Isn't it awesome to have such a notification message."; 
		Notification.show(title, message);
	}
}

Java Swing - LuaApi

 Java Swing - LuaApi


package jlib5.java;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class LuaApi {

    ScriptEngineManager sem ;
    ScriptEngine e;
    ScriptEngineFactory f;

    public LuaApi() {
        sem = new ScriptEngineManager();
        e = sem.getEngineByName("luaj");
        f = e.getFactory();
    }

    public void showVersion() {
        System.out.println( "Engine name: " +f.getEngineName() );
        System.out.println( "Engine Version: " +f.getEngineVersion() );
        System.out.println( "LanguageName: " +f.getLanguageName() );
        System.out.println( "Language Version: " +f.getLanguageVersion() );
    }

    public void set(String name, int value ) {
        e.put( name, value );
    }

    public Object get(String name) {
        return e.get( name );
    }

    public Object eval(String statement ) {
        try {
            return e.eval(statement);
        } catch (ScriptException ex) {
            ex.printStackTrace();
        }
        return null;
    }


    public boolean checkCondition(String statement) {
        String lua_statement = "if " + statement + " then rv=1 else rv=0 end";
        eval( lua_statement );
        int rv = (int)get("rv");
        return rv != 0;
    }

    public boolean checkJavaCondition(String statement) {
        String lua_statement = statement.replace("&&", " and " )
                .replace( "~=", "!=")
                .replace( "||", " or ");
        return checkCondition(lua_statement);
    }

    public static void main(String[] args) {
        LuaApi lua = new LuaApi();
        lua.showVersion();
        lua.set("a",1);
        lua.set("b",2);
        System.out.println( lua.checkCondition("a == 1 and b == 2") );
        System.out.println( lua.checkCondition("a == 1 and b == 1") );
    }
}

Java Swing - PUmlApi

 Java Swing - PUmlApi


package jlib5.java;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import net.sourceforge.plantuml.BlockUml;
import net.sourceforge.plantuml.BlockUmlBuilder;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.Option;
import net.sourceforge.plantuml.core.Diagram;

public class PUmlApi {

    public static List<BufferedImage> makeImage(String input) throws IOException, InterruptedException {
        @SuppressWarnings("deprecation")
        BlockUmlBuilder builder = new BlockUmlBuilder(
                        new ArrayList<String>(), //option.getConfig(),  
                        "UTF-8",      //option.getCharset(), 
                        new Option().getDefaultDefines(), 
                        new StringReader(input));      

        List<BufferedImage> result = new ArrayList<>();
        
        for( BlockUml blockUml : builder.getBlockUmls() ) {
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                final Diagram diagram = blockUml.getDiagram();
                diagram.exportDiagram((OutputStream)os, 0, new FileFormatOption(FileFormat.PNG));
                result.add(ImageIO.read(new ByteArrayInputStream(os.toByteArray())));
                os.close();
            } catch (Exception e) {
                e.getSuppressed();
            }
        }     
        return result;
    }
}

Java Swing - Tree

 Java Swing - Tree


package jlib5.swing;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class Tree {

    public JTree ctrl;
    JPopupMenu menu;

    public Tree(String rootName, Runnable handler) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootName);
        /* root.add( new DefaultMutableTreeNode("하위1") );
        root.add( new DefaultMutableTreeNode("하위2") ); */
        ctrl = new JTree(root);
        if( handler != null ) {
            setTreeHandler(handler);
        }
    }
    public void showTreeRoot() {
        ctrl.setRootVisible(true);}
    public void hideTreeRoot() {
        ctrl.setRootVisible(false);}
    public void expandAll() {
        for (int i = 0; i < ctrl.getRowCount(); i++) {
            ctrl.expandRow(i);
        }
    }
    public void clearAll() {
        ctrl.getSelectionModel().clearSelection();
        DefaultTreeModel model = (DefaultTreeModel) ctrl.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        model.reload();
        //model.setRoot(null);
    }
    public void clear(DefaultMutableTreeNode node) {
        DefaultTreeModel model = (DefaultTreeModel) ctrl.getModel();
        node.removeAllChildren();
        model.reload();
        //model.setRoot(null);
    }

    public void addContextMenu(String name, Runnable handler) {
        JMenuItem item = new JMenuItem(name);
        item.addActionListener( (e) -> handler.run() );
        if( this.menu == null ) {
            this.menu = new JPopupMenu();
            this.menu.add(item);
            ctrl.setComponentPopupMenu(this.menu);
        } else {
            menu.add(item);
        }
    }

    public void setTreeHandler(Runnable runnable) {
        ctrl.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener(){
            public void valueChanged(TreeSelectionEvent event) {
                runnable.run();
            }
        });
    }
    public String getTreeSelectionPath() {
        return ctrl.getSelectionModel().getSelectionPath().toString();
    }
    public DefaultMutableTreeNode addTreeToRoot(String name) {
        DefaultTreeModel model = (DefaultTreeModel) ctrl.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(name);
        model.insertNodeInto(node, root, root.getChildCount());
        //model.insertNodeInto(node, root, model.getChildCount(root));
        model.reload(root);
        return node;
    }
    public DefaultMutableTreeNode addTree(DefaultMutableTreeNode parent, String name) {
        DefaultTreeModel model = (DefaultTreeModel) ctrl.getModel();
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(name);
        model.insertNodeInto(node, parent, parent.getChildCount());
        model.reload(parent);
        return node;
    }
    public DefaultMutableTreeNode getSelectedNode() {
        return (DefaultMutableTreeNode)ctrl.getLastSelectedPathComponent();
    }
    public String[] getSelectedTreePath() {
        TreePath path = ctrl.getSelectionPath();
        if( path != null ) {
            int count = path.getPathCount();
            String[] nodes = new String[count];
            for( int i = 0; i < count; i++ ) {
                nodes[count-i-1] = path.getLastPathComponent().toString();
                path = path.getParentPath();
            }
            return nodes;
        }
        return null;
    }


    public String getTreeToString(DefaultMutableTreeNode node, String prefix) {
        StringBuilder sb = new StringBuilder();
        if( prefix == null ) {
            prefix = "";
            sb.append(node.toString()).append("\n|  \n");
        }
        if( node.getChildCount() == 0 ) {
            return prefix + node.toString() + "\n";
        } else {
            int num = node.getChildCount();
            for (int i = 0; i < num; i++) {
                DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
                if( i == num-1 ) {
                    sb.append(prefix).append("`--").append(child).append("\n");
                    if (child.getChildCount() > 0) {
                        sb.append(getTreeToString(child, prefix + "   "));
                    }
                } else {
                    sb.append(prefix).append("|--").append(child).append("\n");
                    if (child.getChildCount() > 0) {
                        sb.append(getTreeToString(child, prefix + "|  "));
                    }
                }
            }
            return sb.toString();
        }
    }

}