java - 滚动 Pane 中的多种文本颜色?

标签 java swing colors jscrollpane scrollpane

这是我现在拥有的图形用户界面,我需要滚动 Pane 在获胜时显示绿色,在失败时显示红色。是否可以?因为,我也许可以在将其发送到滚动 Pane 之前对其进行着色,对吗?

这是滚动 Pane 部分的代码。

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)

最佳答案

文本的颜色与 JScrollPane 无关。使用支持多种颜色的文本组件,例如 JTextPane 或 JEditorPane。推荐阅读:http://docs.oracle.com/javase/tutorial/uiswing/components/text.html

关于java - 滚动 Pane 中的多种文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24268062/

相关文章:

java - 错误的值类:org.apache.mahout.math.VarLongWritable不是类org.apache.mahout.math.VectorWritable

java - AAR 传递依赖 Google 位置服务

java - JFormattedTextField 和 NumberFormat 与 Float 一起使用

java - 当我运行程序时,如何使 JFrame 中的圆圈随机化

C# 应用程序范围的颜色管理

javascript - jQuery 彩色动画

powershell - 一个命令中的 Powershell 中的多种前景色,包括空格

java - 从请求中提取json参数

java - 如何根据感兴趣区域周围的设计去除图像的背景?

java GridBagLayout 不工作?