Showing posts with label SWing. Show all posts
Showing posts with label SWing. Show all posts

Friday, December 22, 2017

Use MethodHandle to dynamically invoke method

MethodHandle is introduced in Java 7. For dynamic method invoking, it is faster than reflection.

In the code below, class MethodHandleTest2 has three JTextField fields and an objModified method. When any of the JTextField fields is modified, the objModified method will be called to handle the modification accordingly.

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class MethodHandleTest2 extends JFrame{
    public MethodHandleTest2() {
        JTextField[] data = {new JTextField("Peach", 20),
                                  new JTextField("Papaya", 20),
                                  new JTextField("Mango", 20)};
        JPanel panel = new JPanel(new GridLayout(3, 1));

        for (int i=0; i<data.length; i++){
            try {
                data[i].addActionListener(new ObjectActionListener("objModified",
                                                   new Object[]{this, data[i], "Field "+(i+1)+" Modified"}
                ));
                panel.add(data[i]);
            } catch (NoSuchMethodException e){
                System.out.println(e.getMessage());
            }
        }
        this.add(panel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(700, 300);
        this.pack();
    }

    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                (new MethodHandleTest2()).setVisible(true);
            }
        });
    }

    public class ObjectActionListener implements ActionListener {
        private Object[] parameters = null;
        private String methodName = null;

        public ObjectActionListener(String methodName, Object[] parameters)
                throws NoSuchMethodException, SecurityException {
            this.methodName = methodName;
            this.parameters = parameters;
        }

        private MethodHandle getMethod() throws NoSuchMethodException,
                IllegalAccessException {

            //For the objModified method, its return type is void, and it takes
            // a JTextField argument and a String argument.
            MethodType mt = MethodType.methodType(void.class, JTextField.class, String.class);

            //Get the MethodHandle: argument1 is the class where the method is located;
            // argument2 is the method name;
            //argument3 is the method type of the method signature
            MethodHandle mh = MethodHandles.lookup()
                    .findVirtual(MethodHandleTest2.class,
                            methodName,
                            mt);
            return mh;
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            try {
                MethodHandle method = getMethod();
                //The invoke method is supposed to be able to take an array argument.
                //Somehow, it does not work for me in my test code.
               //So, I have to put each component of the array in the arguments.
                method.invoke(parameters[0], parameters[1], parameters[2]);
            } catch (IllegalAccessException e) {
                System.out.println(e.getMessage());
            } catch (InvocationTargetException e) {
                System.out.println(e.getMessage());
            } catch (Throwable e) {
                System.out.println(e.getMessage());
            }
        }
    }

    public void objModified(JTextField obj, String message){
            String text = obj.getText();
            System.out.println(message+": "+text);
    }
}

The code using reflection to do the same job can be found here

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, November 21, 2017

Use UIManager to set fonts, foreground color, background color, select color, border for Swing components

Once you set the properties in the UIManager, all your Swing components will have the corresponding look and feel.

