我問如何選擇在組合框中的值而不會失去JEditorPane的重點/選擇。
當您從組合框中選擇一個項目時,不會丟失在編輯器窗格中選擇的文本。選擇依然存在,但只有在編輯器窗格重新獲得焦點後才能進行繪製。
所以最簡單的方法是使用JMenuItem。請閱讀Swing教程Text Component Features中的一節,以獲取相關示例。
如果你仍然想使用組合框,那麼你可以在你的ActionListener
添加整數值組合框然後代碼組合框看起來是這樣的:
@Override
public void actionPerformed(ActionEvent e)
{
Integer value = (Integer)comboBox.getSelectedItem();
Action action = new StyledEditorKit.FontSizeAction("Font size", value);
action.actionPerformed(null);
}
的StyledEditorKit
行動從延長TextAction
。 TextAction
知道有焦點的最後一個文本組件,因此字體更改應用於該文本組件。
如果你真的想要的文本字段顯示選擇,那麼你需要創建一個自定義Caret
和覆蓋focusLost
方法不調用setSelectionVisible(false)
(這是默認的行爲。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public class DefaultCaretTest extends JFrame
{
public DefaultCaretTest()
{
JTextField textField1 = new JTextField("Text Field1 ");
JTextField textField2 = new JTextField("Text Field2 ");
textField1.setCaret(new SelectionCaret());
textField2.setCaret(new SelectionCaret());
textField1.select(5, 11);
textField2.select(5, 11);
((DefaultCaret)textField2.getCaret()).setSelectionVisible(true);
add(textField1, BorderLayout.WEST);
add(textField2, BorderLayout.EAST);
}
static class SelectionCaret extends DefaultCaret
{
public SelectionCaret()
{
setBlinkRate(UIManager.getInt("TextField.caretBlinkRate"));
}
public void focusGained(FocusEvent e)
{
setVisible(true);
setSelectionVisible(true);
}
public void focusLost(FocusEvent e)
{
setVisible(false);
}
}
public static void main(String[] args)
{
DefaultCaretTest frame = new DefaultCaretTest();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
當然。當焦點在任何其他組件,而不僅僅是組合框中選擇將保持
您還可以使用:
comboBox.setFocusable(false);
由於組合框無法獲得焦點,焦點將保留在文本組件上,但問題在於用戶將無法使用鍵盤從組合框中選擇字體大小。正確的GUI設計總是允許用戶使用鍵盤或鼠標來執行操作。
[As really basic example](http://stackoverflow.com/questions/18948148/jeditorpane-set-foreground-color-for-different-words/18948340#18948340)如何將不同的樣式應用到JEditorPane ' – MadProgrammer
感謝您的迴應,我很喜歡實際應用樣式(這裏沒有顯示這些樣例以保持較小的樣式)。問題是在編輯器窗格中選擇文本時獲取組合框輸入。 – Amber