How to debug a Swing button that causes an error? - java

I am doing a computer studies controlled assessment. This is an encryption/decryption program. However, I am trying to listen to a button in one class called Gui_Maker, which makes the GUI and all the swing elements. I then want to pass the information to a method in another class called Computerscience. However every time I press the button I get an error.
I am not advanced at all in Java, and it would help if any explanation gave any code I should put into my program, and explained in laymen's terms.
Here's my code:
package computerscience;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class Gui_Maker implements ActionListener {
Computerscience computerscience = new Computerscience();
JButton btnEncrypt = new JButton("Encrypt");
JButton btnDecrypt = new JButton("Decrypt");
JButton btnOpen = new JButton("Open");
protected JLabel lblEnterYourMessage;
protected JLabel lblEnterYourOffset;
protected JTextArea txtrMessage;
protected JTextArea txtrOffset;
private JFrame frame;
boolean test;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gui_Maker window = new Gui_Maker();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Gui_Maker() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
btnEncrypt.addActionListener(this);
btnDecrypt.addActionListener(this);
btnOpen.addActionListener(this);
frame = new JFrame();
frame.setBounds(100, 100, 475, 240);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[] { 0, 0, 0 };
gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0 };
gridBagLayout.columnWeights = new double[] { 1.0, 0.0, Double.MIN_VALUE };
gridBagLayout.rowWeights = new double[] { 1.0, 1.0, 1.0, 1.0 };
frame.getContentPane().setLayout(gridBagLayout);
JLabel lblEnterYourMessage = new JLabel("Enter your message here");
GridBagConstraints gbc_lblEnterYourMessage = new GridBagConstraints();
gbc_lblEnterYourMessage.anchor = GridBagConstraints.SOUTH;
gbc_lblEnterYourMessage.insets = new Insets(0, 0, 5, 5);
gbc_lblEnterYourMessage.gridx = 0;
gbc_lblEnterYourMessage.gridy = 0;
frame.getContentPane()
.add(lblEnterYourMessage, gbc_lblEnterYourMessage);
JTextArea txtrMessage = new JTextArea();
txtrMessage.setText("Message");
GridBagConstraints gbc_txtrMessage = new GridBagConstraints();
gbc_txtrMessage.insets = new Insets(0, 0, 5, 5);
gbc_txtrMessage.fill = GridBagConstraints.BOTH;
gbc_txtrMessage.gridx = 0;
gbc_txtrMessage.gridy = 1;
frame.getContentPane().add(txtrMessage, gbc_txtrMessage);
GridBagConstraints gbc_btnEncrypt = new GridBagConstraints();
gbc_btnEncrypt.fill = GridBagConstraints.VERTICAL;
gbc_btnEncrypt.insets = new Insets(0, 0, 5, 0);
gbc_btnEncrypt.gridx = 1;
gbc_btnEncrypt.gridy = 1;
frame.getContentPane().add(btnEncrypt, gbc_btnEncrypt);
JLabel lblEnterYourOffset = new JLabel("Enter your offset here");
GridBagConstraints gbc_lblEnterYourOffset = new GridBagConstraints();
gbc_lblEnterYourOffset.anchor = GridBagConstraints.SOUTH;
gbc_lblEnterYourOffset.insets = new Insets(0, 0, 5, 5);
gbc_lblEnterYourOffset.gridx = 0;
gbc_lblEnterYourOffset.gridy = 2;
frame.getContentPane().add(lblEnterYourOffset, gbc_lblEnterYourOffset);
GridBagConstraints gbc_btnDecrypt = new GridBagConstraints();
gbc_btnDecrypt.fill = GridBagConstraints.VERTICAL;
gbc_btnDecrypt.insets = new Insets(0, 0, 5, 0);
gbc_btnDecrypt.gridx = 1;
gbc_btnDecrypt.gridy = 2;
frame.getContentPane().add(btnDecrypt, gbc_btnDecrypt);
JTextArea txtrOffset = new JTextArea();
txtrOffset.setText("Offset");
GridBagConstraints gbc_txtrOffset = new GridBagConstraints();
gbc_txtrOffset.insets = new Insets(0, 0, 0, 5);
gbc_txtrOffset.fill = GridBagConstraints.BOTH;
gbc_txtrOffset.gridx = 0;
gbc_txtrOffset.gridy = 3;
frame.getContentPane().add(txtrOffset, gbc_txtrOffset);
GridBagConstraints gbc_btnOpen = new GridBagConstraints();
gbc_btnOpen.fill = GridBagConstraints.VERTICAL;
gbc_btnOpen.gridx = 1;
gbc_btnOpen.gridy = 3;
frame.getContentPane().add(btnOpen, gbc_btnOpen);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnEncrypt) {
String input_text;
int input_offset;
test = true;
input_text = txtrMessage.getText();
input_offset = Integer.parseInt(txtrOffset.getText());
computerscience.encrypt(input_text, input_offset, test);
}
if (e.getSource() == btnDecrypt) {
String input_text;
int input_offset;
test = false;
input_text = txtrMessage.getText();
input_offset = Integer.parseInt(txtrOffset.getText());
computerscience.decrypt(input_text, input_offset, test);
}
if (e.getSource() == btnOpen) {
}
}
}