public void setLookAndFeel () {

        Font plainFont = new Font("Serif", Font.PLAIN, 12);
        Font boldFont = new Font("Serif", Font.BOLD, 12);

        Color focusColor = Color.BLUE;
        Color backgroundColor = Color.YELLOW;
        Color disabledForgroundColor = Color.GREY;
        Color selectColor = Color.LIGHT_GRAY;

        UIManager.put("Text.font", new FontUIResource(plainFont));
        UIManager.put("TextField.font", new FontUIResource(plainFont));
        UIManager.put("FormattedTextField.font", new FontUIResource(plainFont));
        UIManager.put("PasswordField.font", new FontUIResource(boldFont));
        UIManager.put("TextArea.font", new FontUIResource(plainFont));
        UIManager.put("TextPane.font", new FontUIResource(plainFont));
        UIManager.put("List.font", new FontUIResource(plainFont));
        UIManager.put("Table.font", new FontUIResource(plainFont));
        UIManager.put("TableHeader.font", new FontUIResource(plainFont));
                   
        UIManager.put("CheckBox.font", new FontUIResource(plainFont));
        UIManager.put("RadioButton.font", new FontUIResource(plainFont));
        UIManager.put("Button.font",new FontUIResource(boldFont));
        UIManager.put("Button.focus", new ColorUIResource(focusColor));
        UIManager.put("Button.border", new LineBorder(Color.ORANGE, 5, true));
        UIManager.put("ComboBox.font", new FontUIResource(plainFont));
        UIManager.put("ComboBox.TableHeader.font", new FontUIResource(plainFont)); 
        UIManager.put("Label.font", new FontUIResource(plainFont));
        UIManager.put("ToolTip.font", new FontUIResource(boldFont));
        UIManager.put("ToggleButton.font", new FontUIResource(plainFont));
        UIManager.put("TitledBorder.font", new FontUIResource(boldFont));
     
        UIManager.put("Menu.font", new FontUIResource(boldFont));
        UIManager.put("MenuItem.font", new FontUIResource(boldFont));
        UIManager.put("MenuBar.font", new FontUIResource(boldFont));
        UIManager.put("PopupMenu.font", new FontUIResource(boldFont));
        UIManager.put("RadioButtonMenuItem.font", new FontUIResource(boldFont));
        UIManager.put("CheckBoxMenuItem.font", new FontUIResource(boldFont));
        UIManager.put("MenuItem.acceleratorFont", new FontUIResource(boldFont));
        UIManager.put("CheckBoxMenuItem.acceleratorFont", new FontUIResource(boldFont));
        UIManager.put("Menu.acceleratorFont", new FontUIResource(boldFont));
        UIManager.put("RadioButtonMenuItem.acceleratorFont", new FontUIResource(boldFont));
     
        UIManager.put("ToolBar.font", new FontUIResource(boldFont));
        UIManager.put("MenuBar.font", new FontUIResource(boldFont));
        UIManager.put("Panel.font", new FontUIResource(boldFont));
        UIManager.put("ProgressBar.font", new FontUIResource(boldFont));
        UIManager.put("OptionPane.font", new FontUIResource(boldFont));
        UIManager.put("OptionPane.buttonFont", new FontUIResource(boldFont));
        UIManager.put("OptionPane.messageFont", new FontUIResource(plainFont));
        UIManager.put("ScrollPane.font", new FontUIResource(boldFont));
        UIManager.put("EditorPane.font", new FontUIResource(plainFont));
        UIManager.put("ColorChooser.font", new FontUIResource(boldFont));
        UIManager.put("InternalFrame.titleFont", new FontUIResource(boldFont));
        UIManager.put("TabbedPane.font", new FontUIResource(boldFont));

        UIManager.put("Panel.background", backgroundColor);
        UIManager.put("CheckBox.background", backgroundColor);
        UIManager.put("RadioButton.background", backgroundColor);
        UIManager.put ("Button.select", selectColor);
UIManager.put ("ToggleButton.select", selectColor);
        UIManager.put("ComboBox.disabledBackground", backgroundColor);
        UIManager.put("ComboBox.fieldBackground", backgroundColor);
        UIManager.put("ComboBox.disabledForeground", disabledForgroundColor);
        UIManager.put("OptionPane.background", backgroundColor);
        UIManager.put("OptionPane.warningDialog.border.background", backgroundColor);
        UIManager.put("Label.background", backgroundColor);
        UIManager.put("TextField.shadow", backgroundColor);
        UIManager.put("TextField.background", backgroundColor); 
    }

Reference:

1. Swing UIManager Keys
2. Nimbus Defaults

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, October 3, 2014

setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

For JFrame:
          Always use setSize for setPreferredSize does nothing.

For JPanel, JButton and JLabel:
          No need to set their sizes for their sizes are always expanding to the space available. You need to use some invisible components or fillers to occupy the space that you don't want these components to be.

For JTextField:
         The setColumns method designates the size of the JTextField.
         The setPreferredSize makes the JTextField disappear, while the setSize does nothing.

