Thursday, July 3, 2014

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.

No comments:

Post a Comment