Thursday, May 20, 2021

[Java Code Sample] Display all fonts in your computer with JList

Here's a sample code to create a font list which includes all the fonts in your computer.


You can see the preview by clicking an item on the list.


Font type: Arial




Font type: Book Antiqua Italic



Font type: Georgia




Please check the video tutorial for details:




Here's the code:



import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Main {
	
	Font timesNewRoman = new Font("Comic Sans MS", Font.PLAIN, 28);

	public static void main(String[] args) {
		
		new Main();		
	}
	
	public Main(){
		
		JFrame window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
		
		JPanel textPanel = new JPanel();
		textPanel.setBounds(350, 50, 400, 500);
		textPanel.setBackground(Color.black);
		window.add(textPanel);
		
		JTextArea textArea = new JTextArea("It began with the forging of the Great Rings. Three were given to the Elves, immortal, wisest and fairest of all beings. Seven to the Dwarf-Lords, great miners and craftsmen of the mountain halls. And nine, nine rings were gifted to the race of Men, who above all else desire power.");
		textArea.setBounds(350, 50, 400, 500);
		textArea.setBackground(Color.black);
		textArea.setForeground(Color.white);
		textArea.setLineWrap(true);
		textArea.setWrapStyleWord(true);
		textArea.setFont(timesNewRoman);
		textPanel.add(textArea);
		
		JPanel scrollPanePanel = new JPanel();
		scrollPanePanel.setBounds(50, 50, 250, 500);
		scrollPanePanel.setBackground(Color.black);
		window.add(scrollPanePanel);
		
		
		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		
		Font allFonts[] = ge.getAllFonts();
		Vector<String> fontNames = new Vector<String>();
		
		for(int i =0; i < allFonts.length; i++){
			fontNames.addElement(allFonts[i].getName());
		}
		
		JList fontList = new JList(fontNames);
		fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		fontList.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				String s = (String) fontList.getSelectedValue();
				System.out.println(s);
				textArea.setFont(new Font(s,Font.PLAIN,28));
			}		
		});
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setPreferredSize(new Dimension(250, 450));
		scrollPane.getViewport().setView(fontList);
		scrollPanePanel.add(scrollPane);

		window.setVisible(true);		
	}
}



end


No comments:

Post a Comment