想要擁有一個JTextPane,其內容始終可以由用戶選擇。因此,我創建了自己的JTextPane的子類,並始終在方法「isEnabled()」中返回true。另外我介紹一個新成員m_enabled,它負責返回正確的前景色(啓用/禁用)。JTextPane和前景色
它按預期工作,但如果我設置了默認的前景色(例如Color.RED)並在啓用和禁用之間切換,則前景色不再是紅色。
你能幫我解決這個問題嗎?
public class StylesExample1 {
public static final String text = "Lorem ipsum dolor...";
public static boolean m_enabled = true;
public static void main(String[] args) throws BadLocationException {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception evt) {
}
JFrame f = new JFrame("Frame");
final JTextPane pane = new MyPane();
pane.setText(text);
pane.setPreferredSize(new Dimension(200, 200));
f.getContentPane().add(pane);
JButton b = new JButton("Toggle Enabled state");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_enabled = !m_enabled;
System.err.println("setting textpane enabled to " + m_enabled);
pane.setEnabled(m_enabled);
}
});
pane.setForeground(Color.red);
f.getContentPane().add(b);
f.getContentPane().setLayout(new FlowLayout());
f.setSize(400, 300);
f.setVisible(true);
}
}
class MyPane extends JTextPane {
private static final long serialVersionUID = 1L;
private boolean m_enabled = true;
private Color defaultForegroundColor, disabledTextColor;
public MyPane() {
defaultForegroundColor = getForeground();
disabledTextColor = getDisabledTextColor();
}
public void setEnabled(boolean enabled) {
m_enabled = enabled;
if (m_enabled) {
setForeground(defaultForegroundColor);
} else {
setForeground(disabledTextColor);
}
}
@Override
public boolean isEnabled() {
return true;
}
}
,但如果我想改變構造後的前景色了所謂? – matthias
我已經修改了相應的答案 – Fallso