Reputation: 174
I want to design a action listener that will create a popup window that will have a combo box containing all the system fonts. To be more specific, I want to design a font selection option like a text editor using Java swing.
How can I do that?
Upvotes: 0
Views: 824
Reputation: 301
Or have a look at my library: https://github.com/dheid/fontchooser
You can include as a Maven dependency. It's very lightweight.
Upvotes: 0
Reputation: 4188
Example based on the three links I posted (that's why this answer is a community wiki, so I can't gain reputation from it):
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Example {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Example();
}
});
}
public Example() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] array = ge.getAvailableFontFamilyNames();
JComboBox<String> box = new JComboBox<String>(array);
box.setEditable(true);
JFrame frame = new JFrame();
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, box, "...", JOptionPane.QUESTION_MESSAGE);
System.out.println(box.getSelectedItem());
}
});
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Upvotes: 3
Reputation: 6119
You should get a list of system fonts available. Put that list to JComboBox and add listeners to that JComboBox.
Get system fonts with this code
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts = e.getAllFonts();
To show the JComboBox for the user with the pop-up use JOptionPane. See tutorial for this https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html#input
Upvotes: 0