These are fields in your class:
protected JTextArea txtrMessage;
protected JTextArea txtrOffset;
Here you recreate objects locally in a method
JTextArea txtrMessage = new JTextArea();
//...
JTextArea txtrOffset = new JTextArea();
And in another method you access the uninitialized fields:
input_text = txtrMessage.getText();
input_offset = Integer.parseInt(txtrOffset.getText());
Omit the types from the code in the init method.
txtrMessage = new JTextArea();
//...
txtrOffset = new JTextArea();
And so for some other JComponents, although it doesn't hurt with these:
lblEnterYourMessage = ...
lblEnterYourOffset = ...

Related

JButton can't be resolved inside actionListener

I'm trying to make a simple GUI calculator with Eclipse
The actionlistener is at the bottom, and eclipse says my ButtonAdd can't be resolved
the error is around lines 125-131, Any help is appreciated! :D
package main;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
public class GUIApp {
private JFrame frame;
public JTextField txtNumber_1;
public JTextField txtNumber;
public JTextField textField;
public JButton ButtonAdd;
public JButton ButtonSub;
public JButton ButtonMulti;
public JButton ButtonDiv;
public JButton btnRng;
String num1;
String num2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUIApp window = new GUIApp();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUIApp() {
initialize();
}
/**
* Initialize the contents of the frame.
* #return
*/
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
ButtonAdd = new JButton("Addition");
ButtonAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
num1 = txtNumber_1.getText();
num2 = txtNumber.getText();
if(ButtonAdd.getModel().isPressed())
textField.setText(num1 + num2);
}
});
GridBagConstraints gbc_ButtonAdd = new GridBagConstraints();
gbc_ButtonAdd.insets = new Insets(0, 0, 5, 5);
gbc_ButtonAdd.gridx = 0;
gbc_ButtonAdd.gridy = 0;
frame.getContentPane().add(ButtonAdd, gbc_ButtonAdd);
ButtonSub = new JButton("Subtraction");
GridBagConstraints gbc_ButtonSub = new GridBagConstraints();
gbc_ButtonSub.insets = new Insets(0, 0, 5, 5);
gbc_ButtonSub.gridx = 0;
gbc_ButtonSub.gridy = 2;
frame.getContentPane().add(ButtonSub, gbc_ButtonSub);
txtNumber_1 = new JTextField();
txtNumber_1.setText("Number 1");
txtNumber_1.setToolTipText("insert a number");
GridBagConstraints gbc_txtNumber_1 = new GridBagConstraints();
gbc_txtNumber_1.insets = new Insets(0, 0, 5, 0);
gbc_txtNumber_1.fill = GridBagConstraints.HORIZONTAL;
gbc_txtNumber_1.gridx = 3;
gbc_txtNumber_1.gridy = 2;
frame.getContentPane().add(txtNumber_1, gbc_txtNumber_1);
txtNumber_1.setColumns(10);
ButtonMulti = new JButton("Multiplication");
GridBagConstraints gbc_ButtonMulti = new GridBagConstraints();
gbc_ButtonMulti.insets = new Insets(0, 0, 5, 5);
gbc_ButtonMulti.gridx = 0;
gbc_ButtonMulti.gridy = 4;
frame.getContentPane().add(ButtonMulti, gbc_ButtonMulti);
txtNumber = new JTextField();
txtNumber.setText("Number 2");
txtNumber.setToolTipText("insert other number");
GridBagConstraints gbc_txtNumber = new GridBagConstraints();
gbc_txtNumber.insets = new Insets(0, 0, 5, 0);
gbc_txtNumber.fill = GridBagConstraints.HORIZONTAL;
gbc_txtNumber.gridx = 3;
gbc_txtNumber.gridy = 5;
frame.getContentPane().add(txtNumber, gbc_txtNumber);
txtNumber.setColumns(10);
ButtonDiv = new JButton("Division");
GridBagConstraints gbc_ButtonDiv = new GridBagConstraints();
gbc_ButtonDiv.insets = new Insets(0, 0, 5, 5);
gbc_ButtonDiv.gridx = 0;
gbc_ButtonDiv.gridy = 6;
frame.getContentPane().add(ButtonDiv, gbc_ButtonDiv);
btnRng = new JButton("RNG");
GridBagConstraints gbc_btnRng = new GridBagConstraints();
gbc_btnRng.insets = new Insets(0, 0, 0, 5);
gbc_btnRng.gridx = 0;
gbc_btnRng.gridy = 8;
frame.getContentPane().add(btnRng, gbc_btnRng);
textField = new JTextField();
textField.setToolTipText("output");
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.gridx = 3;
gbc_textField.gridy = 8;
frame.getContentPane().add(textField, gbc_textField);
textField.setColumns(10);
}
public void actionPerformed(ActionEvent arg0) {
String num1;
String num2;
num1 = txtNumber_1.getText();
num2 = txtNumber.getText();
if(ButtonAdd.getModel().isPressed())
textField.setText(num1 + num2);
}
}
The GUI was made with WindowBuilder by the way
ButtonAdd is a local reference, meaning it can only be accessed inside the initialize method. A solution to this is to declare the ButtonAdd outside the method.
JButton ButtonAdd;
public void initialize() {
ButtonAdd = new JButton("Addition");
}
public void actionPerformed(ActionEvent arg0) {
// here we can now access ButtonAdd
}
Also a tip, by java's standard naming conventions you usually start variables and references with a lower case letter, so ButtonAdd -> buttonAdd
because it is not a member variable. make it one and it works
JButton ButtonAdd = new JButton("Addition"); is inside another method therefore it is not visible to your action listener

