JAVA Swing 设置字体属性

运行效果

JAVA Swing 设置字体属性

代码

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class demo extends JFrame {
    JTextArea text;

    JComboBox fonts,sizes,colors;
    JButton ensure,cancel;
    String[] font ={"宋体","黑体","楷体","仿宋"};
    String[] size ={"10号","12号","14号","16号"};
    String[] color = {"黑色","红色","绿色","蓝色"};
    int[] sizeen={10,12,14,16};
    Color[] coloren = {Color.BLACK,Color.RED,Color.GREEN,Color.BLUE};
    public demo(){
        this.setLayout(new GridLayout(1,2));
        text = new JTextArea("这是一个多行文本框,你可以使用右边的选项来设置字体",3,15);
        text.setLineWrap(true);
        text.setFont(new Font("宋体",Font.PLAIN,10));
        this.add(text);

        JPanel panel = new JPanel(new GridLayout(5,2));
        panel.add(new JLabel("字体设置"));
        panel.add(new JLabel());
        panel.add(new JLabel("字体:"));
        panel.add(fonts=new JComboBox(font));
        panel.add(new JLabel("字号:"));
        panel.add(sizes=new JComboBox(size));
        panel.add(new JLabel("颜色:"));
        panel.add(colors=new JComboBox(color));
        panel.add(ensure=new JButton("确定"));
        panel.add(cancel=new JButton("取消"));
        this.add(panel);
        ActionListen actionListen = new ActionListen();
        fonts.addActionListener(actionListen);
        sizes.addActionListener(actionListen);
        colors.addActionListener(actionListen);
        ensure.addActionListener(actionListen);
        cancel.addActionListener(actionListen);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setVisible(true);
        this.setSize(350,150);
    }
    class ActionListen implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            int f = fonts.getSelectedIndex();
            int s = sizes.getSelectedIndex();
            int c = colors.getSelectedIndex();


            Object source = e.getSource();
            if (source.equals(ensure)){
                text.setFont(new Font(font[f],Font.PLAIN,sizeen[s]));
                text.setForeground(coloren[c]);
            }
            else if (source.equals(cancel)){
                text.setFont(new Font(font[0],Font.PLAIN,sizeen[0]));
                text.setForeground(coloren[0]);
                fonts.setSelectedIndex(0);
                sizes.setSelectedIndex(0);
                colors.setSelectedIndex(0);
            }
        }
    }

    public static void main(String[] args) {
        new demo();
    }
}
上一篇:BoxSizer布局


下一篇:全网最全面的python的讲解,讲的无可挑剔《记得收藏》