2014-06-17 3 views
0

이것은 지금 당장 가지고있는 나의 gui입니다. 나는 승리의 녹색을 표시하고 손실의 빨간색을 표시하는 스크롤 창을 필요로합니다. 가능한가? 왜냐하면 스크롤바에 제대로 보내지기 전에 색상을 지정할 수 있기 때문입니다.스크롤 패널의 여러 텍스트 색상?

다음은 스크롤 창 부분의 코드입니다.

import javax.swing.*; 
import javax.swing.border.EmptyBorder; 
import javax.swing.text.StyledDocument; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.IOException; 
import java.util.Locale; 
import javax.swing.text.Element; 
import javax.swing.text.Style; 
import javax.swing.text.StyleConstants; 
import json.JsonObject; 
public class dicebot extends JFrame implements ActionListener { 
    static final long serialVersionUID = 1L; 
    private JPanel contentPane; 
    public static String APIKey = null; 
    public static JComboBox<String>cmbCurrency; 
    public static JButton btnLow; 
    public static JButton btnFloat; 
    public static JButton btnHigh; 
    public static JButton btnClearLog; 
    public static JButton btnDonate; 
    public static JTextPane textPane; 
    public static JCheckBox scrollCheck; 
    public static JCheckBox scrollDisable; 
    public static JTextField txtRollAmnt; 
    public static JTextField txtUserName; 
    public static JTextField txtStartBid; 
    public static JTextField txtMultiplier; 
    public static JTextField txtMinRemaining; 
    public static JPasswordField txtPassword; 
    public static JTextField txtOdds; 
    public static JTextField txtMaxBet; 
    public static JTextArea txtInfo; 
    public static JCheckBox RollAmntCheck; 
    public static JLabel lblBalTag; 
    public static JLabel userTag; 
    public static JLabel passTag; 
    public static void main(String[] args) { 
     Locale.setDefault(Locale.US); 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        dicebot frame = new dicebot(); 
        frame.setVisible(true); 
        Dicebotcode d = new Dicebotcode(); 
        d.LoadSettings(); 
        d = null; 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    public dicebot() { 
     setTitle("Dice Bot"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     contentPane.setLayout(new BorderLayout(0, 0)); 
     setContentPane(contentPane); 

     JPanel panel = new JPanel(); 
     contentPane.add(panel, BorderLayout.WEST); 
     GridBagLayout gbl_panel = new GridBagLayout(); 
     gbl_panel.columnWidths = new int[]{0, 0}; 
     gbl_panel.rowHeights = new int[]{0, 0}; 
     gbl_panel.columnWeights = new double[]{0.0, 1.0}; 
     gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE}; 
     panel.setLayout(gbl_panel); 

     //Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique. 
     userTag = new JLabel("Username:"); 
     GridBagConstraints gbc_userTag = new GridBagConstraints(); 
     gbc_userTag.insets = new Insets(0, 0, 0, 5); 
     gbc_userTag.anchor = GridBagConstraints.EAST; 
     gbc_userTag.gridx = 0;//Here are your x + y coords 
     gbc_userTag.gridy = 1;//Adding to x moves left, adding to y moves down 
     panel.add(userTag, gbc_userTag); 

     //Every new textfield needs only the * part to change for it to be valid. (gbc_* =) 
      //textField = new JTextField(); 
     txtUserName = new JTextField(); 
     GridBagConstraints grdUserName = new GridBagConstraints(); 
     grdUserName.fill = GridBagConstraints.HORIZONTAL; 
     grdUserName.gridx = 1; 
     grdUserName.gridy = 1; 
     txtUserName.setColumns(10); 
     panel.add(txtUserName, grdUserName); 
     //panel.add(textField,txtUserName); 
     //textField.setColumns(10); 

    JLabel balTag = new JLabel("Current Balance:"); 
     GridBagConstraints gbc_balTag = new GridBagConstraints(); 
     gbc_balTag.insets = new Insets(0, 0, 0, 5); 
     gbc_balTag.anchor = GridBagConstraints.EAST; 
     gbc_balTag.gridx = 0; 
     gbc_balTag.gridy = 0; 
     panel.add(balTag, gbc_balTag); 

     lblBalTag = new JLabel("[________________]"); 
     lblBalTag.setToolTipText("Balance as of the last call to the peerbet site."); 
     GridBagConstraints gbc_lblBalTag = new GridBagConstraints(); 
     gbc_lblBalTag.insets = new Insets(0, 0, 0, 5); 
     gbc_lblBalTag.anchor = GridBagConstraints.EAST; 
     gbc_lblBalTag.gridx = 1; 
     gbc_lblBalTag.gridy = 0; 
     panel.add(lblBalTag, gbc_lblBalTag); 

     JLabel startTag = new JLabel("Starting Bid:"); 
     GridBagConstraints gbc_startTag = new GridBagConstraints(); 
     gbc_startTag.insets = new Insets(0, 0, 0, 5); 
     gbc_startTag.anchor = GridBagConstraints.EAST; 
     gbc_startTag.gridx = 0; 
     gbc_startTag.gridy = 3; 
     panel.add(startTag, gbc_startTag); 

     txtStartBid = new JTextField(); 
     GridBagConstraints grdStartBid = new GridBagConstraints(); 
     grdStartBid.fill = GridBagConstraints.HORIZONTAL; 
     grdStartBid.gridx = 1; 
     grdStartBid.gridy = 3; 
     txtStartBid.setText("0.00000010"); 
     txtStartBid.setEnabled(false); 
     panel.add(txtStartBid, grdStartBid); 

     JLabel multTag = new JLabel("Multiplier:"); 
     GridBagConstraints gbc_multTag = new GridBagConstraints(); 
     gbc_multTag.insets = new Insets(0, 0, 0, 5); 
     gbc_multTag.anchor = GridBagConstraints.EAST; 
     gbc_multTag.gridx = 0; 
     gbc_multTag.gridy = 4; 
     panel.add(multTag, gbc_multTag); 

     txtMultiplier = new JTextField(); 
     GridBagConstraints grdMultiplier = new GridBagConstraints(); 
     grdMultiplier.fill = GridBagConstraints.HORIZONTAL; 
     grdMultiplier.gridx = 1; 
     grdMultiplier.gridy = 4; 
     txtMultiplier.setColumns(10); 
     txtMultiplier.setText("2"); 
     txtMultiplier.setEnabled(false); 
     panel.add(txtMultiplier, grdMultiplier); 

     JLabel minTag = new JLabel("Min Remaining:"); 
     GridBagConstraints gbc_minTag = new GridBagConstraints(); 
     gbc_minTag.insets = new Insets(0, 0, 0, 5); 
     gbc_minTag.anchor = GridBagConstraints.EAST; 
     gbc_minTag.gridx = 0; 
     gbc_minTag.gridy = 5; 
     panel.add(minTag, gbc_minTag); 

     txtMinRemaining = new JTextField(); 
     GridBagConstraints grdMinRemaining = new GridBagConstraints(); 
     grdMinRemaining.fill = GridBagConstraints.HORIZONTAL; 
     grdMinRemaining.gridx = 1; 
     grdMinRemaining.gridy = 5; 
     txtMinRemaining.setColumns(10); 
     txtMinRemaining.setText("0"); 
     txtMinRemaining.setEnabled(false); 
     panel.add(txtMinRemaining, grdMinRemaining); 

     txtPassword = new JPasswordField(); 
     GridBagConstraints grdPassword = new GridBagConstraints(); 
     grdPassword.fill = GridBagConstraints.HORIZONTAL; 
     grdPassword.gridx = 1; 
     grdPassword.gridy = 2; 
     txtPassword.setEchoChar('*'); 
     txtPassword.setColumns(10); 
     panel.add(txtPassword, grdPassword); 

     passTag = new JLabel("Password:"); 
     GridBagConstraints gbc_passTag = new GridBagConstraints(); 
     gbc_passTag.insets = new Insets(0, 0, 0, 5); 
     gbc_passTag.anchor = GridBagConstraints.EAST; 
     gbc_passTag.gridx = 0; 
     gbc_passTag.gridy = 2; 
     panel.add(passTag, gbc_passTag); 

     txtOdds = new JTextField(); 
     GridBagConstraints grdOdds = new GridBagConstraints(); 
     grdOdds.fill = GridBagConstraints.HORIZONTAL; 
     grdOdds.gridx = 1; 
     grdOdds.gridy = 6; 
     txtOdds.setColumns(10); 
     txtOdds.addActionListener(this); 
     txtOdds.setText("49.5"); 
     txtOdds.setEnabled(false); 
     panel.add(txtOdds, grdOdds); 

     JLabel oddsTag = new JLabel("Odds %:"); 
     GridBagConstraints gbc_oddsTag = new GridBagConstraints(); 
     gbc_oddsTag.insets = new Insets(0, 0, 0, 5); 
     gbc_oddsTag.anchor = GridBagConstraints.EAST; 
     gbc_oddsTag.gridx = 0; 
     gbc_oddsTag.gridy = 6; 
     panel.add(oddsTag, gbc_oddsTag); 

     txtMaxBet = new JTextField(); 
     GridBagConstraints grdMaxBet = new GridBagConstraints(); 
     grdMaxBet.fill = GridBagConstraints.HORIZONTAL; 
     grdMaxBet.gridx = 1; 
     grdMaxBet.gridy = 7; 
     txtMaxBet.setColumns(10); 
     txtMaxBet.setText("1"); 
     txtMaxBet.setEnabled(false); 
     panel.add(txtMaxBet, grdMaxBet); 

    txtRollAmnt = new JTextField(); 
     GridBagConstraints grdRollAmnt = new GridBagConstraints(); 
     grdRollAmnt.fill = GridBagConstraints.HORIZONTAL; 
     grdRollAmnt.gridx = 1; 
     grdRollAmnt.gridy = 8; 
     txtRollAmnt.setColumns(10); 
     txtRollAmnt.setText("0=Infinite"); 
     txtRollAmnt.setEnabled(false); 
     panel.add(txtRollAmnt, grdRollAmnt); 

    RollAmntCheck = new JCheckBox("Roll Then Quit:"); 
     RollAmntCheck.setSelected(true); 
    GridBagConstraints grdRollAmntCheck = new GridBagConstraints(); 
     grdRollAmntCheck.fill = GridBagConstraints.HORIZONTAL; 
     grdRollAmntCheck.gridx = 0; 
     grdRollAmntCheck.gridy = 8; 
     panel.add(RollAmntCheck, grdRollAmntCheck); 

     //This is the Combo Box 
     cmbCurrency = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"}); 
     GridBagConstraints gbc_list = new GridBagConstraints(); 
     gbc_list.fill = GridBagConstraints.HORIZONTAL; 
     gbc_list.gridx = 1; 
     gbc_list.gridy = 9; 
     cmbCurrency.addActionListener(this); 
     cmbCurrency.setEnabled(false); 
     panel.add(cmbCurrency, gbc_list); 

     JLabel maxTag = new JLabel("MaxBet:"); 
     GridBagConstraints gbc_maxTag = new GridBagConstraints(); 
     gbc_maxTag.insets = new Insets(0, 0, 0, 5); 
     gbc_maxTag.anchor = GridBagConstraints.EAST; 
     gbc_maxTag.gridx = 0; 
     gbc_maxTag.gridy = 7; 
     panel.add(maxTag, gbc_maxTag); 

     JPanel panel_1 = new JPanel(); 
     contentPane.add(panel_1, BorderLayout.SOUTH); 
     panel_1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); 

     btnDonate = new JButton("Login"); 
     btnDonate.addActionListener(this); 
     panel_1.add(btnDonate); 

     btnHigh = new JButton("Roll High"); 
     btnHigh.addActionListener(this); 
     btnHigh.setEnabled(false); 
     panel_1.add(btnHigh); 

     btnLow = new JButton("Roll Low"); 
     btnLow.addActionListener(this); 
     btnLow.setEnabled(false); 
     panel_1.add(btnLow); 

     btnFloat = new JButton("Roll Float"); 
     btnFloat.addActionListener(this); 
     btnFloat.setEnabled(false); 
     btnFloat.setVisible(false); 
     panel_1.add(btnFloat); 

     btnClearLog = new JButton("Clear Log"); 
     btnClearLog.addActionListener(this); 
     panel_1.add(btnClearLog); 

     scrollCheck = new JCheckBox("Auto-Scroll"); 
     scrollCheck.setSelected(true); 
     panel_1.add(scrollCheck); 

     scrollDisable = new JCheckBox("Disable Log"); 
     scrollDisable.setSelected(false); 
     panel_1.add(scrollDisable); 

     btnClearLog.setToolTipText("Click here to clear the log!"); 
     btnHigh.setToolTipText("Click here to Roll High!"); 
     btnLow.setToolTipText("Click here to Roll Low!"); 
     btnFloat.setToolTipText("Click here to Roll?"); 
     scrollCheck.setToolTipText("Toggles the auto-scroll function of the log."); 
     RollAmntCheck.setToolTipText("Roll Amount then Quit"); 
     txtMaxBet.setToolTipText("The dicebot will not bet above amount entered in."); 
     txtOdds.setToolTipText("What odds(%) will the dicebot be rolling?"); 
     txtPassword.setToolTipText("Enter your peerbet account password."); 
     txtMinRemaining.setToolTipText("The bot will stop when account has less than this amount in bank."); 
     txtMultiplier.setToolTipText("What shall the bet be multiplied by upon loss?"); 
     txtStartBid.setToolTipText("What amount should the bot start each bet at?"); 
     txtUserName.setToolTipText("Enter your peerbet account username."); 
     lblBalTag.setToolTipText("Current amount of chosen currency shown here."); 
     cmbCurrency.setToolTipText("Choose the currency that the bot will be using to roll with."); 

     contentPane.add(textPane, BorderLayout.CENTER); 
     txtInfo = new JTextArea("All number formats must use a period(.)\nBot By: MichaelAdair and DalinSprocket\n"); 
     txtInfo.setColumns(35); 
     txtInfo.setEnabled(false); 

    textPane = new JTextPane(); 
     textPane.setBackground(Color.DARK_GRAY); 
     textPane.setEditable(false); 
     textPane.setMargin(null); 
     textPane.setContentType("text/html"); 

    StyledDocument doc = textPane.getStyledDocument(); 

     Style style = textPane.addStyle("Loss",null); 
     StyleConstants.setForeground(style, Color.red); 

    Style style2 = textPane.addStyle("Win",null); 
     StyleConstants.setForeground(style, Color.green); 
     pack(); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if (e.getSource() == cmbCurrency) { 
      if (cmbCurrency.getSelectedIndex() == 0){ 
       txtStartBid.setText("0.00000010"); 
      }else{ 
       txtStartBid.setText("0.0001"); 
      } 
      if(APIKey != null){ 
       String balance = peerbetapi.get_balance(dicebot.APIKey); 
       JsonObject jsonObject = JsonObject.readFrom(balance); 
       if(jsonObject.get("status").asInt() == 1){ 
        lblBalTag.setText(jsonObject.get("raffle_cur" + Integer.toString((cmbCurrency.getSelectedIndex() + 10))).asString()); 
       } 
      }else{ 
       lblBalTag.setText("[________________]"); 
      } 
     }else if (e.getSource() == btnLow){ 
      if(btnLow.getText() == "Roll Low"){ 
       btnHigh.setText("Stop"); 
       btnLow.setText("Stop On Win"); 
       btnFloat.setEnabled(false); 
       Dicebotcode dbc = new Dicebotcode(); 
       Dicebotcode.RollType = "low"; 
       Dicebotcode.StopRollingOnWin = false; 
       Dicebotcode.StopRolling = false; 
       dbc.dbc(); 
      }else{ 
       // The EnableAllFields function will re-enable the buttons once its done. 
       btnLow.setText("Waiting..."); 
       btnLow.setEnabled(false); 
       Dicebotcode.StopRollingOnWin = true; 
      } 
     }else if (e.getSource() == btnHigh){ 
      if(btnHigh.getText() == "Roll High"){ 
       btnHigh.setText("Stop"); 
       btnLow.setText("Stop On Win"); 
       btnFloat.setEnabled(false); 
       Dicebotcode dbc = new Dicebotcode(); 
       Dicebotcode.RollType = "high"; 
       Dicebotcode.StopRollingOnWin = false; 
       Dicebotcode.StopRolling = false; 
       dbc.dbc(); 
      }else{ 
       // The EnableAllFields function will re-enable the buttons once its done. 
       btnHigh.setText("Stopping..."); 
       btnHigh.setEnabled(false); 
       btnLow.setEnabled(false); 
       Dicebotcode.StopRolling = true; 
      } 
     }else if (e.getSource() == btnFloat){ 
      if(btnFloat.getText() == "Roll Float"){ 
       btnHigh.setText("Stop"); 
       btnLow.setText("Stop On Win"); 
       btnFloat.setEnabled(false); 
       Dicebotcode dbc = new Dicebotcode(); 
       Dicebotcode.RollType = "float"; 
       Dicebotcode.StopRollingOnWin = false; 
       Dicebotcode.StopRolling = false; 
       dbc.dbc(); 
      }else{ 
       // The EnableAllFields function will re-enable the buttons once its done. 
       btnFloat.setText("Stopping..."); 
       btnFloat.setEnabled(false); 
       Dicebotcode.StopRolling = true; 
      } 
     }else if (e.getSource() == btnClearLog){ 
      txtInfo.setText(""); 
     }else if (e.getSource() == btnDonate){ 
      //donate d = new donate(); 
      if(btnDonate.getText() == "Login"){ 
       String reply = null; 
       try { 
        reply = peerbetapi.login(txtUserName.getText(), String.copyValueOf(txtPassword.getPassword())); 
       } catch (IOException e1) { 
        reply = "{\"status\":0, \"message\":\"An unknown error has occurred while attempting to login.\"}"; 
       } 
       JsonObject json = JsonObject.readFrom(reply); 
       if(json.get("status").asInt() != 1){ 
        txtInfo.append("Error: " + json.get("message").asString() + "\n"); 
        txtInfo.setCaretPosition(txtInfo.getText().length()); 
       }else{ 
        APIKey = json.get("key").asString(); 
        lblBalTag.setText(json.get("raffle_cur" + Integer.toString(cmbCurrency.getSelectedIndex() + 10)).asString()); 
        btnDonate.setText("Donate"); 
        userTag.setVisible(false); 
        txtUserName.setVisible(false); 
        passTag.setVisible(false); 
        txtPassword.setVisible(false); 
        txtStartBid.setEnabled(true); 
        txtMultiplier.setEnabled(true); 
        txtMinRemaining.setEnabled(true); 
        txtOdds.setEnabled(true); 
        txtMaxBet.setEnabled(true); 
        cmbCurrency.setEnabled(true); 
        btnHigh.setEnabled(true); 
        btnLow.setEnabled(true); 
        btnFloat.setEnabled(true); 
        txtInfo.append("Login successful!\n"); 
        txtInfo.setCaretPosition(txtInfo.getText().length()); 
       } 
      }else{ 
       donate.showdonate(); 
      } 
     } 
    } 
} 