For JTextArea:
          The setRows and setColumns methods designate the size of the JTextArea.

         The setPreferredSize fixes the displaying area. If the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line, however the width of the JTextArea will not expand and it only displays the number of characters its width can hold. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached. However, when the height of the displaying area is reached, the height of the displaying area will not expand even though the input characters are keeping adding to the end of the text.

        When setSize is used instead of setPreferredSize, the behavior of the JTextArea is the same as it is not used, if the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line and the width of the JTextArea expands accordingly. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached and when the height of the displaying area is reached, the height of the displaying area will expand accordingly.

          If you really want to use the setPreferredSize or the setSize to set the size of the JTextArea instead of using setRows and setColumns, do not call the setRows and setColumns methods and call the setLineWrap(true) before you call the setPreferredSize or the setSize method.

           The setPreferredSize mthod will set the size of the JTextArea to the size specified in the method. The size is fixed and will not expand according to the size of the text you put in it.

           The setSize method will set the width to the specified amount, but will not set the height. The height dynamically expands according to the the text put in the text area.

When the JTextArea is put in a JScrollPane:
          No matter whether the setRows and setColumns or the setPreferredSize or the setSize is used, the size of the JTextArea will occupy the whole available space in the JScrollPane. When setSize is used, it will automatically scroll, where else when setPreferredSize is used the JScrollPane will not scroll.

           However, when a JTextArea is put in a JScrollPane, it is better to not use either setPreferredSize or setSize on the JTextArea and the JScrollPane will scroll when it is needed.

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, October 2, 2014

How to make JTextArea display a maximum number of characters?

Following are the steps of setting the maximum numbers of characters that a JTextArea can take.


  1. Create a Document class that extends the PlainDocument class. 
    • In the class create a maxSize field. 
    • Override the insertString method so that only the maxSize or less number of characters can be inserted into the document. 
    • Create a setMaxSize method for setting the value of the maxSize.
  2. Create a Text Area class that extends the JTextArea, which uses the Document created in step 1 as its default document. Add a setMaxSize method to the class that calls the Document's setMaxSize mthod to set the max size for the Document.
Here is the sample code.


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class TextAreaSize {
    
    private class MyDocument extends PlainDocument {
        private int maxSize = 1000000000;
        
        @Override
        public void insertString(int offset, String s, AttributeSet attributeSet)
                throws BadLocationException {
            int length = s.length();
            if (length == 0) {
                return;
            }

            if (offset + length > maxSize) {
                s = s.substring(0, maxSize - offset);
            }
            super.insertString(offset, s, attributeSet);
        }
        
        public void setMaxSize(int size) {
            maxSize = size;
        }
    }
    
    private class MyTextArea extends JTextArea {
        private MyDocument document;
        
        public MyTextArea (MyDocument d){
            super(d);
            document = d;
        }
        
        public void setMaxSize(int s){
            document.setMaxSize(s);
        }
    }
    
    public TextAreaSize() {
        MyTextArea textArea = new MyTextArea(new MyDocument());
        textArea.setMaxSize(30);
        textArea.setRows(2);
        textArea.setColumns(20);
        
        JPanel panel = new JPanel();
        panel.add(textArea);
        
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setSize(500, 300);
        frame.setVisible(true); 
    }
    
    public static void main(String[] args){
        new TextAreaSize();
    }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


How to make JTextArea display a fixed number of characters each line

There are two ways to achieve this result. One way is to use the setRows and setColumns method to set the size of the JTextArea. The other way is making your text area the subclass of the JTextArea and override the paint() method to get the width and height of the font used. Then, set the size of your text area.

Since for many types of font, the characters do not always have the same widths, some characters are wider than the others, it is better that you use the monospaced font for achieving a constant result.

Following is an example.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class CharInLine {
    private int charWidth = 0;
    private int charHeight = 0;
    private int charPerLine = 30;
 
    public CharInLine() {
        MyTextArea textArea = new MyTextArea();
        textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
     
        //Method 1
        //setting the rows and columns is important for an
        //empty JTextArea to show its size.
        textArea.setRows(5);
        textArea.setColumns(30);
        textArea.setBorder(BorderFactory.createTitledBorder("Text Area"));
     
        //Method 2
        //designate 30 characters per line and 5 lines in the text area
        textArea.setLineWrap(true);
        textArea.setSize(new Dimension(charWidth*charPerLine, charHeight*5));
        //textArea.setPreferredSize(new Dimension(charWidth*charPerLine, charHeight*5));    

        JPanel panel = new JPanel();
        panel.add(textArea);
     
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel,BorderLayout.CENTER);
        frame.setSize(500, 300);
     
        frame.setVisible(true);
    }
 
    private class MyTextArea extends JTextArea {
        @Override
        public void paint(Graphics g){
            super.paint(g);
            FontMetrics fm = g.getFontMetrics();
            charWidth = fm.charWidth('M');
            charHeight = fm.getHeight();
        }
    }
 
    public int getCharWidth() {
        return charWidth;
    }
 
    public static void main(String[] args){
        new CharInLine();
    }
}

