Showing posts with label Swing. Show all posts
Showing posts with label Swing. Show all posts

Thursday, February 13, 2014

Simple example to display message dialog with JOptionPane

The showMessageDialog(Component parentComponent, Object message) method of JOptionPane display an information-message dialog.

where:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used.
message - the Object to display

JOptionPane
display message dialog with JOptionPane

package javajoptionpane;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaJOptionPane extends JFrame{
    
    public void prepareUI() {
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        JButton jButton = new JButton("showMessageDialog");
        jButton.setVerticalTextPosition(JButton.BOTTOM);
        jButton.setHorizontalTextPosition(JButton.RIGHT);
        
        jButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(
                        null, 
                        "It's JOptionPane");
            }
        });

        hPanel.add(jButton);
        getContentPane().add(hPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
    private static void createAndShowGUI() {
        JavaJOptionPane myJavaJOptionPane = new JavaJOptionPane();
        myJavaJOptionPane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myJavaJOptionPane.prepareUI();
        myJavaJOptionPane.pack();
        myJavaJOptionPane.setVisible(true);
    }
}

Monday, February 3, 2014

Java Swing example: Add and Remove UI components dynamically

This example show add and remove UI compnents in run-time dynamically:

Add and Remove UI components dynamically
Add and Remove UI components dynamically

package javadynui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaDynUI extends JFrame {

    static JavaDynUI myFrame;
    static int countMe = 0;
    JPanel mainPanel;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        myFrame = new JavaDynUI();
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }

    private void prepareUI() {
        mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JButton buttonAdd = new JButton("Add subPanel");
        buttonAdd.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                mainPanel.add(new subPanel());
                myFrame.pack();
            }
        });
        
        JButton buttonRemoveAll = new JButton("Remove All");
        buttonRemoveAll.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                mainPanel.removeAll();
                myFrame.pack();
            }
        });

        getContentPane().add(mainPanel, BorderLayout.CENTER);
        getContentPane().add(buttonAdd, BorderLayout.PAGE_START);
        getContentPane().add(buttonRemoveAll, BorderLayout.PAGE_END);
    }

    private class subPanel extends JPanel {
        
        subPanel me;

        public subPanel() {
            super();
            me = this;
            JLabel myLabel = new JLabel("Hello subPanel(): " + countMe++);
            add(myLabel);
            JButton myButtonRemoveMe = new JButton("remove me");
            myButtonRemoveMe.addActionListener(new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e) {
                    me.getParent().remove(me);
                    myFrame.pack();
                }
            });
            add(myButtonRemoveMe);
        }
    }
}


Java Swing example: insert UI dynamically

This example show inserting UI compnents in run-time dynamically:

Insert UI dynamically
Insert UI dynamically

package javadynui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaDynUI extends JFrame {

    static JavaDynUI myFrame;
    static int countMe = 0;
    JPanel mainPanel;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        myFrame = new JavaDynUI();
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }

    private void prepareUI() {
        mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JButton buttonAdd = new JButton("Add subPanel");
        buttonAdd.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                mainPanel.add(new subPanel());
                myFrame.pack();
            }
        });

        getContentPane().add(mainPanel, BorderLayout.CENTER);
        getContentPane().add(buttonAdd, BorderLayout.PAGE_START);
    }

    private class subPanel extends JPanel {

        public subPanel() {
            super();
            JLabel myLabel = new JLabel("Hello subPanel(): " + countMe++);
            add(myLabel);
        }
    }
}


Saturday, February 1, 2014

Example of using JInternalFrame

JInternalFrame example
JInternalFrame example

package javaswingjinternalframe;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.SwingUtilities;

public class JavaSwingJInternalFrame extends JFrame {

    JDesktopPane desktop;

    public JavaSwingJInternalFrame() {
        super("Java-Buddy");

        int inset = 50;
        setBounds(inset, inset, 500, 400);

        desktop = new JDesktopPane();
        createFrame();
        createFrame(50, 100);
        setContentPane(desktop);
    }

