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.
Related
For Quick understanding , Pls refer to the given snapshot
I've a Jdialog SampleTestDialog that has some components defined on it
along with the focus traversal order defined in setTraversalOrder() Method. This Dialog also uses a Separate panel defined in SeparatePanel Class which contain some components on it and also defines the focus order for the component defined init in the method called method called setTraversalOrder() defined in the same class.
Problem:
On pressing TAB the focus traverse on all the components defined in SampleTestDialog but
it does not enters into the SeparatePanel components
I've set this.setFocusTraversalPolicy(focusPolicy);
this.setFocusTraversalPolicyProvider(true); for SeparatePanel.
Following are the SSCCE of Two Containers used.
SampleTestDialog.java
public class SampleTestDialog extends JDialog {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JLabel jLabel = null;
private JLabel jLabel1 = null;
private JTextField jTextField = null;
private JTextField jTextField1 = null;
private JPanel jPanel = null;
private JButton jButton = null;
private JButton jButton1 = null;
private SeparatePanel seperatePanel = null;
private CustomTraversalPolicyHandler focusPolicy = null;
public SampleTestDialog(Frame owner) {
super(owner);
initialize();
setFocusTraversalPolicy(focusPolicy);
}
private void initialize() {
this.setSize(392, 320);
this.setContentPane(getJContentPane());
setFocusTraversalOrder();
}
private void setFocusTraversalOrder() {
Vector<Component> order = new Vector<Component>();
order.add(getJButton1());
order.add(getJButton());
order.add(getJTextField1());
order.add(getJTextField());
focusPolicy = new CustomTraversalPolicyHandler(order);
}
private JPanel getJContentPane() {
if (jContentPane == null) {
GridBagConstraints gridBagConstraints31 = new GridBagConstraints();
gridBagConstraints31.gridx = 0;
gridBagConstraints31.gridwidth = 2;
gridBagConstraints31.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints31.anchor = GridBagConstraints.WEST;
gridBagConstraints31.insets = new Insets(10, 10, 5, 10);
gridBagConstraints31.gridy = 3;
GridBagConstraints gridBagConstraints21 = new GridBagConstraints();
gridBagConstraints21.gridx = 0;
gridBagConstraints21.anchor = GridBagConstraints.WEST;
gridBagConstraints21.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints21.gridwidth = 2;
gridBagConstraints21.gridy = 2;
GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
gridBagConstraints3.fill = GridBagConstraints.VERTICAL;
gridBagConstraints3.gridy = 1;
gridBagConstraints3.weightx = 1.0;
gridBagConstraints3.anchor = GridBagConstraints.WEST;
gridBagConstraints3.insets = new Insets(5, 10, 0, 0);
gridBagConstraints3.gridx = 1;
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
gridBagConstraints2.fill = GridBagConstraints.NONE;
gridBagConstraints2.gridy = 0;
gridBagConstraints2.weightx = 1.0;
gridBagConstraints2.anchor = GridBagConstraints.WEST;
gridBagConstraints2.insets = new Insets(5, 10, 0, 0);
gridBagConstraints2.gridx = 1;
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.gridx = 0;
gridBagConstraints1.gridy = 1;
jLabel1 = new JLabel();
jLabel1.setText("Text 2");
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
jLabel = new JLabel();
jLabel.setText("Text 1:");
jContentPane = new JPanel();
jContentPane.setLayout(new GridBagLayout());
jContentPane.add(jLabel, gridBagConstraints);
jContentPane.add(jLabel1, gridBagConstraints1);
jContentPane.add(getJTextField(), gridBagConstraints2);
jContentPane.add(getJTextField1(), gridBagConstraints3);
jContentPane.add(getJPanel(), gridBagConstraints21);
jContentPane.add(getSeperatePanel(), gridBagConstraints31);
}
return jContentPane;
}
private JTextField getJTextField() {
if (jTextField == null) {
jTextField = new JTextField();
jTextField.setColumns(10);
}
return jTextField;
}
private JTextField getJTextField1() {
if (jTextField1 == null) {
jTextField1 = new JTextField();
jTextField1.setColumns(10);
}
return jTextField1;
}
private JPanel getJPanel() {
if (jPanel == null) {
GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
gridBagConstraints5.insets = new Insets(10, 10, 10, 10);
GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
gridBagConstraints4.gridx = 1;
gridBagConstraints4.insets = new Insets(10, 10, 10, 10);
gridBagConstraints4.gridy = 0;
jPanel = new JPanel();
jPanel.setLayout(new GridBagLayout());
jPanel.add(getJButton(), gridBagConstraints5);
jPanel.add(getJButton1(), gridBagConstraints4);
}
return jPanel;
}
public SeparatePanel getSeperatePanel() {
if(seperatePanel == null)
{
seperatePanel = new SeparatePanel();
seperatePanel.setBorder(BorderFactory.createTitledBorder(null, "SeparatePanel", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51)));
seperatePanel.setFocusCycleRoot(true);
seperatePanel.setFocusTraversalPolicyProvider(true);
}
return seperatePanel;
}
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setText("Button 1");
}
return jButton;
}
private JButton getJButton1() {
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setText("Button 2");
}
return jButton1;
}
public static void main(String[] args) {
SampleTestDialog dialog = new SampleTestDialog(null);
dialog.setVisible(true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
}
SeparatePannel.java
public class SeparatePanel extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel jLabel = null;
private JTextField nameTextField = null;
private JLabel jLabel1 = null;
private JTextField addressTextField = null;
private JLabel jLabel2 = null;
private JTextField contactTextField2 = null;
private JPanel jPanel = null;
private JButton sendButton = null;
private JButton cancleButton = null;
private CustomTraversalPolicyHandler focusPolicy = null;
public SeparatePanel() {
super();
initialize();
this.setFocusTraversalPolicy(focusPolicy);
this.setFocusTraversalPolicyProvider(true);
}
private void initialize() {
GridBagConstraints gridBagConstraints11 = new GridBagConstraints();
gridBagConstraints11.gridx = 1;
gridBagConstraints11.fill = GridBagConstraints.BOTH;
gridBagConstraints11.gridy = 3;
GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
gridBagConstraints5.fill = GridBagConstraints.VERTICAL;
gridBagConstraints5.gridy = 2;
gridBagConstraints5.weightx = 1.0;
gridBagConstraints5.anchor = GridBagConstraints.WEST;
gridBagConstraints5.insets = new Insets(5, 10, 0, 0);
gridBagConstraints5.weighty = 0.0;
gridBagConstraints5.gridx = 1;
GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
gridBagConstraints4.gridx = 0;
gridBagConstraints4.insets = new Insets(0, 5, 0, 0);
gridBagConstraints4.gridy = 2;
jLabel2 = new JLabel();
jLabel2.setText("Contact #:");
GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
gridBagConstraints3.fill = GridBagConstraints.VERTICAL;
gridBagConstraints3.gridy = 1;
gridBagConstraints3.weightx = 1.0;
gridBagConstraints3.anchor = GridBagConstraints.WEST;
gridBagConstraints3.insets = new Insets(5, 10, 0, 0);
gridBagConstraints3.gridx = 1;
GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
gridBagConstraints2.gridx = 0;
gridBagConstraints2.anchor = GridBagConstraints.EAST;
gridBagConstraints2.gridy = 1;
jLabel1 = new JLabel();
jLabel1.setText("Address:");
GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
gridBagConstraints1.fill = GridBagConstraints.VERTICAL;
gridBagConstraints1.gridy = 0;
gridBagConstraints1.weightx = 1.0;
gridBagConstraints1.anchor = GridBagConstraints.WEST;
gridBagConstraints1.insets = new Insets(5, 10, 0, 0);
gridBagConstraints1.gridx = 1;
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = GridBagConstraints.EAST;
gridBagConstraints.gridy = 0;
jLabel = new JLabel();
jLabel.setText("Name:");
this.setSize(300, 200);
this.setLayout(new GridBagLayout());
this.add(jLabel, gridBagConstraints);
this.add(getNameTextField(), gridBagConstraints1);
this.add(jLabel1, gridBagConstraints2);
this.add(getAddressTextField(), gridBagConstraints3);
this.add(jLabel2, gridBagConstraints4);
this.add(getContactTextField(), gridBagConstraints5);
this.add(getJPanel(), gridBagConstraints11);
setFocusTraversalOrder();
}
private void setFocusTraversalOrder() {
Vector<Component> order = new Vector<Component>();
order.add(getCancleButton());
order.add(getSendButton());
order.add(getContactTextField());
order.add(getAddressTextField());
order.add(getNameTextField());
focusPolicy = new CustomTraversalPolicyHandler(order);
}
private JTextField getNameTextField() {
if (nameTextField == null) {
nameTextField = new JTextField();
nameTextField.setColumns(10);
}
return nameTextField;
}
private JTextField getAddressTextField() {
if (addressTextField == null) {
addressTextField = new JTextField();
addressTextField.setColumns(10);
}
return addressTextField;
}
private JTextField getContactTextField() {
if (contactTextField2 == null) {
contactTextField2 = new JTextField();
contactTextField2.setColumns(10);
}
return contactTextField2;
}
private JPanel getJPanel() {
if (jPanel == null) {
GridBagConstraints gridBagConstraints8 = new GridBagConstraints();
gridBagConstraints8.gridx = 0;
gridBagConstraints8.gridy = 0;
GridBagConstraints gridBagConstraints7 = new GridBagConstraints();
gridBagConstraints7.insets = new Insets(10, 10, 10, 10);
GridBagConstraints gridBagConstraints6 = new GridBagConstraints();
gridBagConstraints6.gridx = 1;
gridBagConstraints6.insets = new Insets(10, 10, 10, 10);
gridBagConstraints6.gridy = 0;
jPanel = new JPanel();
jPanel.setLayout(new GridBagLayout());
jPanel.add(getSendButton(), gridBagConstraints7);
jPanel.add(getCancleButton(), gridBagConstraints6);
jPanel.add(getSendButton(), gridBagConstraints8);
}
return jPanel;
}
private JButton getSendButton() {
if (sendButton == null) {
sendButton = new JButton();
sendButton.setText("Send");
}
return sendButton;
}
private JButton getCancleButton() {
if (cancleButton == null) {
cancleButton = new JButton();
cancleButton.setText("Cancel");
}
return cancleButton;
}
}
To accomplish Custom focus traversal, a class CustomTraversalPolicyHandler is used which extends FocusTraversalPolicy
public class CustomTraversalPolicyHandler extends FocusTraversalPolicy {
Vector<Component> order;
public CustomTraversalPolicyHandler(Vector<Component> order) {
this.order = order;
}
#Override
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
Component nextComponent;
int idx = (order.indexOf(aComponent) + 1) % order.size();
nextComponent = order.get(idx);
if (!nextComponent.isEnabled()
|| !nextComponent.isVisible()
|| !nextComponent.getParent().isVisible()
|| !nextComponent.getParent().isEnabled()){
nextComponent = getComponentAfter(focusCycleRoot, nextComponent);
}
return nextComponent;
}
#Override
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
Component previousComponent;
int idx = order.indexOf(aComponent) - 1;
if (idx < 0) {
idx = order.size() - 1;
}
previousComponent = order.get(idx);
if (!previousComponent.isEnabled()
|| !previousComponent.isVisible()
|| !previousComponent.getParent().isVisible()
|| !previousComponent.getParent().isEnabled()){
previousComponent = getComponentBefore(focusCycleRoot,
previousComponent);
}
return previousComponent;
}
#Override
public Component getFirstComponent(Container focusCycleRoot) {
return order.firstElement();
}
#Override
public Component getLastComponent(Container aContainer) {
return order.lastElement();
}
#Override
public Component getDefaultComponent(Container aContainer) {
return order.firstElement();
}
}
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 = ...
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";
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.*;
public class NewAccountApplet extends JApplet implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
JLabel titlePage;
JLabel[] txt;
JTextField[] jtf;
JButton accept, decline;
JPanel jp1, jp2, jp3, jp4, jp5, jp6;
String[] accountlist = {"Select Account Type.", "Customer", "Admin"};
JComboBox<Object> textAlignment = new JComboBox<Object>(accountlist);
GridLayout productLO = new GridLayout(10,4,10,10);
int qty = 5;
JComboBox<Object>[] selectQty;
public void init(){
setSize(400,400);
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
String[] labeltxt = {"Name","Account ID","Password","E-Mail","Phone","Address","","","Account Type"};
titlePage = new JLabel("Create New Account");
txt = new JLabel[9];
jtf = new JTextField[9];
accept = new JButton("Create");
decline = new JButton("Decline");
jp1 = new JPanel();
jp2 = new JPanel(new GridBagLayout());
jp3 = new JPanel();
jp4 = new JPanel();
jp5 = new JPanel();
jp6 = new JPanel();
for(int i=0; (i<9); i++) {
txt[i] = new JLabel();
txt[i].setText(labeltxt[i]);
jp2.add(txt[i], firstCol);
jtf[i] = new JTextField();
jtf[i].setPreferredSize(new Dimension(300, 20));
jp2.add(jtf[i], lastCol);
}
jp1.add(titlePage);
jp3.add(accept);
jp3.add(decline);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp1);
content.add(jp2);
content.add(jp3);
String id = this.jtf[1].getText();
String pw = this.jtf[2].getText();
jtf[6].setText(id);
jtf[7].setText(pw);
jtf[6].setVisible(false);
jtf[7].setVisible(false);
jtf[8].setVisible(false);
jp2.add(textAlignment, lastCol);
decline.addActionListener(this);
accept.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String id = jtf[1].getText();
String pw = jtf[2].getText();
String checkID = jtf[6].getText();
String checkPW = jtf[7].getText();
String accountType = "";
String correctType = "Customer";
String chosenType = (String) textAlignment.getSelectedItem();
JPasswordField pField = new JPasswordField(10);
JPanel pPanel = new JPanel();
pPanel.add(new JLabel("Please Enter Password: "));
pPanel.add(pField);
if (e.getActionCommand().equals("Create") && (chosenType.equals("Customer"))){
JOptionPane.showMessageDialog(null, "Thank you for Joining!");
id = jtf[1].getText();
pw = jtf[2].getText();
titlePage.setText("Welcome to Final Sales!");
accept.setText("Login");
decline.setText("Cancel");
txt[6].setText("UserName");
txt[7].setText("Password");
jtf[0].setText("");
jtf[3].setText("");
jtf[4].setText("");
jtf[5].setText("");
txt[0].setVisible(false);
txt[1].setVisible(false);
txt[2].setVisible(false);
txt[3].setVisible(false);
txt[4].setVisible(false);
txt[5].setVisible(false);
textAlignment.setVisible(false);
txt[8].setVisible(false);
jtf[0].setVisible(false);
jtf[1].setVisible(false);
jtf[2].setVisible(false);
jtf[3].setVisible(false);
jtf[4].setVisible(false);
jtf[5].setVisible(false);
jtf[6].setVisible(true);
jtf[7].setVisible(true);
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Admin"))) {
JOptionPane.showMessageDialog(null, pPanel);
JOptionPane.showMessageDialog(null, "Wrong Admin Password");
}
if (e.getActionCommand().equals("Create") && (chosenType.equals("Select Account Type."))) {
JOptionPane.showMessageDialog(null, "You have selected wrong account type.");
}
if (e.getActionCommand().equals("Decline"))
System.exit(0);
if (e.getActionCommand().equals("Login")) {
if (id.equals(checkID) && pw.equals(checkPW)) {
JOptionPane.showMessageDialog(null, "Authenticated");
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
selectQty = new JComboBox[qty];
jp1.setVisible(false);
jp2.setVisible(false);
jp3.setVisible(false);
jp4.setVisible(true);
jp5.setVisible(true);
jp6.setVisible(true);
String[] itemText = {"White Snapback", "Silver Necklace", "Black T Shirt", "", "5"};
JLabel[] items = new JLabel[5];
JLabel purchasePage = new JLabel("Items for Purchase");
jp4.add(purchasePage);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp4);
jp4 = new JPanel();
jp5.setLayout(new GridBagLayout());
jp6 = new JPanel();
for(int i=0; (i<items.length); i++) {
items[i] = new JLabel();
items[i].setText(itemText[i]);
jp5.add(items[i], firstCol);
selectQty[i] = new JComboBox<Object>();
selectQty[i].setPreferredSize(new Dimension(300, 20));
jp5.add(selectQty[i], lastCol);
}
}
else JOptionPane.showMessageDialog(null, "Wrong account information");}
if (e.getActionCommand().equals("Cancel")) {
System.exit(0);}
}
}
I need to know why my jp5 is not showing up.
Is it because the gridbaglayout is not declared correct?
I did setVisible(true) and setLayout for jp5, and it is still not showing up.
Any help would be great!
THank you.
You've not added jp5 to anything...
You can test this by adding System.out.println("parent = " + jp5.getParent()); anywhere within your actionPerformed method
Applets can't be "exited", using System.exit(0); in an applet makes no sense
This would be an excellent use case for CardLayout
You should consider separating each "screen" into it's own class/JPanel rather then stuffing everything into a single class
Hi
I'm working on a JavaSwing application but there's a problem with... I don't know exactly but I think it's maybe a (re)paint-problem :S - anyway here's my code:
MAIN:
public class QickSort {
protected static ArrayList<String> input;
private static File file = new File("C:/Users/save.txt");
public static void main(String[] args) throws Exception {
BufferedReader reader;
String line = null;
try {
input = new ArrayList<String>();
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
input.add(line);
}
reader.close();
} catch (Exception ex) {
System.out.println("Can't load file on path.. - " + ex);
ex.printStackTrace();
}
System.out.println(input.size());
JFrame.setDefaultLookAndFeelDecorated(false);
MasterWin win = new MasterWin(input);
}
}
UI:
public class MasterWin {
private JFrame frame;
private JTextField txtFieldPath;
private JButton btnBrowse;
private JButton btnAddPathTo;
private JLabel lblChosenFolderpaths;
private JButton btnRemove;
private JButton btnNext;
protected static ImageIcon icon = new ImageIcon(MasterWin.class.getResource("/View/logo_sml.gif"));
private JScrollPane scrollPane;
private JList linkList;
private List<String> test;
/**
* Create the application.
*/
public MasterWin(ArrayList<String> fileInput) {
test = fileInput;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setIconImage(icon.getImage());
frame.setTitle("QickSort - Start");
frame.setResizable(false);
frame.setBounds(100, 100, 645, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{480, 127, 0};
gridBagLayout.rowHeights = new int[]{135, 60, 0, 0, 0, 115, 0};
gridBagLayout.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
frame.setVisible(true);
JLabel logo = new JLabel("");
logo.setIcon(new ImageIcon(MasterWin.class.getResource("/View/Logo.gif")));
GridBagConstraints gbc_logo = new GridBagConstraints();
gbc_logo.fill = GridBagConstraints.HORIZONTAL;
gbc_logo.gridwidth = 2;
gbc_logo.insets = new Insets(0, 0, 5, 0);
gbc_logo.anchor = GridBagConstraints.SOUTH;
gbc_logo.gridx = 0;
gbc_logo.gridy = 0;
frame.getContentPane().add(logo, gbc_logo);
JLabel lblChosePathYou = new JLabel("Choose paths you want to use:");
GridBagConstraints gbc_lblChosePathYou = new GridBagConstraints();
gbc_lblChosePathYou.anchor = GridBagConstraints.SOUTHWEST;
gbc_lblChosePathYou.insets = new Insets(0, 60, 5, 5);
gbc_lblChosePathYou.gridx = 0;
gbc_lblChosePathYou.gridy = 1;
frame.getContentPane().add(lblChosePathYou, gbc_lblChosePathYou);
txtFieldPath = new JTextField();
txtFieldPath.setEditable(false);
GridBagConstraints gbc_txtFieldPath = new GridBagConstraints();
gbc_txtFieldPath.fill = GridBagConstraints.HORIZONTAL;
gbc_txtFieldPath.insets = new Insets(0, 60, 5, 5);
gbc_txtFieldPath.gridx = 0;
gbc_txtFieldPath.gridy = 2;
frame.getContentPane().add(txtFieldPath, gbc_txtFieldPath);
txtFieldPath.setColumns(10);
btnBrowse = new JButton("Browse...");
btnBrowse.setMinimumSize(new Dimension(89, 25));
btnBrowse.setMaximumSize(new Dimension(89, 25));
GridBagConstraints gbc_btnBrowse = new GridBagConstraints();
gbc_btnBrowse.anchor = GridBagConstraints.WEST;
gbc_btnBrowse.insets = new Insets(0, 10, 5, 0);
gbc_btnBrowse.gridx = 1;
gbc_btnBrowse.gridy = 2;
frame.getContentPane().add(btnBrowse, gbc_btnBrowse);
lblChosenFolderpaths = new JLabel("Chosen folderpaths:");
GridBagConstraints gbc_lblChosenFolderpaths = new GridBagConstraints();
gbc_lblChosenFolderpaths.anchor = GridBagConstraints.SOUTHWEST;
gbc_lblChosenFolderpaths.insets = new Insets(0, 60, 5, 5);
gbc_lblChosenFolderpaths.gridx = 0;
gbc_lblChosenFolderpaths.gridy = 3;
frame.getContentPane().add(lblChosenFolderpaths, gbc_lblChosenFolderpaths);
btnAddPathTo = new JButton("Add to list");
GridBagConstraints gbc_btnAddPathTo = new GridBagConstraints();
gbc_btnAddPathTo.anchor = GridBagConstraints.WEST;
gbc_btnAddPathTo.insets = new Insets(5, 10, 5, 0);
gbc_btnAddPathTo.gridx = 1;
gbc_btnAddPathTo.gridy = 3;
frame.getContentPane().add(btnAddPathTo, gbc_btnAddPathTo);
btnRemove = new JButton("Remove");
btnRemove.setToolTipText("Delete selected path");
btnRemove.setPreferredSize(new Dimension(89, 25));
btnRemove.setMinimumSize(new Dimension(89, 25));
btnRemove.setMaximumSize(new Dimension(89, 25));
GridBagConstraints gbc_btnRemove = new GridBagConstraints();
gbc_btnRemove.anchor = GridBagConstraints.NORTHWEST;
gbc_btnRemove.insets = new Insets(5, 10, 5, 0);
gbc_btnRemove.gridx = 1;
gbc_btnRemove.gridy = 4;
frame.getContentPane().add(btnRemove, gbc_btnRemove);
btnNext = new JButton("Accept");
btnNext.setPreferredSize(new Dimension(89, 25));
btnNext.setMinimumSize(new Dimension(89, 25));
btnNext.setMaximumSize(new Dimension(89, 25));
GridBagConstraints gbc_btnNext = new GridBagConstraints();
gbc_btnNext.anchor = GridBagConstraints.SOUTHWEST;
gbc_btnNext.insets = new Insets(0, 10, 25, 0);
gbc_btnNext.gridx = 1;
gbc_btnNext.gridy = 5;
frame.getContentPane().add(btnNext, gbc_btnNext);
scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.gridheight = 2;
gbc_scrollPane.insets = new Insets(0, 60, 25, 5);
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 4;
frame.getContentPane().add(scrollPane, gbc_scrollPane);
//JList I copy the array
linkList = new JList(test.toArray());
scrollPane.setViewportView(linkList);
}
}
The Problem:
It's really strange! Sometimes the text is shown on my JList - but if I start the program once again there's just a empty ScrollPane without the JList or the inputs.
Its more or less random that the text appears.
I tried a various kinds of Array(List)s, to impl. - with AbstractModel() oder just toArray(). Always same result..
Does someone know this problem?
Change:
protected static ArrayList<String> input;
To:
protected static final ArrayList<String> input = new ArrayList<String>();
Remove the assignment to input in main.
Wrap the calls to swing code in an invokeLater:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame.setDefaultLookAndFeelDecorated(false);
MasterWin win = new MasterWin(input);
};
});
After setting your list as the viewport view you should call invalidate() on the JList which will tell the underlying Swing graphics system that it needs to check the component as well as any possibly affected components whether or not these require updating.
Do not call repaint() because that will trigger a repaint of the component as it is, it will not ensure that other affected components are properly updated as well -- and because this JList is wrapped in a JScrollPane it will not behave as expected.
user268396's answer about layout validation is correct, but you should never need to be in this situation in the first place. Your layout is invalidated because you're adding components after you've made your JFrame visible. Simply by moving the call to frame.setVisible(true) to the end of the initialize() method, you should see the problem goes away, because the layout is now finalized and it will validate and render correctly first time.
I solved this issue:
I kicked out my Scrollpane and used only a JList. But that didn't work either.
I call now updateUI() after I create the JList - now it works.