Reference:

1. setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, July 3, 2014

Set text style, color, size, font family and print text in multiple lines of JComponent (JLabel, JCheckBox, JRadioButton ...) (2): html

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class JLabelTest extends JFrame {

    public JLabelTest() {
           
        StringBuilder text = new StringBuilder("<html><font ");
        text.append("family='Monospaced' size='18' color='blue' style='bold' ")
                .append("style='background-color: gray;'>")
                .append("My appearance </font><br/>can be<br/><font family='Serif' size='2' ")
                .append("color='red' style='background-color: yellow;'>")
                .append(" very colorful</font></html>");
     
        JLabel label = new JLabel(text.toString());
     
        setLayout(new FlowLayout());
        add(label);
        setSize(700, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
 
    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JLabelTest();
            }
        });
    }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Set text style, color, size and font family of JComponents (JLabel, JCheckBox, JRadioButton ....) (1): attributes and JComponent methods

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.font.TextAttribute;
import java.util.HashMap;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class JLabelTest extends JFrame {

    public JLabelTest(boolean attri) {
        JLabel label = new JLabel("My appearance can be very coloful");
     
        if (!attri){
            //set the font, font style, and font size
            label.setFont(new Font(Font.SERIF, Font.ITALIC, 18));
         
            //set the text color
            label.setForeground(Color.red);
         
            //set the background color
            label.setBackground(Color.yellow);
         
            this.setTitle("Using JComponent methods");
            this.setLocation(100, 100);

        } else {

            HashMap<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();

            attributes.put(TextAttribute.FAMILY, "Monospaced");
            //set text to be bold
            attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
            //set text to be Italic
            attributes.put(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
            attributes.put(TextAttribute.FOREGROUND, Color.BLUE);
            attributes.put(TextAttribute.BACKGROUND, Color.green);
            attributes.put(TextAttribute.SIZE, 18);
         
            label.setFont(new Font(attributes));
            this.setTitle("Using text attributes");
            this.setLocation(100, 300);
        }
     
        setLayout(new FlowLayout());
        add(label);
        setSize(500, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
 
    public static void main(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JLabelTest(false);
                new JLabelTest(true);
            }
        });
    }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, June 27, 2014

How to execute code in a method/constructor after the execution of the method/constructor is finished

To execute certain code after all the other code in the same method/constructor has been executed, you need to create a new thread  and make the new thread to wait util the parent thread finishes execution.

Following is an example.

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FocusTest extends JFrame {
    JTextField f1 = null;
    JButton b1 = null;

    public FocusTest() {
        getContentPane().setLayout(new GridLayout(2,2));
        JLabel label1 = new JLabel("Input 1: ");
        f1 = new JTextField(15);
        b1 = new JButton("button 1");
     
        add(label1);
        add(f1);
        add(b1);
     
        ArrayList<Component> tp = new ArrayList<Component>();
        tp.add(f1);
        tp.add(b1);
     
        //the following code will not work
        //because the layout of button 1 is not realized
        //b1.requestFocusInWindow();
     
        //request focus on button 1
        //after all the other code in the constructor is executed.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               b1.requestFocusInWindow();
           }
        });
     
        b1.addActionListener(new ButtonListener());
        f1.addFocusListener(new F1FocusListener());
     
        b1.setEnabled(false);
     
        pack();
        setVisible(true);
    }
 
    private class F1FocusListener extends FocusAdapter {
        public void focusGained(FocusEvent e){
            if (e.getSource().equals(f1)){
             
                //because button 1 is disabled
                //the following code will do nothing
                //b1.doClick();
             
                //will programmatically click button 1
                //after all the other code in the method is executed.
                javax.swing.SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        b1.doClick();
                    }
                });
             
                b1.setEnabled(true);
            }
        }
    }
 
    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e){
            if (e.getSource() == b1){
                f1.setText("Excellent job!!!!");
            }
        }
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FocusTest();
            }
        }
        );
    }
}

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Set focus to a field in window/frame (2): FocusTraversalPolicy