    private void createFrame() {
        MyInternalFrame frame = new MyInternalFrame();
        frame.setVisible(true);
        desktop.add(frame);
        try {
            frame.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {
        }
    }

    private void createFrame(int x, int y) {
        MyInternalFrame frame = new MyInternalFrame(x, y);
        frame.setVisible(true);
        desktop.add(frame);
        try {
            frame.setSelected(true);
        } catch (java.beans.PropertyVetoException e) {
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaSwingJInternalFrame myFrame = new JavaSwingJInternalFrame();
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setVisible(true);

    }

    private class MyInternalFrame extends JInternalFrame {

        public MyInternalFrame() {
            super("MyInternalFrame",
                    true, //resizable
                    true, //closable
                    true, //maximizable
                    true);//iconifiable

            setSize(300, 200);
        }

        public MyInternalFrame(int offsetX, int offsetY) {
            super("MyInternalFrame",
                    true, //resizable
                    true, //closable
                    true, //maximizable
                    true);//iconifiable

            setSize(300, 200);
            setLocation(offsetX, offsetY);
        }
    }

}

Sunday, January 26, 2014

JavaFX/Swing + RxTx to communicate with Arduino, as ColorPicker

Here is examples from arduino-er.blogspot.com to demonstrate how to use RxTx Java Library in JavaFX/Swing application to communicate with Arduino Esplora via USB serial. javafx.scene.control.ColorPicker/javax.swing.JColorChooser are used to choice color, then send to Arduino via USB serial with RxTx Java Library, then to set the color of LCD screen/LED in Arduino side.

JavaFX version:
package javafxcolorpicker;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavaFXColorPicker extends Application {

    MyRxTx myRxTx;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("ColorPicker");
        final Scene scene = new Scene(new HBox(20), 400, 100);
        HBox box = (HBox) scene.getRoot();
        box.setPadding(new Insets(5, 5, 5, 5));

        final ColorPicker colorPicker = new ColorPicker();
        //colorPicker.setValue(Color.CORAL);

        colorPicker.setOnAction(new EventHandler() {
            public void handle(Event t) {
                scene.setFill(colorPicker.getValue());
                
                Color color = colorPicker.getValue();
                byte byteR = (byte)(color.getRed() * 255);
                byte byteG = (byte)(color.getGreen() * 255);
                byte byteB = (byte)(color.getBlue() * 255);
                
                try {
                    byte[] bytesToSent = 
                            new byte[]{byteB, byteG, byteR};
                    myRxTx.output.write(bytesToSent);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        });

        box.getChildren().add(colorPicker);

        primaryStage.setScene(scene);
        primaryStage.show();
        
        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

    public static void main(String[] args) {
        launch(args);
    }

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId
                        = (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                System.out.println("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();
                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }

}



Java Swing version:
package javaswingcolorpicker;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;

public class JavaSwingColorPicker extends JFrame {
    
    MyRxTx myRxTx;

    public JavaSwingColorPicker() {
        super("JColorChooser Test Frame");
        setSize(200, 100);
        final Container contentPane = getContentPane();
        final JButton go = new JButton("Show JColorChooser");
        go.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Color c;
                c = JColorChooser.showDialog(
                        ((Component) e.getSource()).getParent(),
                        "Demo", Color.blue);
                contentPane.setBackground(c);

                byte byteR = (byte)(c.getRed());
                byte byteG = (byte)(c.getGreen());
                byte byteB = (byte)(c.getBlue() );
                
                try {
                    byte[] bytesToSent = 
                            new byte[]{byteB, byteG, byteR};
                    myRxTx.output.write(bytesToSent);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        });
        contentPane.add(go, BorderLayout.SOUTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

    public static void main(String[] args) {
        JavaSwingColorPicker myColorPicker = new JavaSwingColorPicker();
        myColorPicker.setVisible(true);
        
    }

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId
                        = (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                System.out.println("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();
                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }

}



For the code in Arduino side, refer: http://arduino-er.blogspot.com/2014/01/send-array-of-byte-from-pc-to-arduino.html

Tuesday, January 21, 2014

JButton with Icon

JButton with Icon
JButton with Icon

package javaexample;

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaExample extends JFrame {

    public void prepareUI() {
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        ImageIcon dukesIcon = null;
        java.net.URL imgURL = JavaExample.class.getResource("dukes_36x36.png");
        if (imgURL != null) {
            dukesIcon = new ImageIcon(imgURL);
        } else {
            System.err.println("Can't load icon! ");
        }

        JButton jButton = new JButton("java-buddy.blogspot.com",
                            dukesIcon);
        jButton.setVerticalTextPosition(JButton.BOTTOM);
        jButton.setHorizontalTextPosition(JButton.RIGHT);

        hPanel.add(jButton);
        getContentPane().add(hPanel, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaExample myExample = new JavaExample();
        myExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myExample.prepareUI();
        myExample.pack();
        myExample.setVisible(true);
    }
    
}

Monday, January 20, 2014

Example to create JLabel with icon

JLabel with icon
JLabel with icon

package javaexample;

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaExample extends JFrame {

    public void prepareUI() {
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        ImageIcon dukesIcon = null;
        java.net.URL imgURL = JavaExample.class.getResource("dukes_36x36.png");
        if (imgURL != null) {
            dukesIcon = new ImageIcon(imgURL);
        } else {
            System.err.println("Can't load icon! ");
        }

        JLabel jLabel = new JLabel("java-buddy.blogspot.com",
                            dukesIcon,
                            JLabel.CENTER);
        jLabel.setVerticalTextPosition(JLabel.BOTTOM);
        jLabel.setHorizontalTextPosition(JLabel.CENTER);

        hPanel.add(jLabel);
        getContentPane().add(hPanel, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaExample myExample = new JavaExample();
        myExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myExample.prepareUI();
        myExample.pack();
        myExample.setVisible(true);
    }
    
}

Thursday, January 16, 2014

Java Swing example using Border

Java Swing example using Border

package javaswingborder;

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.AbstractBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingBorder extends JFrame 
    implements ListSelectionListener{

    JList jList;
    JLabel jLabelInfo;
    
    static final String borderTypeArray[] = {
        "Bevel", 
        "Compound", 
        "Empty", 
        "Etched", 
        "Line", 
        "Matte", 
        "SoftBevel",
        "Titled" };
    
    AbstractBorder[] borderArray = {
        new BevelBorder(BevelBorder.LOWERED),
        new CompoundBorder(
                new LineBorder(Color.blue, 10), 
                new LineBorder(Color.red, 5)),
        new EmptyBorder(10, 10, 10, 10), 
        new EtchedBorder(), 
        new LineBorder(Color.blue, 10),
        new MatteBorder(5, 10, 5, 10, Color.GREEN), 
        new SoftBevelBorder(BevelBorder.RAISED),
        new TitledBorder("TitledBorder") };

    private void prepareUI() {
        
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        jList = new JList(borderTypeArray);
        jList.addListSelectionListener(this);
        hPanel.add(jList);
        jLabelInfo = new JLabel("java-buddy.blogspot.com");
        hPanel.add(jLabelInfo);

        getContentPane().add(hPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaSwingBorder myFrame = new JavaSwingBorder();
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        int selectedIndex = jList.getSelectedIndex();
        String selectedType = (String)jList.getSelectedValue();
        jLabelInfo.setText(selectedType);
        jLabelInfo.setBorder(borderArray[selectedIndex]);
    }

}

Wednesday, January 8, 2014

Java example of using JPopupMenu

JPopupMenu
JPopupMenu

package javamenu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMenu extends JFrame {

    JLabel jLabel;
    JPopupMenu jPopupMenu;

    private void prepareUI() {

        jLabel = new JLabel("Label", JLabel.RIGHT);
        getContentPane().add(jLabel);

        jPopupMenu = new JPopupMenu();
        JMenuItem jMenuItem_A = new JMenuItem("Menu Item A");
        JMenuItem jMenuItem_B = new JMenuItem("Menu Item B");
        JMenuItem jMenuItem_C = new JMenuItem("Menu Item C");
        jPopupMenu.add(jMenuItem_A);
        jPopupMenu.add(jMenuItem_B);
        jPopupMenu.add(jMenuItem_C);
        jMenuItem_A.addActionListener(menuActionListener);
        jMenuItem_B.addActionListener(menuActionListener);
        jMenuItem_C.addActionListener(menuActionListener);

        addMouseListener(myMouseAdapter);
    }

    MouseAdapter myMouseAdapter = new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
        
        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }

    };
    
    ActionListener menuActionListener = new ActionListener(){
 
        @Override
        public void actionPerformed(ActionEvent e) {
            jLabel.setText(e.getActionCommand());
        }
         
    };

    private static void createAndShowGUI() {
        JavaMenu myFrame = new JavaMenu();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(400, 300);
        myFrame.prepareUI();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

}

Tuesday, January 7, 2014

Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem

This example add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem:
Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem
Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem

package javamenu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMenu extends JFrame {
    
    JLabel jLabel;

    private void prepareUI() {
        
        jLabel = new JLabel("Label", JLabel.RIGHT);
        getContentPane().add(jLabel);
        
        JMenuBar jMenuBar = new JMenuBar();

        JMenu menuFile = new JMenu("File");
        menuFile.setMnemonic(KeyEvent.VK_F);
        jMenuBar.add(menuFile);
        JMenu menuOption = new JMenu("Options");
        menuOption.setMnemonic(KeyEvent.VK_P);
        jMenuBar.add(menuOption);

        //MenuItem New, Open, Save under File
        JMenuItem menuItemNew = new JMenuItem("New", KeyEvent.VK_N);
        menuFile.add(menuItemNew);
        JMenuItem menuItemOpen = new JMenuItem("Open", KeyEvent.VK_O);
        menuFile.add(menuItemOpen);
        JMenuItem menuItemSave = new JMenuItem("Save", KeyEvent.VK_S);
        menuFile.add(menuItemSave);

        //CheckBox A, B, C under Options
        JCheckBoxMenuItem jCheckBoxMenuItem_A = new JCheckBoxMenuItem("Check A");
        jCheckBoxMenuItem_A.setMnemonic(KeyEvent.VK_A);
        menuOption.add(jCheckBoxMenuItem_A);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_B = new JCheckBoxMenuItem("Check B");
        jCheckBoxMenuItem_B.setMnemonic(KeyEvent.VK_B);
        menuOption.add(jCheckBoxMenuItem_B);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_C = new JCheckBoxMenuItem("Check C");
        jCheckBoxMenuItem_C.setMnemonic(KeyEvent.VK_C);
        menuOption.add(jCheckBoxMenuItem_C);
        menuOption.addSeparator();
        
        //Create ButtonGroup for radio button D, E, F
        ButtonGroup buttonGroup = new ButtonGroup();
        
        JRadioButtonMenuItem jRadioButtonMenuItem_D = new JRadioButtonMenuItem("Option D", true);
        jRadioButtonMenuItem_D.setMnemonic(KeyEvent.VK_D);
        menuOption.add(jRadioButtonMenuItem_D);
        buttonGroup.add(jRadioButtonMenuItem_D);

        JRadioButtonMenuItem jRadioButtonMenuItem_E = new JRadioButtonMenuItem("Option E");
        jRadioButtonMenuItem_E.setMnemonic(KeyEvent.VK_E);
        menuOption.add(jRadioButtonMenuItem_E);
        buttonGroup.add(jRadioButtonMenuItem_E);
        
        JRadioButtonMenuItem jRadioButtonMenuItem_F = new JRadioButtonMenuItem("Option F");
        jRadioButtonMenuItem_F.setMnemonic(KeyEvent.VK_F);
        menuOption.add(jRadioButtonMenuItem_F);
        buttonGroup.add(jRadioButtonMenuItem_F);
        
        setJMenuBar(jMenuBar);
       
        //Add ActionListener
        menuItemNew.addActionListener(menuActionListener);
        menuItemOpen.addActionListener(menuActionListener);
        menuItemSave.addActionListener(menuActionListener);
        jCheckBoxMenuItem_A.addActionListener(menuActionListener);
        jCheckBoxMenuItem_B.addActionListener(menuActionListener);
        jCheckBoxMenuItem_C.addActionListener(menuActionListener);
        jRadioButtonMenuItem_D.addActionListener(menuActionListener);
        jRadioButtonMenuItem_E.addActionListener(menuActionListener);
        jRadioButtonMenuItem_F.addActionListener(menuActionListener);
    }

    ActionListener menuActionListener = new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            jLabel.setText(e.getActionCommand());
        }
        
    };

    private static void createAndShowGUI() {
        JavaMenu myFrame = new JavaMenu();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(400, 300);
        myFrame.prepareUI();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

}

Monday, January 6, 2014

Java JMenu Example

Example of using JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem and ButtonGroup.
Example of Java JMenu
Example of Java JMenu

package javamenu;

import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMenu extends JFrame {

    private void prepareUI() {
        JMenuBar jMenuBar = new JMenuBar();

        JMenu menuFile = new JMenu("File");
        menuFile.setMnemonic(KeyEvent.VK_F);
        jMenuBar.add(menuFile);
        JMenu menuOption = new JMenu("Options");
        menuOption.setMnemonic(KeyEvent.VK_P);
        jMenuBar.add(menuOption);

        //MenuItem New, Open, Save under File
        JMenuItem menuItemNew = new JMenuItem("New", KeyEvent.VK_N);
        menuFile.add(menuItemNew);
        JMenuItem menuItemOpen = new JMenuItem("Open", KeyEvent.VK_O);
        menuFile.add(menuItemOpen);
        JMenuItem menuItemSave = new JMenuItem("Save", KeyEvent.VK_S);
        menuFile.add(menuItemSave);

        //CheckBox A, B, C under Options
        JCheckBoxMenuItem jCheckBoxMenuItem_A = new JCheckBoxMenuItem("Check A");
        jCheckBoxMenuItem_A.setMnemonic(KeyEvent.VK_A);
        menuOption.add(jCheckBoxMenuItem_A);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_B = new JCheckBoxMenuItem("Check B");
        jCheckBoxMenuItem_B.setMnemonic(KeyEvent.VK_B);
        menuOption.add(jCheckBoxMenuItem_B);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_C = new JCheckBoxMenuItem("Check C");
        jCheckBoxMenuItem_C.setMnemonic(KeyEvent.VK_C);
        menuOption.add(jCheckBoxMenuItem_C);
        menuOption.addSeparator();
        
        //Create ButtonGroup for radio button D, E, F
        ButtonGroup buttonGroup = new ButtonGroup();
        
        JRadioButtonMenuItem jRadioButtonMenuItem_D = new JRadioButtonMenuItem("Option D", true);
        jRadioButtonMenuItem_D.setMnemonic(KeyEvent.VK_D);
        menuOption.add(jRadioButtonMenuItem_D);
        buttonGroup.add(jRadioButtonMenuItem_D);

        JRadioButtonMenuItem jRadioButtonMenuItem_E = new JRadioButtonMenuItem("Option E");
        jRadioButtonMenuItem_E.setMnemonic(KeyEvent.VK_E);
        menuOption.add(jRadioButtonMenuItem_E);
        buttonGroup.add(jRadioButtonMenuItem_E);
        
        JRadioButtonMenuItem jRadioButtonMenuItem_F = new JRadioButtonMenuItem("Option F");
        jRadioButtonMenuItem_F.setMnemonic(KeyEvent.VK_F);
        menuOption.add(jRadioButtonMenuItem_F);
        buttonGroup.add(jRadioButtonMenuItem_F);
        
        setJMenuBar(jMenuBar);
    }

    private static void createAndShowGUI() {
        JavaMenu myFrame = new JavaMenu();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(400, 300);
        myFrame.prepareUI();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

}



Next:
- Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem

Java exercise: Display JTable data in line chart using JComponent

It's a simple example to display data in JTable in a line-chart, by combining example of "JTable" and "JComponent". To make it simple, only the first row will be shown on chart.

Display JTable data in line chart
Display JTable data in line chart

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyFrame extends JFrame {

    Label labelInfo;
    JTable jTable;

    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        JavaMyFrame myFrame = new JavaMyFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }
    
    private void prepareUI(){
        
        JPanel vPanel = new JPanel();
        vPanel.setLayout(new BoxLayout(vPanel, BoxLayout.Y_AXIS));
        
        MyChart myChart = new MyChart();
        myChart.setPreferredSize(new Dimension(450, 200));
        
        jTable = new JTable(new MyTableModel());
        jTable.getSelectionModel()
                .addListSelectionListener(new MyRowColListener());
        jTable.getColumnModel().getSelectionModel()
                .addListSelectionListener(new MyRowColListener());

        jTable.setFillsViewportHeight(true);
        JScrollPane jScrollPane = new JScrollPane(jTable);
        jScrollPane.setPreferredSize(new Dimension(450, 100));
        vPanel.add(jScrollPane);

        labelInfo = new Label();
        vPanel.add(labelInfo);
        
        Button buttonPrintAll = new Button("Print All");
        buttonPrintAll.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println();
                for(int i=0; i<jTable.getRowCount(); i++){
                    for(int j=0; j<jTable.getColumnCount(); j++){
                        String val = String.valueOf(jTable.getValueAt(i, j));
                        System.out.print(val + "\t");
                    }
                    System.out.println();
                }
                
                //Create ListArray for the first row
                //and update MyChart
                ArrayList<Integer> l = new ArrayList<>();
                for(int i=0; i<jTable.getColumnCount(); i++){
                    l.add((Integer)jTable.getValueAt(0, i));
                }
                myChart.updateList(l);
            }
        });
        
        getContentPane().add(myChart, BorderLayout.PAGE_START);
        getContentPane().add(vPanel, BorderLayout.CENTER);
        getContentPane().add(buttonPrintAll, BorderLayout.PAGE_END);
    }
    
    private class MyChart extends JComponent {
        ArrayList<Integer> chartList;
        
        public void updateList(ArrayList<Integer> l){
            System.out.println("updateList()");
            
            chartList = l;
            repaint();
        }

        @Override
        public void paint(Graphics g) {
            System.out.println("paint()");
            
            if(chartList != null){
                paintMe(g);
            }
        }
        
        private void paintMe(Graphics g){
            Graphics2D graphics2d = (Graphics2D)g;
            graphics2d.setColor(Color.blue);
            
            int width = getWidth();
            int height = getHeight();
            
            float hDiv = (float)width/(float)(chartList.size()-1);
            float vDiv = (float)height/(float)(Collections.max(chartList));
            
            for(int i=0; i<chartList.size()-1; i++){
                
                int value1, value2;
                if(chartList.get(i)==null){
                    value1 = 0;
                }else{
                    value1 = chartList.get(i);
                }
                if(chartList.get(i+1)==null){
                    value2 = 0;
                }else{
                    value2 = chartList.get(i+1);
                }
                
                graphics2d.drawLine(
                        (int)(i*hDiv), 
                        height - ((int)(value1*vDiv)),
                        (int)((i+1)*hDiv), 
                        height - ((int)(value2*vDiv)));
            }
            
            graphics2d.drawRect(0, 0, width, height);
        }
        
    }
    
    private class MyRowColListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            System.out.println("valueChanged: " + e.toString());

            if (!e.getValueIsAdjusting()) {
                
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                
                if(row>= 0 && col>=0){
                    int selectedItem = (int)jTable.getValueAt(row, col);
                    labelInfo.setText("MyRowListener: " 
                        + row + " : " + col + " = " + selectedItem);
                }
                
            }
        }
    }
    
    class MyTableModel extends AbstractTableModel {
        private String[] DayOfWeek = {
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday",
            "Sunday"};
    
        private Object[][] tableData = {
            {1, 2, 3, 4, 5, 6, 7},
            {4, 3, 2, 1, 7, 6, 5},
            {12, 20, 13, 14, 11, 24, 56},
            {13, 29, 23, 24, 25, 21, 20},
            {2, 4, 6, 8, 10, 12, 14},
            {11, 21, 33, 4, 9, 5, 4}};

        @Override
        public int getColumnCount() {
            return DayOfWeek.length;
        }

        @Override
        public int getRowCount() {
            return tableData.length;
        }

        @Override
        public String getColumnName(int col) {
            return DayOfWeek[col];
        }

        @Override
        public Object getValueAt(int row, int col) {
            return tableData[row][col];
        }

        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return true;
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            tableData[row][col] = value;
            fireTableCellUpdated(row, col);
        }

    }
}

Saturday, January 4, 2014

Detect mousePressed and mouseDragged with MouseAdapter

This example implement MouseAdpater to act as both MouseListener and MouseMotionListener, to handle mousePressed and mouseDragged to draw Oval on JComponent dynamically.

Detect mousePressed and mouseDragged with MouseAdapter
Detect mousePressed and mouseDragged with MouseAdapter

package javaswingdrawing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingDrawing extends JComponent {
    
    int mouseX, mouseY;
    int mouseX_dragged, mouseY_dragged;
    boolean mouseDragged;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    public JavaSwingDrawing() {
        addMouseListener(myMouseAdapter);
        addMouseMotionListener(myMouseAdapter);
    }
    
    MouseAdapter myMouseAdapter = new MouseAdapter(){

        @Override
        public void mousePressed(MouseEvent e) {
            mouseX = e.getX();
            mouseY = e.getY();
            mouseDragged = false;
            repaint();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            mouseX_dragged = e.getX();
            mouseY_dragged = e.getY();
            mouseDragged = true;
            repaint();
        }

    };

    @Override
    public void paint(Graphics g) {
        
        Graphics2D graphics2d = (Graphics2D)g;
        graphics2d.setColor(Color.blue);
        if(mouseDragged){
            int x, y;
            int w, h;
            
            if(mouseX > mouseX_dragged){
                x = mouseX_dragged;
                w = mouseX - mouseX_dragged;
            }else{
                x = mouseX;
                w = mouseX_dragged - mouseX;
            }
            
            if(mouseY > mouseY_dragged){
                y = mouseY_dragged;
                h = mouseY - mouseY_dragged;
            }else{
                y = mouseY;
                h = mouseY_dragged - mouseY;
            }
            
            graphics2d.drawOval(x, y, w, h);
        }else{
            graphics2d.fillOval(mouseX-5, mouseY-5, 10, 10);
        }
    }

    private static void createAndShowGUI() {
        JFrame myFrame = new JFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(new Dimension(400, 300));
        myFrame.setLayout(new BorderLayout());
        myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER);
        myFrame.setVisible(true);
    }
}

Friday, January 3, 2014

Implement MouseAdapter for JComponent

Implement MouseAdapter for JComponent
Implement MouseAdapter for JComponent

package javaswingdrawing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingDrawing extends JComponent {
    
    int mouseX, mouseY;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    public JavaSwingDrawing() {
        addMouseListener(myMouseAdapter);
    }
    
    MouseAdapter myMouseAdapter = new MouseAdapter(){

        @Override
        public void mousePressed(MouseEvent e) {
            mouseX = e.getX();
            mouseY = e.getY();
            repaint();
        }

    };

    @Override
    public void paint(Graphics g) {
        
        Graphics2D graphics2d = (Graphics2D)g;
        graphics2d.setColor(Color.blue);
        graphics2d.fillOval(mouseX-5, mouseY-5, 10, 10);
    }

    private static void createAndShowGUI() {
        JFrame myFrame = new JFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(new Dimension(400, 300));
        myFrame.setLayout(new BorderLayout());
        myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER);
        myFrame.setVisible(true);
    }
}



