我正在用Java swing编写电子邮件应用程序。我希望用户可以在写电子邮件时更改字体,但是我不确定该怎么做。我创建了一个具有所有字体的JComboBox。
我想我应该使用getSelectedItem()
并向JComboBox添加actionListener以便将此信息传递给JTextArea?还是有其他方法?这是我的代码:
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
JComboBox comboBox = new JComboBox(fonts);// create a combo box with the array
comboBox.setFont(new Font("Times New Roman", Font.PLAIN, 12));// set the font
comboBox.setBounds(21, 6, 193, 25);// set size and location
add(comboBox);
我应该如何使所有文本字段根据comboBox中的选定项目更改字体?
在这里,您可以找到一个简单的主方法中嵌入的您所要询问的工作示例(如果我理解正确的话)。
为了简单起见,我只使用了一个组合框来选择字体名称,但是最好另外放置两个组合以使字体大小和样式(粗体,普通,斜体)也可以选择。
基本上是,最常见的方法是将actionListener绑定到comboBox,以便在comboBox与用户进行交互时更改字体。确保这不是唯一的方法,您甚至可以侦听按下键盘上的按键来触发操作,或者实现某种其他方法来识别用户的更改字体的意图,但据我所知,我在例子是最简单的方法。
package fontchooser;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComboFont {
// Put this in other two combo-boxes if you want to make these selectable by user
public static int default_size = 16;
public static int default_style = Font.PLAIN;
public static void main(String[] args) {
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[] {400};
layout.rowHeights = new int[] {100,300};
JFrame container = new JFrame();
container.setLayout(layout);
container.setBounds(150,150,400,400);
container.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComboBox<String> comboFontNames = new JComboBox<String>(fonts);
JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(textArea);
GridBagConstraints comboContraints = new GridBagConstraints();
comboContraints.gridx = 0;
comboContraints.gridy = 0;
// This only set font to display on combo
comboFontNames.setFont(new Font("Times New Roman", Font.PLAIN, 12));
container.add(comboFontNames, comboContraints);
GridBagConstraints scrollerContraints = new GridBagConstraints();
scrollerContraints.gridx = 0;
scrollerContraints.gridy = 1;
scrollerContraints.gridwidth = 400;
scrollerContraints.fill = GridBagConstraints.BOTH;
container.add(scrollPane, scrollerContraints);
// Variant of action listener with lambda (since java 8)
comboFontNames.addActionListener((e) -> {
String selectedFamilyName = (String)comboFontNames.getSelectedItem();
Font selectedFont = new Font(selectedFamilyName, default_style, default_size);
textArea.setFont(selectedFont);
textArea.repaint();
});
container.setVisible(true);
}
}
我希望这就是您所需要的!再见
Alessio