NullPointerException Runtimer Error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm completely lost, being new to Java I can't seem to find what I need to do.
Please, do not refer me to another person's question, those don't help because I don't know how it will fix my problem.
Here is my code:
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();
}
}
}
}
Here is my error:
michaeladair#michaeladair:~/Desktop/dicebot/src$ java dicebotjava.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)
The problem is here:
contentPane.add(textPane, BorderLayout.CENTER);
At this point, you haven't set up textPane. You set it up 4 lines later:
textPane = new JTextPane();
textPane.setBackground(Color.DARK_GRAY);
textPane.setEditable(false);
textPane.setMargin(null);
textPane.setContentType("text/html");
You need to add it to the pane after initializing.
Simple debugging would have fixed this problem for you. SO is not an appropriate place for "fix my code" questions.
Here is what's causing the error. You are adding textPane, before you create it. That's why a null pointer exception is thrown:
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();
Create the textPane object first, then add it.

Multiple Text Colors in a scrollpane?

This is my gui that I have right now, I need the scroll pane to display green on a win and red on a loss. Is it possible? Because, I might be able to color it before it is sent to the scrollpane right?
Here is the code for the scroll pane part.
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();
}
}
}
}
Errors:
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)
The color of the text has nothing to do with the JScrollPane. Use a text component that support multiple colors, such as JTextPane or JEditorPane. Recommended reading: http://docs.oracle.com/javase/tutorial/uiswing/components/text.html
You have 3 variables called style in one method. You cannot do this. Also you are not passing the correct number of arguments to addStyle.
See http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneStylesExample6.htm for a complete example of using JTextPane Styles:
/*
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";
}

Using combo box values with a button

I have 10 combo boxes and one button. Is there an easy way to make it so you set all the values of each combo box and then press this button and it stores all the values of the combo boxes?
You first have to iterate through all your JComboBox elements and get their selected state (ie: getSelectedItem() or getSelectedIndex()). Once you have determined what selection has been made, you can save the selections in a number of places to be read later, dependent on your needs:
You can save the states into a file that can be read at a later date
You can save the information in the local registry via Java Preferences API
If it is a network application, you can save the information in an SQL database
Sure! I'd propose to write yourself a new class which has both things:
class comboTrack{
private JComboBox box;
private Object value;
public comboTrack(JComboBox box){
this.box = box;
this.value = box.getSelectedItem();
}
public void update(){
this.value = box.getSelectedItem();
}
public Object getValue(){
return value;
}
}
Then, use these instead of normal Boxes. Like this:
//List of boxes (class variable):
ArrayList<comboTrack> boxes;
//Inside the button click method:
for(comboTrack box : boxes){
box.update();
}
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class ComboBoxValues extends JFrame {
private JPanel contentPane;
JComboBox comboBox;
JComboBox comboBox_1;
JComboBox comboBox_2;
JComboBox comboBox_3;
JComboBox comboBox_4;
JComboBox comboBox_5;
JComboBox comboBox_6;
JComboBox comboBox_7;
JComboBox comboBox_8;
JComboBox comboBox_9;
private JTextArea textArea;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ComboBoxValues frame = new ComboBoxValues();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public ComboBoxValues() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
comboBox = new JComboBox();
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 5, 5);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 0;
gbc_comboBox.gridy = 0;
contentPane.add(comboBox, gbc_comboBox);
comboBox.addItem("comboBox_0 val 1");
comboBox.addItem("comboBox_0 val 2");
comboBox_1 = new JComboBox();
GridBagConstraints gbc_comboBox_1 = new GridBagConstraints();
gbc_comboBox_1.insets = new Insets(0, 0, 5, 0);
gbc_comboBox_1.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_1.gridx = 1;
gbc_comboBox_1.gridy = 0;
contentPane.add(comboBox_1, gbc_comboBox_1);
comboBox_1.addItem("comboBox_1 val 1");
comboBox_1.addItem("comboBox_1 val 2");
comboBox_2 = new JComboBox();
GridBagConstraints gbc_comboBox_2 = new GridBagConstraints();
gbc_comboBox_2.insets = new Insets(0, 0, 5, 5);
gbc_comboBox_2.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_2.gridx = 0;
gbc_comboBox_2.gridy = 1;
contentPane.add(comboBox_2, gbc_comboBox_2);
comboBox_2.addItem("comboBox_2 val 1");
comboBox_2.addItem("comboBox_2 val 2");
comboBox_3 = new JComboBox();
GridBagConstraints gbc_comboBox_3 = new GridBagConstraints();
gbc_comboBox_3.insets = new Insets(0, 0, 5, 0);
gbc_comboBox_3.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_3.gridx = 1;
gbc_comboBox_3.gridy = 1;
contentPane.add(comboBox_3, gbc_comboBox_3);
comboBox_3.addItem("comboBox_3 val 1");
comboBox_3.addItem("comboBox_3 val 2");
comboBox_4 = new JComboBox();
GridBagConstraints gbc_comboBox_4 = new GridBagConstraints();
gbc_comboBox_4.insets = new Insets(0, 0, 5, 5);
gbc_comboBox_4.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_4.gridx = 0;
gbc_comboBox_4.gridy = 2;
contentPane.add(comboBox_4, gbc_comboBox_4);
comboBox_4.addItem("comboBox_4 val 1");
comboBox_4.addItem("comboBox_4 val 2");
comboBox_5 = new JComboBox();
GridBagConstraints gbc_comboBox_5 = new GridBagConstraints();
gbc_comboBox_5.insets = new Insets(0, 0, 5, 0);
gbc_comboBox_5.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_5.gridx = 1;
gbc_comboBox_5.gridy = 2;
contentPane.add(comboBox_5, gbc_comboBox_5);
comboBox_5.addItem("comboBox_5 val 1");
comboBox_5.addItem("comboBox_5 val 2");
comboBox_6 = new JComboBox();
GridBagConstraints gbc_comboBox_6 = new GridBagConstraints();
gbc_comboBox_6.insets = new Insets(0, 0, 5, 5);
gbc_comboBox_6.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_6.gridx = 0;
gbc_comboBox_6.gridy = 3;
contentPane.add(comboBox_6, gbc_comboBox_6);
comboBox_6.addItem("comboBox_6 val 1");
comboBox_6.addItem("comboBox_6 val 2");
comboBox_7 = new JComboBox();
GridBagConstraints gbc_comboBox_7 = new GridBagConstraints();
gbc_comboBox_7.insets = new Insets(0, 0, 5, 0);
gbc_comboBox_7.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_7.gridx = 1;
gbc_comboBox_7.gridy = 3;
contentPane.add(comboBox_7, gbc_comboBox_7);
comboBox_7.addItem("comboBox_7 val 1");
comboBox_7.addItem("comboBox_7 val 2");
comboBox_8 = new JComboBox();
GridBagConstraints gbc_comboBox_8 = new GridBagConstraints();
gbc_comboBox_8.insets = new Insets(0, 0, 5, 5);
gbc_comboBox_8.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_8.gridx = 0;
gbc_comboBox_8.gridy = 4;
contentPane.add(comboBox_8, gbc_comboBox_8);
comboBox_8.addItem("comboBox_8 val 1");
comboBox_8.addItem("comboBox_8 val 2");
comboBox_9 = new JComboBox();
GridBagConstraints gbc_comboBox_9 = new GridBagConstraints();
gbc_comboBox_9.insets = new Insets(0, 0, 5, 0);
gbc_comboBox_9.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox_9.gridx = 1;
gbc_comboBox_9.gridy = 4;
contentPane.add(comboBox_9, gbc_comboBox_9);
comboBox_9.addItem("comboBox_9 val 1");
comboBox_9.addItem("comboBox_9 val 2");
JButton btnGetValues = new JButton("Get Values");
GridBagConstraints gbc_btnGetValues = new GridBagConstraints();
gbc_btnGetValues.insets = new Insets(0, 0, 5, 0);
gbc_btnGetValues.gridx = 1;
gbc_btnGetValues.gridy = 5;
contentPane.add(btnGetValues, gbc_btnGetValues);
textArea = new JTextArea();
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.gridheight = 2;
gbc_lblNewLabel.gridwidth = 2;
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 6;
contentPane.add(textArea, gbc_lblNewLabel);
textArea.setColumns(30);
textArea.setRows(5);
pack();
btnGetValues.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.setText(comboBox.getSelectedItem().toString()+","+
comboBox_1.getSelectedItem().toString()+","+
comboBox_2.getSelectedItem().toString()+"\n"+
comboBox_3.getSelectedItem().toString()+","+
comboBox_4.getSelectedItem().toString()+","+
comboBox_5.getSelectedItem().toString()+"\n"+
comboBox_6.getSelectedItem().toString()+","+
comboBox_7.getSelectedItem().toString()+","+
comboBox_8.getSelectedItem().toString()+"\n"+
comboBox_9.getSelectedItem().toString());
}
});
}
}

Java GUI - JTextArea expanding but not contracting

MAIN PROBLEM: In a JScrollPane with JPanel which contains a JTextArea, text wraps up if GUI is expanded but text does not wrap back when GUI is contracted. See example below
Okay I am building the GUI for an app I am currently working on and I am having a bit of a problem.
The explanation: My GUI is structured as illustrated below:
And this is what it looks like.
Upon expansion the the JTextArea inside the panelWithText expands and resizes the text as such:
But the problem is what happens when you make the GUI smaller. The "problem" is that I want the text to warp back as it was before. I did a little experimenting by implementing a ComponentListener to both the JScrollPane and the panelWithText and found out that componentResized is being called for panelWithText upon expansion but not for contraction. Is there any way to implement the behavior of the text warping back in the panelWithText Component?
PS: Apparently if I switch the JScrollPane with a regular JPanel it works. But I can't do that! I have a LOT of panelWithText to show to the user.
PS PS: Sorry here is the code I am using.
JFrameExt.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.FlowLayout;
import java.awt.Window.Type;
import javax.swing.ScrollPaneConstants;
import java.awt.CardLayout;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
public class JFrameExt extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameExt frame = new JFrameExt();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameExt() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 246, 164);
contentPane = new JPanel();
contentPane.setBorder(null);
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportBorder(null);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
panelWithText panelWithText_ = new panelWithText();
GridBagConstraints gbc_panelWithText_ = new GridBagConstraints();
gbc_panelWithText_.anchor = GridBagConstraints.NORTH;
gbc_panelWithText_.insets = new Insets(0, 0, 5, 0);
gbc_panelWithText_.fill = GridBagConstraints.HORIZONTAL;
gbc_panelWithText_.gridx = 0;
gbc_panelWithText_.gridy = 0;
panel.add(panelWithText_, gbc_panelWithText_);
panelWithText panelWithText__1 = new panelWithText();
GridBagConstraints gbc_panelWithText__1 = new GridBagConstraints();
gbc_panelWithText__1.insets = new Insets(0, 0, 5, 0);
gbc_panelWithText__1.anchor = GridBagConstraints.NORTH;
gbc_panelWithText__1.fill = GridBagConstraints.HORIZONTAL;
gbc_panelWithText__1.gridx = 0;
gbc_panelWithText__1.gridy = 1;
panel.add(panelWithText__1, gbc_panelWithText__1);
panelWithText panelWithText__2 = new panelWithText();
GridBagConstraints gbc_panelWithText__2 = new GridBagConstraints();
gbc_panelWithText__2.insets = new Insets(0, 0, 5, 0);
gbc_panelWithText__2.fill = GridBagConstraints.BOTH;
gbc_panelWithText__2.gridx = 0;
gbc_panelWithText__2.gridy = 2;
panel.add(panelWithText__2, gbc_panelWithText__2);
panelWithText panelWithText__3 = new panelWithText();
GridBagConstraints gbc_panelWithText__3 = new GridBagConstraints();
gbc_panelWithText__3.insets = new Insets(0, 0, 5, 0);
gbc_panelWithText__3.fill = GridBagConstraints.BOTH;
gbc_panelWithText__3.gridx = 0;
gbc_panelWithText__3.gridy = 3;
panel.add(panelWithText__3, gbc_panelWithText__3);
panelWithText panelWithText__4 = new panelWithText();
GridBagConstraints gbc_panelWithText__4 = new GridBagConstraints();
gbc_panelWithText__4.insets = new Insets(0, 0, 5, 0);
gbc_panelWithText__4.fill = GridBagConstraints.BOTH;
gbc_panelWithText__4.gridx = 0;
gbc_panelWithText__4.gridy = 4;
panel.add(panelWithText__4, gbc_panelWithText__4);
panelWithText panelWithText__5 = new panelWithText();
GridBagConstraints gbc_panelWithText__5 = new GridBagConstraints();
gbc_panelWithText__5.insets = new Insets(0, 0, 5, 0);
gbc_panelWithText__5.fill = GridBagConstraints.BOTH;
gbc_panelWithText__5.gridx = 0;
gbc_panelWithText__5.gridy = 5;
panel.add(panelWithText__5, gbc_panelWithText__5);
panelWithText panelWithText__6 = new panelWithText();
GridBagConstraints gbc_panelWithText__6 = new GridBagConstraints();
gbc_panelWithText__6.fill = GridBagConstraints.BOTH;
gbc_panelWithText__6.gridx = 0;
gbc_panelWithText__6.gridy = 6;
panel.add(panelWithText__6, gbc_panelWithText__6);
setSize(300,100);
}
}
panelWithText.java
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.ImageIcon;
import java.awt.BorderLayout;
public class panelWithText extends JPanel {
/**
* Create the panel.
*/
public void me_resized(Dimension d){
System.out.println("CALLED..");
super.setPreferredSize(d);
}
public panelWithText() {
setBackground(Color.DARK_GRAY);
setForeground(Color.WHITE);
setLayout(new BorderLayout(0, 0));
JTextArea txtrIveBeenReading = new JTextArea();
txtrIveBeenReading.setEditable(false);
txtrIveBeenReading.setColumns(28);
txtrIveBeenReading.setFont(new Font("Tahoma", Font.PLAIN, 10));
txtrIveBeenReading.setLineWrap(true);
txtrIveBeenReading.setWrapStyleWord(true);
txtrIveBeenReading.setText("\n A bunch of really important text here... A bunch of really important text here... A bunch of really important text here... A bunch of really important text here...\n");
txtrIveBeenReading.setForeground(Color.WHITE);
txtrIveBeenReading.setBackground(Color.DARK_GRAY);
add(txtrIveBeenReading, BorderLayout.CENTER);
}
}
After a little playing around, I came up with this...
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameExt frame = new JFrameExt();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static class ScrollablePane extends JPanel implements Scrollable {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(100, 100);
}
#Override
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 64;
}
#Override
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return 128;
}
#Override
public boolean getScrollableTracksViewportWidth() {
return true;
}
#Override
public boolean getScrollableTracksViewportHeight() {
return false;
}
}
public static class JFrameExt extends JFrame {
private JPanel contentPane;
/**
* Create the frame.
*/
public JFrameExt() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 246, 164);
contentPane = new JPanel();
contentPane.setBorder(null);
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportBorder(null);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new ScrollablePane();
scrollPane.setViewportView(panel);
GridBagLayout gbl_panel = new GridBagLayout();
// gbl_panel.columnWidths = new int[]{0, 0};
// gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0};
// gbl_panel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
// gbl_panel.rowWeights = new double[]{0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
panelWithText panelWithText_ = new panelWithText();
GridBagConstraints gbc_panelWithText_ = new GridBagConstraints();
gbc_panelWithText_.anchor = GridBagConstraints.NORTH;
gbc_panelWithText_.insets = new Insets(0, 0, 5, 0);
gbc_panelWithText_.fill = GridBagConstraints.HORIZONTAL;
gbc_panelWithText_.gridx = 0;
gbc_panelWithText_.gridy = 0;
gbc_panelWithText_.weightx = 1;
panel.add(panelWithText_, gbc_panelWithText_);
// panelWithText panelWithText__1 = new panelWithText();
// GridBagConstraints gbc_panelWithText__1 = new GridBagConstraints();
// gbc_panelWithText__1.insets = new Insets(0, 0, 5, 0);
// gbc_panelWithText__1.anchor = GridBagConstraints.NORTH;
//// gbc_panelWithText__1.fill = GridBagConstraints.HORIZONTAL;
// gbc_panelWithText__1.gridx = 0;
// gbc_panelWithText__1.gridy = 1;
// panel.add(panelWithText__1, gbc_panelWithText__1);
//
// panelWithText panelWithText__2 = new panelWithText();
// GridBagConstraints gbc_panelWithText__2 = new GridBagConstraints();
// gbc_panelWithText__2.insets = new Insets(0, 0, 5, 0);
//// gbc_panelWithText__2.fill = GridBagConstraints.BOTH;
// gbc_panelWithText__2.gridx = 0;
// gbc_panelWithText__2.gridy = 2;
// panel.add(panelWithText__2, gbc_panelWithText__2);
//
// panelWithText panelWithText__3 = new panelWithText();
// GridBagConstraints gbc_panelWithText__3 = new GridBagConstraints();
// gbc_panelWithText__3.insets = new Insets(0, 0, 5, 0);
//// gbc_panelWithText__3.fill = GridBagConstraints.BOTH;
// gbc_panelWithText__3.gridx = 0;
// gbc_panelWithText__3.gridy = 3;
// panel.add(panelWithText__3, gbc_panelWithText__3);
//
// panelWithText panelWithText__4 = new panelWithText();
// GridBagConstraints gbc_panelWithText__4 = new GridBagConstraints();
// gbc_panelWithText__4.insets = new Insets(0, 0, 5, 0);
//// gbc_panelWithText__4.fill = GridBagConstraints.BOTH;
// gbc_panelWithText__4.gridx = 0;
// gbc_panelWithText__4.gridy = 4;
// panel.add(panelWithText__4, gbc_panelWithText__4);
//
// panelWithText panelWithText__5 = new panelWithText();
// GridBagConstraints gbc_panelWithText__5 = new GridBagConstraints();
// gbc_panelWithText__5.insets = new Insets(0, 0, 5, 0);
//// gbc_panelWithText__5.fill = GridBagConstraints.BOTH;
// gbc_panelWithText__5.gridx = 0;
// gbc_panelWithText__5.gridy = 5;
// panel.add(panelWithText__5, gbc_panelWithText__5);
//
// panelWithText panelWithText__6 = new panelWithText();
// GridBagConstraints gbc_panelWithText__6 = new GridBagConstraints();
//// gbc_panelWithText__6.fill = GridBagConstraints.BOTH;
// gbc_panelWithText__6.gridx = 0;
// gbc_panelWithText__6.gridy = 6;
// panel.add(panelWithText__6, gbc_panelWithText__6);
setSize(300, 100);
}
}
public static class panelWithText extends JPanel {
/**
* Create the panel.
*/
public void me_resized(Dimension d) {
System.out.println("CALLED..");
super.setPreferredSize(d);
}
public panelWithText() {
setBackground(Color.DARK_GRAY);
setForeground(Color.WHITE);
setLayout(new BorderLayout(0, 0));
JTextArea txtrIveBeenReading = new JTextArea();
txtrIveBeenReading.setEditable(false);
txtrIveBeenReading.setColumns(28);
txtrIveBeenReading.setFont(new Font("Tahoma", Font.PLAIN, 10));
txtrIveBeenReading.setLineWrap(true);
txtrIveBeenReading.setWrapStyleWord(true);
txtrIveBeenReading.setText("\n A bunch of really important text here... A bunch of really important text here... A bunch of really important text here... A bunch of really important text here...\n");
txtrIveBeenReading.setForeground(Color.WHITE);
txtrIveBeenReading.setBackground(Color.DARK_GRAY);
add(txtrIveBeenReading, BorderLayout.CENTER);
}
}
}
Basically, you need a container that implements the Scrollable interface. This will allow you to specify that the container should track/match the view ports width. This will cause the container to be laid out when ever the view port changes size...
As a side note, you can use a single copy of the GridBagConstraints, when you add each new component to the container, the GridBagLayout will generate a copy of it's own. This is very powerful when you want to share properties of the GridBagConstraints between components ;)

Categories

Resources