Next: Detect mousePressed and mouseDragged with MouseAdapter

Example of drawing something on Swing JComponent

Draw something on Swing JComponent
Draw something on Swing JComponent

package javaswingdrawing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingDrawing extends JComponent {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    @Override
    public void paint(Graphics g) {
        
        Graphics2D graphics2d = (Graphics2D)g;
        
        int w = getWidth();
        int h = getHeight();
        graphics2d.setColor(Color.red);
        graphics2d.fillOval(w/4, h/4, w/2, h/2);
        graphics2d.setColor(Color.blue);
        graphics2d.fillRect(w/2, h/2, w/4, h/4);
    }

    private static void createAndShowGUI() {
        JFrame myFrame = new JFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(new Dimension(400, 300));
        myFrame.setLayout(new BorderLayout());
        myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER);
        myFrame.setVisible(true);
    }
}


Next:
- Implement MouseAdapter for JComponent
- Detect mousePressed and mouseDragged with MouseAdapter

More:
- Display JTable data in line chart using JComponent

Thursday, January 2, 2014

Draw something on JFrame


package javaswingdrawing;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingDrawing extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    @Override
    public void paint(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        g.setColor(Color.red);
        g.fillOval(w/4, h/4, w/2, h/2);
        g.setColor(Color.blue);
        g.fillRect(w/2, h/2, w/4, h/4);
        //super.paint(g);
    }

    private static void createAndShowGUI() {
        JavaSwingDrawing myFrame = new JavaSwingDrawing();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setPreferredSize(new Dimension(400, 300));

        myFrame.pack();
        myFrame.setVisible(true);
    }
}