The FocusTraversalPolicy controls the sequence of fields gaining focus when you tapping through the fields and also the field that has the focus when the window/frame is first constructed/activated/visible.

Following is a sample code.

import java.awt.Component;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FocusTest extends JFrame {
    JTextField f1 = null;
    JTextField f2 = null;
    JButton b1 = null;
    JButton b2 = null;
    public FocusTest() {
        getContentPane().setLayout(new GridLayout(3,2));
        JLabel label1 = new JLabel("Input 1: ");
        JLabel label2 = new JLabel("Input 2: ");
        f1 = new JTextField(15);
        f2 = new JTextField(20);
        b1 = new JButton("button 1");
        b2 = new JButton("button 2");
     
        add(label1);
        add(f1);
        add(label2);
        add(f2);
        add(b1);
        add(b2);

        b1.addActionListener(new ButtonListener());
        b2.addActionListener(new ButtonListener());
     
        ArrayList<Component> tp = new ArrayList<Component>();
        tp.add(f1);
        tp.add(f2);
        tp.add(b1);
        tp.add(b2);
     
        setFocusTraversalPolicyProvider(true);
        setFocusTraversalPolicy(new MyTraversalPolicy(tp));
     
        pack();
        setVisible(true);
    }
 
    private class MyTraversalPolicy extends FocusTraversalPolicy {
        ArrayList<Component> components = null;
        public MyTraversalPolicy(ArrayList<Component> list){
            this.components = list;
        }
     
        public Component getComponentAfter(Container focusCycleRoot, Component focused){
            int idx = components.indexOf(focused);
            if (idx >= components.size()-1){
                idx = -1;
            }
            return components.get(idx+1);
        }
     
        public Component getComponentBefore(Container c, Component focused){
            int idx = components.indexOf(focused);
            if (idx <= 0){
                idx = components.size();
            }
            return components.get(idx-1);
        }
     
        public Component getDefaultComponent(Container c){
            return f2;
        }
     
        public Component getFirstComponent(Container c){
            return components.get(0);
        }
     
        //Set the field of focus 
        //when the window is first activated/contructed/visible
        public Component getInitialComponent(Window w){
            return f2;
        }
     
        public Component getLastComponent(Container c){
            return components.get(components.size()-1);
        }
    }
 
    private class ButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e){
            if (e.getSource() == b1){
                f1.setText("button 1 is pressed");
                f2.setText("");
            } else if (e.getSource() == b2){
                f2.setText("button 2 is pressed");
                f1.setText("");
            }
        }
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FocusTest();
            }
        }
        );
    }
}

            Previous <

Reference:

1. Set focus to a field in java swing when a window/JFrame is first activated/constructed (1): requestFocusInWindow

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, June 26, 2014

Set focus to a field in java swing when a window/JFrame is first activated/constructed/visible (1): requestFocusInWindow

To set focus to a field in a java swing user interface, you can use either the requestFocusInWindow method of java.awt.Component or the java.awt.FocusTraversalPolicy and the setFocusTraversalPolicy method of java.awt.Component.

The requestFocusInWindow method works only after the layout of the component that is going to gain focus in the window/frame is complete, which means it works only after the pack method is called. This can be achieved by either putting the requestFocusInWindow method after the pack method or using the invokeLater method of SwingUtilities to call the requestFocusInWindow method.

Following is a sample code.

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class FocusTest extends JFrame {
    public FocusTest() {
        getContentPane().setLayout(new GridLayout(2,2));
        JLabel label1 = new JLabel("Input 1: ");
        JLabel label2 = new JLabel("Input 2: ");
        JTextField f1 = new JTextField(15);
        JTextField f2 = new JTextField(20);
     
        add(label1);
        add(f1);
        add(label2);
        add(f2);
     
        //the following will not work
         //f2.requestFocusInWindow();

        //the following will work
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
           public void run() {
               f2.requestFocusInWindow();
           }
        });

        pack();
     
        //the following will work
        //f2.requestFocusInWindow();
     
        setVisible(true);
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new FocusTest();
            }
        }
        );
    }
}

                               > Next

