Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Changing background color of JEditorPane in Nimbus

843806Dec 22 2008 — edited Oct 2 2011
I've noticed that a simple call to JEditorPane.setBackground(Color) doesn't work in Nimbus. setBackground() seems to work for JTextAreas fine, but not JEditorPane. Why is this? The only workaround I can come up with is to install a BasicEditorPaneUI on my JEditorPane, which will honor the setBackground() call, but then I have to workaround other issues (such as setting the selected text and selection colors to match the rest of Nimbus).

Below is an SSCCE. Any ideas? Is there an easier solution than changing the UI?
import java.awt.*;
import javax.swing.*;
import javax.swing.text.JTextComponent;

public class NimbusTest extends JFrame {

	final Color BACKGROUND = new Color(232,232,255);

	public NimbusTest() {

		JPanel contentPane = new JPanel(new BorderLayout());

		JTextComponent editor = createEditorPane();
		contentPane.add(new JScrollPane(editor));

		setContentPane(contentPane);
		setTitle("Nimbus Test");
		setSize(350, 350);
		setLocationRelativeTo(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

	private JTextComponent createEditorPane() {

		//JTextArea editor = new JTextArea();
		JEditorPane editor = new JEditorPane();

		// Comment this out and JEditorPane BG won't be changed for Nimbus
		if (UIManager.getLookAndFeel().getName().equals("Nimbus")) {
			Color selFG = editor.getSelectedTextColor();
			Color selBG = editor.getSelectionColor();
			editor.setUI(new javax.swing.plaf.basic.BasicEditorPaneUI());
			editor.setSelectedTextColor(selFG);
			editor.setSelectionColor(selBG);
			//editor.setContentType("text/html");
		}

		editor.setBackground(BACKGROUND);

		editor.setText("This is some sample text");
		return editor;

	}


	/**
	 * Program entry point.
	 *
	 * @param args Command line arguments.
	 */
	public static void main(String[] args) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
				} catch (Exception e) {
					e.printStackTrace();
				}
				new NimbusTest().setVisible(true);
			}
		});

	}


}
Edited by: BoBear2681 on Dec 22, 2008 4:51 PM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 30 2011
Added on Dec 22 2008
11 comments
3,764 views