Tuesday, December 31, 2013

JTable with TableModel

In this example, we will implement our TableModel for JTable, and also fix bugs in last example. It can be eddited, its column can be moved, the data in our TableModel will be updated after changed, and also implement a button to print all the updated result in System.out.

JTable with TableModel
JTable with TableModel 

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyFrame extends JFrame {

    Label labelInfo;
    JTable jTable;

    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        JavaMyFrame myFrame = new JavaMyFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }
    
    private void prepareUI(){
        
        JPanel vPanel = new JPanel();
        vPanel.setLayout(new BoxLayout(vPanel, BoxLayout.Y_AXIS));
        
        jTable = new JTable(new MyTableModel());
        jTable.getSelectionModel()
                .addListSelectionListener(new MyRowListener());
        jTable.getColumnModel().getSelectionModel()
                .addListSelectionListener(new MyColListener());

        jTable.setFillsViewportHeight(true);
        JScrollPane jScrollPane = new JScrollPane(jTable);
        jScrollPane.setPreferredSize(new Dimension(450, 100));
        vPanel.add(jScrollPane);

        labelInfo = new Label();
        vPanel.add(labelInfo);
        
        Button buttonPrintAll = new Button("Print All");
        buttonPrintAll.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println();
                for(int i=0; i<jTable.getRowCount(); i++){
                    for(int j=0; j<jTable.getColumnCount(); j++){
                        String val = String.valueOf(jTable.getValueAt(i, j));
                        System.out.print(val + "\t");
                    }
                    System.out.println();
                }
            }
        });
        
        getContentPane().add(vPanel, BorderLayout.CENTER);
        getContentPane().add(buttonPrintAll, BorderLayout.PAGE_END);
    }
    
    private class MyRowListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {

            if (!e.getValueIsAdjusting()) {
                System.out.println("valueChanged: " + e.toString());
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                
                /*
                // cannot access getValueAt(row, col) here...!
                // Otherwise ArrayIndexOutOfBoundsException when move column
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyRowListener: " 
                        + row + " : " + col + " = " + selectedItem);
                */
                labelInfo.setText("MyRowListener: " + row + " : " + col);

            }
        }
    }
    
    private class MyColListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {

            if (!e.getValueIsAdjusting()) {
                System.out.println("valueChanged: " + e.toString());
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                
                /*
                // cannot access getValueAt(row, col) here...!
                // Otherwise ArrayIndexOutOfBoundsException when move column
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyColListener: " 
                        + row + " : " + col + " = " + selectedItem);
                */
                labelInfo.setText("MyRowListener: " + row + " : " + col);

            }
        }
    }
    
    class MyTableModel extends AbstractTableModel {
        private String[] DayOfWeek = {
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday"};
    
        private Object[][] tableData = {
            {1, 2, 3, 4},
            {4, 3, 2, 1},
            {12, 20, 13, 14},
            {13, 29, 23, 24},
            {2, 4, 6, 8},
            {11, 21, 33, 4}};

        @Override
        public int getColumnCount() {
            return DayOfWeek.length;
        }

        @Override
        public int getRowCount() {
            return tableData.length;
        }

        @Override
        public String getColumnName(int col) {
            return DayOfWeek[col];
        }

        @Override
        public Object getValueAt(int row, int col) {
            return tableData[row][col];
        }

        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return true;
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            tableData[row][col] = value;
            fireTableCellUpdated(row, col);
        }

    }
}