오류 :

java.lang.NullPointerException 
    at java.awt.Container.addImpl(Container.java:1086) 
    at java.awt.Container.add(Container.java:966) 
    at dicebot.<init>(dicebot.java:298) 
    at dicebot$1.run(dicebot.java:44) 
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) 
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733) 
    at java.awt.EventQueue.access$200(EventQueue.java:103) 
    at java.awt.EventQueue$3.run(EventQueue.java:694) 
    at java.awt.EventQueue$3.run(EventQueue.java:692) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:703) 
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) 
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) 
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) 
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) 
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) 
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) 
+0

을 가정한다. 한 단어/문자에 설정된 속성은 전체 문서에서 사용됩니다. 대답의 말대로, 「JTextPane/JEditorPane」가이 요구에 가장 적합합니다. 하나의 [예] (http://stackoverflow.com/a/9651404/1057230) 및 다른 [예] (http://stackoverflow.com/a/9652143/1057230) –

답변

2

한 가지 방법에는 3 가지 변수가 있습니다. 너는 이것을 못해. 또한 addStyle에 올바른 수의 인수를 전달하지 않습니다.

는 JTextPane가 스타일을 사용하는 완전한 예를 들어 http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneStylesExample6.htm를 참조하십시오 :`JTextArea` 만 일반 텍스트를 즐겁게

/* 
Core SWING Advanced Programming 
By Kim Topley 
ISBN: 0 13 083292 8  
Publisher: Prentice Hall 
*/ 



import javax.swing.*; 
import javax.swing.text.*; 
import java.awt.*; 

public class StylesExample6 { 
    public static void main(String[] args) { 
    try { 
     UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); 
    } catch (Exception evt) {} 

    JFrame f = new JFrame("Styles Example 6"); 

    // Create the StyleContext, the document and the pane 
    StyleContext sc = new StyleContext(); 
    final DefaultStyledDocument doc = new DefaultStyledDocument(sc); 
    final JTextPane pane = new JTextPane(doc); 

    // Create and add the main document style 
    Style defaultStyle = sc.getStyle(StyleContext.DEFAULT_STYLE); 
    final Style mainStyle = sc.addStyle("MainStyle", defaultStyle); 
    StyleConstants.setLeftIndent(mainStyle, 16); 
    StyleConstants.setRightIndent(mainStyle, 16); 
    StyleConstants.setFirstLineIndent(mainStyle, 16); 
    StyleConstants.setFontFamily(mainStyle, "serif"); 
    StyleConstants.setFontSize(mainStyle, 12); 

    // Create and add the constant width style 
    final Style cwStyle = sc.addStyle("ConstantWidth", null); 
    StyleConstants.setFontFamily(cwStyle, "monospaced"); 
    StyleConstants.setForeground(cwStyle, Color.green); 

    // Create and add the heading style 
    final Style heading2Style = sc.addStyle("Heading2", null); 
    StyleConstants.setForeground(heading2Style, Color.red); 
    StyleConstants.setFontSize(heading2Style, 16); 
    StyleConstants.setFontFamily(heading2Style, "serif"); 
    StyleConstants.setBold(heading2Style, true); 
    StyleConstants.setLeftIndent(heading2Style, 8); 
    StyleConstants.setFirstLineIndent(heading2Style, 0); 

    try { 
     SwingUtilities.invokeAndWait(new Runnable() { 
     public void run() { 
      try { 
      // Set the logical style 
      doc.setLogicalStyle(0, mainStyle); 

      // Add the text to the document 
      doc.insertString(0, text, null); 

      // Apply the character attributes 
      doc.setCharacterAttributes(49, 13, cwStyle, false); 
      doc.setCharacterAttributes(223, 14, cwStyle, false); 
      doc.setCharacterAttributes(249, 14, cwStyle, false); 
      doc.setCharacterAttributes(286, 8, cwStyle, false); 
      doc.setCharacterAttributes(475, 14, cwStyle, false); 
      doc.setCharacterAttributes(497, 21, cwStyle, false); 
      doc.setCharacterAttributes(557, 9, cwStyle, false); 
      doc.setCharacterAttributes(639, 12, cwStyle, false); 
      doc.setCharacterAttributes(733, 21, cwStyle, false); 
      doc.setCharacterAttributes(759, 9, cwStyle, false); 

      // Finally, apply the style to the heading 
      doc.setParagraphAttributes(0, 1, heading2Style, false); 

      // Set the foreground color and change the font 
      pane.setForeground(Color.pink); 
      pane.setFont(new Font("Monospaced", Font.ITALIC, 24)); 
      } catch (BadLocationException e) { 
      } 
     } 
     }); 
    } catch (Exception e) { 
     System.out.println("Exception when constructing document: " + e); 
     System.exit(1); 
    } 

    f.getContentPane().add(new JScrollPane(pane)); 
    f.setSize(400, 300); 
    f.setVisible(true); 
    } 

    public static final String text = 
      "Attributes, Styles and Style Contexts\n" + 
      "The simple PlainDocument class that you saw in the previous " + 
      "chapter is only capable of holding text. The more complex text " + 
      "components use a more sophisticated model that implements the " + 
      "StyledDocument interface. StyledDocument is a sub-interface of " + 
      "Document that contains methods for manipulating attributes that " + 
      "control the way in which the text in the document is displayed. " + 
      "The Swing text package contains a concrete implementation of " + 
      "StyledDocument called DefaultStyledDocument that is used as the " + 
      "default model for JTextPane and is also the base class from which " + 
      "more specific models, such as the HTMLDocument class that handles " + 
      "input in HTML format, can be created. In order to make use of " + 
      "DefaultStyledDocument and JTextPane, you need to understand how " + 
      "Swing represents and uses attributes.\n"; 

} 
+0

그 부분이 수정되었지만 런타임 오류가 발생했습니다 ... – michaeladair

+0

"Null 포인터 예외 란 무엇이며 어떻게 수정합니까?" http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – DavidPostill

+0

나는 아직도 내가해야 할 일을 이해하지 못한다 ... 죄송합니다, 나는 Java에 대한 멍청한 행동입니다 ... – michaeladair

3

텍스트의 색상이 JScrollPane의와는 아무 상관이있다. JTextPane 또는 JEditorPane 등, 복수의 색을 지원하는 텍스트 컴퍼넌트를 사용합니다. 추천 읽기 : http://docs.oracle.com/javase/tutorial/uiswing/components/text.html

+0

그래서 JtextPane 같은? – michaeladair

+0

그래, 그걸 시도했을 때 무슨 일이 있었 니? –

+0

위의 업데이트 된 코드를 보면 오류가 발생했습니다 ... – michaeladair

관련 문제