gpt4 book ai didi

java - 使用 JComboBox 在 JEditorPane 中设置所选文本的字体大小

转载 作者:行者123 更新时间:2023-11-29 05:58:04 28 4
gpt4 key购买 nike

如何在 JEditorPane( Pane )使用 JComboBox 中设置所选文本的字体大小?

以前我用过:

toolbar.add(new StyledEditorKit.FontSizeAction("12", 12));

但是您不能简单地拥有数百个按钮。

最佳答案

我不知道执行此操作的规范方法,但在实验中,这是可行的:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;

public class EditorPaneFun extends JPanel {
private static final Integer[] ITEMS = { 9, 10, 11, 12, 14, 16, 18, 20, 24,
32 };
private JEditorPane editorPane = new JEditorPane();
private JComboBox<Integer> fontBox = new JComboBox<Integer>(ITEMS);
private StyledDocument doc = new DefaultStyledDocument();
private StyledEditorKit styledEditorKit = new StyledEditorKit();

public EditorPaneFun() {
editorPane.setDocument(doc);
editorPane.setEditorKit(styledEditorKit);
JScrollPane scrollpane = new JScrollPane(editorPane);
scrollpane.setPreferredSize(new Dimension(500, 400));
JPanel comboPanel = new JPanel();
comboPanel.add(fontBox);

setLayout(new BorderLayout());
add(scrollpane, BorderLayout.CENTER);
add(comboPanel, BorderLayout.SOUTH);

Document doc = editorPane.getDocument();
for (int i = 0; i < 20; i++) {
int offset = doc.getLength();
String str = "This is line number: " + i + "\n";
try {
doc.insertString(offset, str, null);
} catch (BadLocationException e) {
e.printStackTrace();
}
}

fontBox.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
int size = (Integer) fontBox.getSelectedItem();
Action fontAction = new StyledEditorKit.FontSizeAction(String
.valueOf(size), size);
fontAction.actionPerformed(e);
}
});
}

private static void createAndShowGui() {
JFrame frame = new JFrame("EditorPaneFun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new EditorPaneFun());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

请注意,这仅在 Document 是 DefaultStyledDocument 且 EditorKit 是 StyledEditorKit 时有效。

关于java - 使用 JComboBox 在 JEditorPane 中设置所选文本的字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11275113/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com