More:
- Display JTable data in line chart using JComponent

Sunday, December 29, 2013

Detect selection on individual cell in JTable

Last post of "Java Swing JTable and ListSelectionListener" implement MyListSelectionListener() for listSelectionModel. It can be noticed from the demo video that if click on another cell in the same row, MyListSelectionListener() will not be called.

In this post, two seperated ListSelectionListener, MyRowListener and MyColListener, are implemented and added to jTable.getSelectionModel() and jTable.getColumnModel().getSelectionModel(), to monitor individual cell selected .

Detect selection on individual cell in JTable
Detect selection on individual cell in JTable

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Label;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyFrame extends JFrame {

    Label labelInfo;
    JTable jTable;
    ListSelectionModel listSelectionModel;
    
    static final String DayOfWeek[] = {
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday"};
    
    Object[][] tableData = {
        {1, 2, 3, 4},
        {4, 3, 2, 1},
        {12, 20, 13, 14},
        {13, 29, 23, 24},
        {2, 4, 6, 8},
        {11, 21, 33, 4}};

    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        JavaMyFrame myFrame = new JavaMyFrame();
        myFrame.setTitle("java-buddy.blogspot.com");

        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        myFrame.prepareUI();

        myFrame.pack();
        myFrame.setVisible(true);
    }
    
    private void prepareUI(){
        
        JPanel vPanel = new JPanel();
        vPanel.setLayout(new BoxLayout(vPanel, BoxLayout.Y_AXIS));
        
        jTable = new JTable(tableData, DayOfWeek);
        jTable.setMaximumSize(new Dimension(10,10));

        listSelectionModel = jTable.getSelectionModel();
        jTable.getSelectionModel()
                .addListSelectionListener(new MyRowListener());
        jTable.getColumnModel().getSelectionModel()
                .addListSelectionListener(new MyColListener());
        jTable.setSelectionModel(listSelectionModel);

        jTable.setFillsViewportHeight(true);
        JScrollPane jScrollPane = new JScrollPane(jTable);
        jScrollPane.setPreferredSize(new Dimension(450, 100));
        vPanel.add(jScrollPane);

        labelInfo = new Label();

        vPanel.add(labelInfo);
        
        getContentPane().add(vPanel, BorderLayout.CENTER);
    }
    
    private class MyRowListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                System.out.println("valueChanged: " + e.toString());
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyRowListener: " 
                        + row + " : " + col + " = " + selectedItem);
            }
        }
    }
    
    private class MyColListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                System.out.println("valueChanged: " + e.toString());
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                int selectedItem = (int)jTable.getValueAt(row, col);
                labelInfo.setText("MyColListener: " 
                        + row + " : " + col + " = " + selectedItem);
            }
        }
    }
}



