2014-03-26 212 views
7

我正在制作一个基于文本的游戏,其中用户输入文本来解决游戏。我决定使用java swing来显示文本,并且我希望textPane的背景为黑色。我已经尝试了我找到的所有东西(注释掉),但似乎并非如此。JTextPane背景颜色

private JTextPane blackJTextPane() { 
    //JTextPane area = new JTextPane(); 
    //area.setBackground(Color.BLACK); 
    //area.setForeground(Color.WHITE); 
    JEditorPane area = new JEditorPane(); 

     Color bgColor = Color.BLACK; 
     UIDefaults defaults = new UIDefaults(); 
     defaults.put("EditorPane[Enabled].backgroundPainter", bgColor); 
     area.putClientProperty("Nimbus.Overrides", defaults); 
     area.putClientProperty("Nimbus.Overrides.InheritDefaults", true); 
     area.setBackground(bgColor); 

    return area; 
    } 
public Everything(){ 
    super("Game"); 
    try { 
     UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 
    } catch (Exception exc) { 

     // ignore error 
    } 
    setSize(600,500); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    BorderLayout layout = new BorderLayout(); 
    setLayout(layout); 
    setVisible(true); 

    text = new JLabel(""); 
    text.setText("Text:"); 

    texts = new JTextField(20); 
    texts.setBackground(Color.white); 
    texts.setText(""); 

    JPanel panel = new JPanel(); 

    panel.add(text); 
    panel.add(texts); 

    texts.addActionListener(this); 
    add(panel, BorderLayout.SOUTH); 


    UIDefaults defs = UIManager.getDefaults(); 
    defs.put("TextPane.background", new ColorUIResource(Color.BLACK)); 
    defs.put("TextPane.inactiveBackground", new ColorUIResource(Color.BLACK)); 


    area = blackJTextPane(); 

    area.setEditable(false); 

    style = area.addStyle("style", null); 
    //StyleConstants.setBackground(style, Color.black); 

    JScrollPane pane = new JScrollPane(area); 
    add(pane, BorderLayout.CENTER); 

    doc = area.getStyledDocument(); 

    button.addActionListener(this); 

    setVisible(true); 







} 

进口未图为但也有当我在使用这些注释部分运行游戏没有错误。

回答

9

您可能会遇到Nimbus不尊重背景颜色设置的问题。试试这个来覆盖颜色:

JEditorPane area = new JEditorPane(); 

    Color bgColor = Color.BLACK; 
    UIDefaults defaults = new UIDefaults(); 
    defaults.put("EditorPane[Enabled].backgroundPainter", bgColor); 
    area.putClientProperty("Nimbus.Overrides", defaults); 
    area.putClientProperty("Nimbus.Overrides.InheritDefaults", true); 
    area.setBackground(bgColor); 
+0

我在哪里放这段代码? –

+0

@Slushy_G把它放在'blackJTextPane()'而不是'area.setBackground(Color.BLACK);' – tenorsax

+0

给出错误,我将更新代码以显示新版本 –