2022년 2월 19일 토요일

Java Swing - Swing

 Java Swing - Swing



package jlib5.swing;

import jlib5.java.IconApi;
import jlib5.java.Runnable1;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class Swing {

    public static void runLater( Runnable handler ) {
        SwingUtilities.invokeLater(handler);
    }
    public static Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); }
    public static Double getScreenSizeWidth() { return Toolkit.getDefaultToolkit().getScreenSize().getWidth(); }
    public static Double getScreenHeight() { return Toolkit.getDefaultToolkit().getScreenSize().getHeight(); }

    public static void setWindowIcon(JFrame frame, String icon) { frame.setIconImage( IconApi.getBase64Image(icon) ); }
    public static void setWindowIconRes(JFrame frame, URL icon) throws IOException {
        frame.setIconImage(ImageIO.read(icon)); //JS.class.getResource("app.png")
    }
    public static void setWindowTitle(JFrame frame, String title) { frame.setTitle(title); }
    public static void setWindowCenter(JFrame frame) {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frm = frame.getSize();
        int xpos = (int)(screen.getWidth() / 2 - frm.getWidth() / 2);
        int ypos = (int)(screen.getHeight() / 2 - frm.getHeight() / 2);
        frame.setLocation(xpos, ypos);
    }
    public static void addTop(JFrame frame, JComponent obj) { frame.add( obj, BorderLayout.NORTH); }
    public static void addCenter(JFrame frame, JComponent obj) { frame.add( obj, BorderLayout.CENTER); }
    public static void addBottom(JFrame frame, JComponent obj) { frame.add( obj, BorderLayout.SOUTH); }
    public static void setDrop(JComponent node, Runnable1 handler) {
        node.setTransferHandler( new Drop(handler) );
    }

    public static void setFont( JComponent node, String fontName, int fontSize ) {
        node.setFont(new Font( fontName, Font.PLAIN, fontSize)); //Font.BOLD
    }
    public static void hide(JComponent node) {
        node.setVisible(false);
    }
    public static void show(JComponent node) {
        node.setVisible(true);
    }

    public static JMenuBar getMenuBar() {
        JMenuBar menubar = new JMenuBar();
        menubar.add(getFileMenu());
        return menubar;
    }
    public static JMenu getFileMenu() {
        JMenu menu = new JMenu("File");
        JMenuItem exit_item = new JMenuItem("Exit");
        menu.add(getMenuItem( "Exit", () -> { System.exit(0); } ));
        return menu;
    }
    public static JMenuItem getMenuItem( String name, Runnable handler ) {        
        JMenuItem item = new JMenuItem(name);
        item.addActionListener( (e) -> handler.run() );
        return item;
    }

    public static void addContextMenu(JComponent node, String name, Runnable handler) {
        JPopupMenu menu = new JPopupMenu();
        JMenuItem item = new JMenuItem(name);
        item.addActionListener( (e) -> handler.run() );        
        menu.add(item);
        node.setComponentPopupMenu(menu);
    }
        
    public static JSplitPane getHSplitPane(JComponent left, JComponent right, int div) {
        JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
        split.setDividerLocation(div);
        split.setResizeWeight(1);
        return split;
    }
    public static JSplitPane getVSplitPane(JComponent left, JComponent right, int div) {
        JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, left, right);
        split.setDividerLocation(div);
        split.setResizeWeight(1);
        return split;
    }
    public static JComponent HExpand( JComponent node ) {
        node.setMaximumSize( new Dimension(Integer.MAX_VALUE, node.getPreferredSize().height) );
        return node;
    }
    public static JPanel getHbox() {
        JPanel box = new JPanel();
        BoxLayout layout = new BoxLayout(box, BoxLayout.X_AXIS);
        box.add(Box.createRigidArea(new Dimension(1, 0)));
        box.setAlignmentX( Component.LEFT_ALIGNMENT );
        box.setAlignmentY( Component.TOP_ALIGNMENT );
        box.setBorder(BorderFactory.createEmptyBorder(2 , 2 , 2 , 2));
        box.setLayout( layout );
        return box;
    }
    public static JPanel getHbox(JComponent...objs) {
        JPanel box = getHbox();
        if( objs != null && objs.length > 0 ) {
            for (JComponent obj : objs) {
                box.add(obj);
                box.add(Box.createRigidArea(new Dimension(2, 0)));
            }
        }
        return box;
    }
    public static JPanel getVbox() {
        JPanel box = new JPanel();
        BoxLayout layout = new BoxLayout(box, BoxLayout.Y_AXIS);
        box.add(Box.createRigidArea(new Dimension(0,1)));
        box.setAlignmentX( Component.LEFT_ALIGNMENT );
        box.setAlignmentY( Component.TOP_ALIGNMENT );
        box.setBorder(BorderFactory.createEmptyBorder(2 , 2 , 2 , 2));
        box.setLayout( layout );
        return box;
    }
    public static JPanel getVbox(JComponent...objs) {
        JPanel box = getVbox();
        if( objs != null && objs.length > 0 ) {
            for (JComponent obj : objs) {
                box.add(obj);
                box.add(Box.createRigidArea(new Dimension(0, 2)));
            }
        }
        return box;
    }

    public static JTabbedPane getTabbedPane() {
        JTabbedPane pane = new JTabbedPane();
        return pane;
    }
    public static void addTab( JTabbedPane pane, String name, JComponent node) {
        pane.add( name, node );
    }

    public static JLabel getLabel(String text ) {
        JLabel label = new JLabel();
        label.setText(text);
        label.setMaximumSize( new Dimension(label.getPreferredSize().width, label.getPreferredSize().height) );
        return label;
    }

    public static JButton getButton(String text, Image image, Runnable handler) {
        JButton button = new JButton();
        if( text != null ) { button.setText(text); }
        if( image != null ) { button.setIcon(new ImageIcon(image)); }
        if( handler != null ) { button.addActionListener( (e) -> handler.run() ); }
        return button;
    }

    public static JComboBox<String> getAutoComboBox(Integer width, Runnable handler) {
        JComboBox<String> node = new JComboBox<>();
        node.setEditable(true);
        if( width != null ) { 
            node.setMaximumSize( new Dimension(width, node.getPreferredSize().height) );
            node.setPreferredSize(new Dimension(width, node.getPreferredSize().height) ); 
        }    
        if( handler != null ) { 
            node.addActionListener( (e) -> {
                for( int i = 0; i < node.getModel().getSize(); i++ ) {
                    if( node.getItemAt(i).equals(node.getSelectedItem()) ) {
                        handler.run();
                        return;
                    }
                }
                node.addItem((String)node.getSelectedItem());
            }); 
        }
        return node;
    }
    public static JComboBox getComboBox(Integer width, Runnable handler) {
        JComboBox node = new JComboBox();
        node.setEditable(true);
        if( width != null ) { 
            node.setMaximumSize( new Dimension(width, node.getPreferredSize().height) );
            node.setPreferredSize(new Dimension(width, node.getPreferredSize().height) ); 
        }    
        if( handler != null ) { 
            node.addActionListener( (e) ->  handler.run() ); 
        }
        return node;
    }
    public static JComboBox getComboBox(Runnable handler) {
        return getComboBox( null, handler);
    }      
    public static JComboBox getComboBox() {
        return getComboBox( null, null);
    }  
    public static void addToComboBox(JComboBox node, String text) {
        node.addItem(text);
    }

    public static JTextField getTextField(String text, Runnable handler) {
        JTextField tf = new JTextField();
        //tf.setMaximumSize( tf.getPreferredSize() );
        tf.setMaximumSize( new Dimension(Integer.MAX_VALUE, tf.getPreferredSize().height) );
        if( text != null ) { tf.setText( text ); }
        if( handler != null ) { tf.addActionListener( e -> handler.run() ); };
        return tf;
    }
    public static void setTextFieldChangeEvent(JTextField textField) {
        textField.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
          warn();
        }
        public void removeUpdate(DocumentEvent e) {
          warn();
        }
        public void insertUpdate(DocumentEvent e) {
          warn();
        }
        public void warn() {
            if (Integer.parseInt(textField.getText())<=0){
                JOptionPane.showMessageDialog(null,
                   "Error: Please enter number bigger than 0", "Error Message",
                   JOptionPane.ERROR_MESSAGE);
                }
           }
       });
    }
    public static void setTextFieldMouseEvent(JTextField textField) {
        textField.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e){
                JTextField t = (JTextField)e.getSource();
                if(e.getClickCount()==2) {               
                }
            }
        });
    }    
    public static void setTextFieldFocusEvent(JTextField textField) {
        textField.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                if( textField.isFocusOwner()) {
                    
                }
            }
            @Override
            public void focusLost(FocusEvent e) {
                //Your code here
            }
        });

    }    
    public static void setTextFieldCaretEvent(JTextField textField) {
        CaretListener listener = new CaretListener() {
            public void caretUpdate(CaretEvent caretEvent) {
                System.out.println("dot:" + caretEvent.getDot());
                System.out.println("mark" + caretEvent.getMark());
            }
        };
        textField.addCaretListener(listener);   
    }    
    
    public static JProgressBar getProgressBar(int min, int max) {
        JProgressBar progress = new JProgressBar(min, max);
        progress.setMaximumSize( new Dimension(100, /*20*/progress.getPreferredSize().height) );
        //progress.setIndeterminate(true);
        //progress.setStringPainted(true);
        return progress;
    }

    public static void startProgress(JProgressBar progress) {
        //progress.setIndeterminate(true);
        progress.setStringPainted(true);
        progress.setVisible(true);
    }

    public static void startProgress(JProgressBar progress, int min, int max) {
        progress.setMinimum(min);
        progress.setMaximum(max);
        //progress.setIndeterminate(true);
        progress.setStringPainted(true);
        progress.setVisible(true);
    }

    public static void setProgress(JProgressBar progress, int value) {
        progress.setValue(value);
    }

    public static void showImage(String title, BufferedImage bimage) {
        JFrame frame = new JFrame();
        ImageIcon image = new ImageIcon(bimage);
        JLabel label = new JLabel(image);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        //frame.setUndecorated(true); //removes the surrounding border
        frame.setTitle(title);
        frame.getContentPane().add(label);
        frame.setSize(image.getIconWidth() + 20, image.getIconHeight() + 40);
        int x = (screenSize.width - frame.getSize().width)/2;
        int y = (screenSize.height - frame.getSize().height)/2;
        frame.setLocation(x, y);
        frame.setVisible(true);
    }

    public static File fileOpenDialog(JFrame frame) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        int result = fileChooser.showOpenDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            return fileChooser.getSelectedFile();
        }
        return null;
    }

    public static File fileSaveDialog(JFrame frame) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        int result = fileChooser.showSaveDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            return fileChooser.getSelectedFile();
        }
        return null;
    }
        
    public static File directoryOpenDialog(JFrame frame) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
        fileChooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY);
        int result = fileChooser.showOpenDialog(frame);
        if (result == JFileChooser.APPROVE_OPTION) {
            return fileChooser.getSelectedFile();
        }
        return null;
    }

    public static Object showInputDialog(JFrame frame, String title) {
        return JOptionPane.showInputDialog(frame, title);
    }
    public static Object showConfirmDialog(JFrame frame, Object message, String title) {
        int optionType = JOptionPane.YES_NO_OPTION; //YES_NO_CANCEL,OK_CANCEL
        int result = JOptionPane.showConfirmDialog(frame, message, title, optionType);
        if( result == JOptionPane.YES_OPTION ) return true;
        if( result == JOptionPane.NO_OPTION ) return false;
        return null;
    }
    public static void showMessageDialog(JFrame frame, Object message, String title) {
        int messageType = JOptionPane.INFORMATION_MESSAGE;
        JOptionPane.showMessageDialog(frame, message, title, messageType);
    }
    
    public static void main(String[] args) {
        JFrame f = new JFrame();
        JComboBox node = new JComboBox();
        node.setEditable(true);
        node.addItem("One");
        node.addItem("Two");
        node.addItem("Three");
        node.setSelectedIndex(0);
        node.addActionListener( (e) -> {
            for( int i = 0; i < node.getModel().getSize(); i++ ) {
                if( node.getItemAt(i) == node.getSelectedItem() ) {
                    System.out.println("[a] " + node.getSelectedItem() );
                    return;
                }
            }
            node.addItem(node.getSelectedItem());
            System.out.println("[b] " + node.getSelectedItem() );
         });
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add( node, BorderLayout.CENTER);
        f.pack();
        f.setVisible(true); 
    }    
}

댓글 없음:

댓글 쓰기