Next: JTable with TableModel

Java Swing JTable and ListSelectionListener

Example of Swing JTable and ListSelectionListener. JTable is used to display and edit regular two-dimensional tables of cells.

Example of JTable
Example of JTable

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Label;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMyFrame extends JFrame {

    Label labelInfo;
    JTable jTable;
    ListSelectionModel listSelectionModel;
    
    static final String DayOfWeek[] = {
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday"};
    
    Object[][] tableData = {
        {1, 2, 3, 4},
        {4, 3, 2, 1},
        {12, 20, 13, 14},
        {13, 29, 23, 24},
        {2, 4, 6, 8},
        {11, 21, 33, 4}};

    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    private static void createAndShowGUI() {
        JavaMyFrame myFrame = new JavaMyFrame();
        myFrame.setTitle("java-buddy.blogspot.com");

        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        myFrame.prepareUI();

        myFrame.pack();
        myFrame.setVisible(true);
    }
    
    private void prepareUI(){
        
        JPanel vPanel = new JPanel();
        vPanel.setLayout(new BoxLayout(vPanel, BoxLayout.Y_AXIS));
        
        jTable = new JTable(tableData, DayOfWeek);
        jTable.setMaximumSize(new Dimension(10,10));

        listSelectionModel = jTable.getSelectionModel();
        listSelectionModel.addListSelectionListener(new MyListSelectionListener());
        jTable.setSelectionModel(listSelectionModel);

        jTable.setFillsViewportHeight(true);
        JScrollPane jScrollPane = new JScrollPane(jTable);
        jScrollPane.setPreferredSize(new Dimension(450, 100));
        vPanel.add(jScrollPane);

        labelInfo = new Label();

        vPanel.add(labelInfo);
        
        getContentPane().add(vPanel, BorderLayout.CENTER);
 
    }

    class MyListSelectionListener implements ListSelectionListener{

        @Override
        public void valueChanged(ListSelectionEvent e) {
            System.out.println("valueChanged: " + e.toString());
            int row = jTable.getSelectedRow();
            int col = jTable.getSelectedColumn();
            int selectedItem = (int)jTable.getValueAt(row, col);
            labelInfo.setText(row + " : " + col + " = " + selectedItem);
        }
        
    };
}



It can be noticed from the demo video that if click on another cell in the same row, MyListSelectionListener() will not be called. Read next post "Detect selection on individual cell in JTable".