Reference:

1. Set focus to a field in window/frame (2): FocusTraversalPolicy

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Friday, May 30, 2014

Setting text styles, colors, font and alignment in JTextPane (2): html

You can also setting the styles, colors, font and other character of the text in JTextPane using html. Following is an example code.

import java.awt.Color;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class HtmlTest extends JTextPane {
 
    public static void main(String[] args){
        //create the JTextPane and set the ContentType to text/html
        HtmlTest test = new HtmlTest();
        test.setContentType("text/html");
        test.setBackground(Color.yellow);
     
        String str = "<p align='center'><font size='14' color='blue' style='background-color: gray;'>Style Test Result</font></p><br/>"+
                    "<font size='8' color='red' style='background-color:green;'>the first line</font><br/>"+
                    "the second line<br/>";
     
        //get the HTMLEditorKit
        HTMLDocument doc = (HTMLDocument)test.getDocument();
        HTMLEditorKit editorKit = (HTMLEditorKit)test.getEditorKit();
        try{
            //insert the text using the HTMLEditorKit
            editorKit.insertHTML(doc, doc.getLength(), str,0,0, null);
        }catch(BadLocationException ble){
            ble.printStackTrace(System.out);
        } catch(IOException ioe){
            ioe.printStackTrace(System.out);
        }
     
        JFrame f = new JFrame("Style Test");
        f.setContentPane(new JScrollPane(test));
        f.setSize(500, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

           Previous <

References

1. Setting text styles, colors, font and alignment in JTextPane (1): attributes

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, May 29, 2014

Setting text styles, colors, font and alignment in JTextPane (1): attributes

JTextPane allows to set font, styles, foreground color, background color, and text alignment for each segment of  the text, which is very difficult to do with JTextArea. Following is a sample code for setting some of this characters in JTextPane.

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

public class AttributeTest extends JTextPane {
    SimpleAttributeSet attributeSet;
 
    public AttributeTest() {
        //create the SimpleAttributeSet
        attributeSet = new SimpleAttributeSet();
    }
 
    public void addString(int fontSize,
            Color foregroundColor,
            Color backgroundColor,
            boolean isBold,
            boolean isItalic,
            int alignment,
            String str) {
        //add the attributes to the SimpleAttributeSet
        StyleConstants.setFontSize(attributeSet, fontSize);
        StyleConstants.setForeground(attributeSet, foregroundColor);
        StyleConstants.setBackground(attributeSet, backgroundColor);
        StyleConstants.setBold(attributeSet, isBold);
        StyleConstants.setItalic(attributeSet, isItalic);
        StyleConstants.setAlignment(attributeSet, alignment);
     
        //set the attribute to the StyledDocument
        int len = this.getText().length();    
        StyledDocument sDoc = this.getStyledDocument();
        sDoc.setCharacterAttributes(len, str.length(), attributeSet, false);

        // Or using the following two lines of code to replace the above two lines of code
       // this.setCaretPosition(len);
      //  this.setCharacterAttributes(attributeSet, false);
   
       //insert the string to the JTextPane
        this.replaceSelection(str);
    }
 
    public static void main(String[] args){
        String[] strs = {"The Third Line\n",
                         "The Second Line\n",
                         "The First Line\n",
                         "Style Test Result\n"
                         };
        AttributeTest test = new AttributeTest();
        for (int i=0; i<strs.length; i++) {
            if (i == 3){
                test.addString(14, Color.blue, Color.LIGHT_GRAY, true, false, StyleConstants.ALIGN_CENTER, strs[i]);
            } else if (i == 2){
                test.addString(11, Color.red, Color.GREEN, false, true, StyleConstants.ALIGN_LEFT, strs[i]);
            } else if (i == 1) {
                test.addString(11, Color.orange, Color.LIGHT_GRAY, false, false, StyleConstants.ALIGN_LEFT, strs[i]);
            } else {
                test.addString(11, Color.black, Color.CYAN, false, false, StyleConstants.ALIGN_LEFT, strs[i]);
            }
        }
        test.setBackground(Color.yellow);
        JFrame f = new JFrame("Style Test");
        f.setContentPane(new JScrollPane(test));
        f.setSize(500, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

                                                    > next

References

1. Setting text styles, colors, font and alignment in JTextPane (2): html

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Order Here

Wednesday, January 15, 2014

Integrating JavaFX code to a Swing package

To take advantage of JavaFX such as smooth animation, web views, audio and video playback, and styles based on Cascading Style Sheets (CSS) in your already built Java Swing project, you can either create a JFXPanel to add to your Swing JFrame, or create a JavaFX Application in your Swing package. You need to add these jars (deploy.jar, jfxrt.jar, plugin.jar, javaws.jar) from your JAVA_HOME\jdk folder\jre\lib directory to your project libraries or class path.

1. Creating a JFXPanel and add it to the JFrame. 


import java.awt.BorderLayout;
import java.awt.Dimension;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class NewFXSwingMain extends JFrame {
 
    private final int JFXPANEL_WIDTH_INT = 300;
    private final int JFXPANEL_HEIGHT_INT = 250;
    private JFXPanel fxContainer;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new NewFXSwingMain();
            }
        });
    }
 
    public NewFXSwingMain() {
        fxContainer = new JFXPanel();
        fxContainer.setPreferredSize(new Dimension(JFXPANEL_WIDTH_INT, JFXPANEL_HEIGHT_INT));
     
        // create JavaFX scene
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                createScene();
            }
        });
     
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Hello");
        add(fxContainer, BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
 
    private void createScene() {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
         //choose one of the panes from javafx.scene.layout
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        fxContainer.setScene(new Scene(root));
    }
}

2. Creating a JavaFX class in your Swing package.


import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class NewFXMain extends Application {
 
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
            }
        });
     
        StackPane root = new StackPane();
        root.getChildren().add(btn);
     
        Scene scene = new Scene(root, 300, 250);
     
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
-------------------------------------------------------------------------------------------------------------------------

References:

1.JavaFX for Swing Developers

Tuesday, January 7, 2014

Make JTable show horizontal scroll bar and automatically resize to the width of the container

It will be nice that when the frame is small, we can use the scroll bar to view the contents of the JTable and when the frame is larger than the JTable size, the table is able to automatically fill up the space. This can be achieved by the following methods

1. Override the method getScrollableTracksViewportWidth() and set the table's auto resize mode to AUTO_RESIZE_OFF.


          JTable table = new JTable() {
                private boolean doingLayout;

                public boolean getScrollableTracksViewportWidth() {
                        return getPreferredSize().width < getParent().getWidth();
                }

        public void doLayout() {
           if (getScrollableTracksViewportWidth()) {
          
               autoResizeMode = AUTO_RESIZE_SUBSEQUENT_COLUMNS;
           }
           doingLayout = true;
           super.doLayout();
           doingLayout = false;
           autoResizeMode = AUTO_RESIZE_OFF;
       }
       public void columnMarginChanged(ChangeEvent e) {
           if (isEditing()) {
               removeEditor();
           }
           TableColumn resizingColumn = getTableHeader().getResizingColumn();
           // Need to do this here, before the parent's
           // layout manager calls getPreferredSize().
           if (resizingColumn != null && autoResizeMode == AUTO_RESIZE_OFF
                   && !doingLayout) {
               resizingColumn.setPreferredWidth(resizingColumn.getWidth());
           }
           resizeAndRepaint();
       }
         }

         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         JScrollPane scrollPane = new JScrollPane(table);
         frame.getContentPane.add(scrollPane);

2. Use a ComponentListener to toggle the auto resize mode of the JTable between AUTO_RESIZE_OFF and AUTO_RESIZE_ALL_COLUMNS.


    table.getParent().addComponentListener(new ComponentAdapter() {
        public void componentResized(final ComponentEvent e) {
            if (jTable.getPreferredSize().width < jTable.getParent().getWidth()) {
                 jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
            } else {
                jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            }
        }
   });
-------------------------------------------------------------------------
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
-----------------------------------------------------------------------------

References: