I'm trying to make a simple GUI program that can be used to make multiple choices inside a game. I understand that I have to take all the questions, their choices, and the right answer as well. My problem is that when I try to collect the right answers in the hashmap, I get only the last true answer and its duplicated within the hashmap. In addition, I received a problem when collecting choices and solved the issue with an unusual for-loop, but unfortunately I couldn't do that with answers.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
public class ExamFrame extends JFrame {
private ExamPanel examPanel;
private static int count = 1;
static HashMap<Integer,ArrayList<String>> choicesMap = new HashMap<>();
static ArrayList<String> choicesList = new ArrayList<>();
static HashMap<Integer,ArrayList<String>> truesMap = new HashMap<>();
static ArrayList<String> truesList = new ArrayList<>();
static ArrayList<String> prompts = new ArrayList<>();
public ExamFrame() {
super("Making exam");
examPanel = new ExamPanel();
setContentPane(examPanel);
setSize(700,600);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
class ExamPanel extends JPanel implements ActionListener{
private JLabel quLabel;
private JTextField questionField;
private ArrayList<JCheckBox> jCheckBoxes;
private ArrayList<JTextField> respnsesFields;
private JButton suivant,terminer;
private JPanel centerPanel;
public ExamPanel() {
centerPanel = new JPanel(new BorderLayout());
suivant = new JButton("next");
suivant.addActionListener(this);
terminer = new JButton("Finish");
terminer.setEnabled(false);
terminer.addActionListener(this);
layoutComponents();
}
public void layoutComponents() {
setBackground(Color.green);
setLayout(new BorderLayout());
JPanel prince = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.NONE;
prince.setBackground(Color.CYAN);
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 0.1;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.LINE_END;
gc.gridx = 0;
quLabel = new JLabel("Question: ");
prince.add(quLabel,gc);
gc.gridx = 1;
gc.insets = new Insets(0, 0, 0, 0);
gc.anchor = GridBagConstraints.LINE_START;
questionField = new JTextField(45);
prince.add(questionField, gc);
jCheckBoxes = new ArrayList<>();
respnsesFields = new ArrayList<>();
for (int j = 0; j<2; j++) {
JCheckBox jCheckBox= new JCheckBox("Reponse "+(j+1));
jCheckBoxes.add(jCheckBox);
gc.gridy++;
gc.weightx = 1;
gc.weighty = 0.1;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.LINE_END;
gc.gridx=0;
prince.add(jCheckBox,gc);
JTextField jTextField = new JTextField(40);
respnsesFields.add(jTextField);
gc.gridx=1;
gc.insets = new Insets(0, 0, 0, 0);
gc.anchor = GridBagConstraints.LINE_START;
prince.add(jTextField,gc);
}
gc.gridy++;
gc.weightx = 1;
gc.weighty = 0.1;
gc.insets = new Insets(0, 0, 0, 5);
gc.anchor = GridBagConstraints.LINE_END;
gc.gridx=0;
prince.add(suivant,gc);
gc.gridx=1;
gc.insets = new Insets(0, 0, 0, 0);
gc.anchor = GridBagConstraints.LINE_START;
prince.add(terminer,gc);
centerPanel.add(prince,BorderLayout.CENTER);
add(centerPanel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
suivant.setEnabled(false);
if (count<=3) { //3 == Number of questions
suivant.setEnabled(true);
if (e.getSource() == suivant) {
String prompt = questionField.getText();
prompts.add(prompt);
ExamPanel.this.setVisible(false);
ExamFrame.this.setContentPane(new ExamPanel());
for (int i=0;i<2;i++) { //2 == Number of choices
choicesList.add(respnsesFields.get(i).getText());
}
for (int i=0;i<2;i++) {
if (jCheckBoxes.get(i).isSelected()) {
truesList.add(respnsesFields.get(i).getText());
}
}
truesMap.put(count,truesList);
truesList.clear();
count++;
}
}
else {
terminer.setEnabled(true);
questionField.setEnabled(false);
for (JTextField jTextField:respnsesFields) {
jTextField.setEnabled(false);
}
suivant.setEnabled(false);
if (e.getSource() == terminer) {
System.out.println(choicesList);
for (int i=0;i<3;i++) {
ArrayList<String> arrayList = new ArrayList<>();
for (int j=(i*2);j<(i+1)*2;j++) {
arrayList.add(choicesList.get(j));
}
choicesMap.put(i,arrayList);
}
System.out.println(choicesMap);
System.out.println(truesMap);
System.exit(0);
}
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ExamFrame();
}
});
}
}
You need to create a new ArrayList for each distinct item placed into the Map. Your program has only one truesList ArrayList instance that all Map items share. Inside of the ActionListener's actionPerformed method, create the new ArrayList (if one is needed -- if you're creating a new item to put into the Map), and place it into the Map along with the Integer key.
e.g.,
if (e.getSource() == suivant) {
truesList = new ArrayList<>(); // !! ADDED *****
String prompt = questionField.getText();
prompts.add(prompt);
ExamPanel.this.setVisible(false);
ExamFrame.this.setContentPane(new ExamPanel());
for (int i = 0; i < 2; i++) { // 2 == Number of choices
choicesList.add(respnsesFields.get(i).getText());
}
for (int i = 0; i < 2; i++) {
if (jCheckBoxes.get(i).isSelected()) {
truesList.add(respnsesFields.get(i).getText());
}
}
truesMap.put(count, truesList);
// !! truesList.clear(); // !! REMOVED ****
count++;
}
Side note: if you're using a Map<Integer, List<String>>, and the Integer key String is monotonically increasing as yours is, why use a Map at all? Why not simply use nested lists?
List<List<String>> truesList = new ArrayList<>();
The index of the outside list will be the same as the Integer key for the HashMap.
Related
I added some data to JTable (dataTable), using button click event need to get sum of last column specific values to another JTable (summeryTable). I need to keep dataTable data as it is and get sum to summeryTable .But original data changing during summing process. What is the best way to get sum by keeping original data as it is?
Class MyApplication
`public class MyApplication {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("My Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DataPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}`
Class DataPanel
public class DataPanel extends JPanel {
private JButton sumButton = new JButton();
private JTable dataTable = new JTable();
private JTable summeryTable = new JTable();
public DataPanel() {
GridBagConstraints gbc = new GridBagConstraints();
setLayout(new GridBagLayout());
sumButton.setText("Get Sum");
dataTable.setModel(new javax.swing.table.DefaultTableModel(
new Object[][]{
{"Column", null, null, null},
{null,"01","T20","500"},
{null, "01", "R6", "250"},
{null, "02", "R6", "50"},
{"Slab", null, null, null},
{null, "03", "T10", "300"},
{null, "04", "T10", "150"}
},
new String[]{
"Member", "Bar mark", "Type & Size", "Weight"
}
));
summeryTable.setModel(new javax.swing.table.DefaultTableModel(
new Object[][]{},
new String[]{
"Type & Size", " Total Weight"
}
));
JScrollPane dTableContainer = new JScrollPane(dataTable);
JScrollPane sTableContainer = new JScrollPane(summeryTable);
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0.1;
gbc.weighty = 0.1;
add(dTableContainer, gbc);
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 0.1;
gbc.weighty = 0.1;
add(sTableContainer, gbc);
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 0.1;
gbc.weighty = 0.1;
add(sumButton, gbc);
sumButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel dataModel = (DefaultTableModel) dataTable.getModel();
DefaultTableModel summeryModel = (DefaultTableModel) summeryTable.getModel();
BigDecimal tWeightRsix = BigDecimal.ZERO;
int rowCount = summeryModel.getRowCount();
for (int j = rowCount - 1; j >= 0; j--) {
summeryModel.removeRow(j);
}
for (int i = 0; i < dataModel.getRowCount(); i++) {
if (dataModel.getValueAt(i, 2) == null) {
dataModel.removeRow(i);
}
String mark = (String) dataModel.getValueAt(i, 2);
if (mark.equals("R6")) {
BigDecimal weights = new BigDecimal((String) dataModel.getValueAt(i, 3).toString());
tWeightRsix = tWeightRsix.add(weights).setScale(2, RoundingMode.HALF_UP);
}
}
Object data1 = "R6";
Object data2 = tWeightRsix;
summeryModel.addRow(new Object[]{data1, data2});
}
});
}
}
After doing few changes I got the expected result.
for (int i = 0; i < dataModel.getRowCount(); i++) {
if (dataModel.getValueAt(i, 2) != null) {
String mark = (String) dataModel.getValueAt(i, 2);
if (mark.equals("R6")) {
BigDecimal weights = new BigDecimal((String) dataModel.getValueAt(i, 3).toString());
tWeightRsix = tWeightRsix.add(weights).setScale(2, RoundingMode.HALF_UP);
}
}
}
I have ran into yet another issue. I am trying to set the text of a JTextField from another java class, and it does not seem to work.
I have tried the following:
calling the setter from inside the GUI class to .setText with a String. WORKS!
Setting the JTextField to some text so it isnt NULL -failed
Calling another method inside the GUI class, pass the string, then call the setter for the JTextField to set its text to the string. -failed (Just an idea i wanted to play with)
I did insure that the string is passed into the setter method by using a println. WORKED.
From googling around I believe that i have not set the reference to the main GUI?
Here is the GUI Class:
package book;
import book.BookIO;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
/**
*
*
*/
public class UserInterface implements ActionListener {
//Containers
JFrame frame = new JFrame("Ye old Book stoppe");
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
//Buttons
JButton processItem = new JButton("Process Item #1");
JButton confirmItem = new JButton("Confirm Item #1");
JButton viewOrder = new JButton("View Order");
JButton finishOrder = new JButton("Finish Order ");
JButton newOrder = new JButton("New Order");
JButton exit = new JButton("Exit");
//TextFields
JTextField amount = new JTextField();
JTextField id = new JTextField();
JTextField quantity = new JTextField();
JTextField info = new JTextField("");
JTextField total = new JTextField();
//Labels
JLabel num = new JLabel("Enter Number of Items in this Order:");
JLabel bookID = new JLabel("Enter Book ID for Item #1:");
JLabel quantityItem = new JLabel("Enter Quantity for Item #1:");
JLabel itemInfo = new JLabel("Item #1:");
JLabel subtotal = new JLabel("Order subtotal for 0 Items(s):");
public void startUI() {
UserInterface gui = new UserInterface();
gui.bookingUI();
}
public void bookingUI() {
//sets windows, and pane in the UI
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints c = new GridBagConstraints();
frame.setSize(800, 300);
//adding the labels to the panel
c.insets = new Insets(5, 0, 0, 0);
c.gridx = 2;
c.gridy = 1;
toppane.add(num, c);
c.gridx = 2;
c.gridy = 2;
toppane.add(bookID, c);
c.gridx = 2;
c.gridy = 3;
toppane.add(quantityItem, c);
c.gridx = 2;
c.gridy = 4;
toppane.add(itemInfo, c);
c.gridx = 2;
c.gridy = 5;
toppane.add(subtotal, c);
toppane.setBackground(Color.GREEN);
frame.add(toppane);
//add textfield to panel
c.ipadx = 400;
c.insets = new Insets(5, 10, 0, 0);
c.gridx = 3;
c.gridy = 1;
toppane.add(amount, c);
c.gridx = 3;
c.gridy = 2;
toppane.add(id, c);
c.gridx = 3;
c.gridy = 3;
toppane.add(quantity, c);
c.gridx = 3;
c.gridy = 4;
toppane.add(info, c);
c.gridx = 3;
c.gridy = 5;
toppane.add(total, c);
//----------------------------------------------------------BUTTOM PANE-------------------------
//adding the buttons to the pane.---------------------------------------------------------------
GridBagConstraints b = new GridBagConstraints();
b.insets = new Insets(5, 5, 5, 5);
b.ipadx = 10;
b.ipady = 10;
b.gridx = 1;
b.gridy = 0;
bottomPane.add(processItem, b);
processItem.addActionListener(this);
b.gridx = 2;
b.gridy = 0;
bottomPane.add(confirmItem, b);
confirmItem.setEnabled(false);
confirmItem.addActionListener(this);
b.gridx = 3;
b.gridy = 0;
bottomPane.add(viewOrder, b);
viewOrder.setEnabled(true);
viewOrder.addActionListener(this);
b.gridx = 4;
b.gridy = 0;
bottomPane.add(finishOrder, b);
finishOrder.setEnabled(true);
finishOrder.addActionListener(this);
b.gridx = 5;
b.gridy = 0;
bottomPane.add(newOrder, b);
newOrder.addActionListener(this);
b.gridx = 6;
b.gridy = 0;
bottomPane.add(exit, b);
exit.addActionListener(this);
bottomPane.setBackground(Color.BLUE);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.setSize(810, 310);
frame.setVisible(true);
}
//action listener for the buttons
public void actionPerformed(ActionEvent e) {
if (e.getSource() == processItem) {
confirmItem.setEnabled(true);
processItem.setEnabled(false);
BookIO findInfo = new BookIO();
findInfo.readFile(id.getText());
} else if (e.getSource() == confirmItem) {
processItem.setEnabled(true);
confirmItem.setEnabled(false);
} else if (e.getSource() == viewOrder) {
} else if (e.getSource() == finishOrder) {
} else if (e.getSource() == newOrder) {
} else if (e.getSource() == exit) {
System.exit(0);
}
}
//Creating getters and setters to change the text for the buttons and labels, as well as getting text from the textfields.
public void setProcessItemBtn(int num) {
processItem.setText("Process Item #" + num);
processItem.validate();
processItem.repaint();
}
public void setConfirmItemBtn(int num) {
confirmItem.setText("Confirm Item #" + num);
confirmItem.validate();
confirmItem.repaint();
}
public void setViewOrderBtn(String title) {
viewOrder.validate();
viewOrder.repaint();
}
public void setInfo(String title) {
System.out.println(title);
info.setText(title);
info.validate();
info.repaint();
}
public String getAmount() {
String str = amount.getText();
return str;
}
}
Here is the class with the method call to the setter:
package book;
import book.UserInterface;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.StringTokenizer;
/**
*
*
*/
public class BookIO {
public void readFile(String bookID) {
try {
FileReader read = new FileReader("inventory.txt");
BufferedReader buffer = new BufferedReader(read);
StringBuffer stringBuff = new StringBuffer();
String line, delim = "[,]";
for (int i = 0; i < 12; i++) {
line = buffer.readLine();
String[] tokens = line.split(delim);
if ((Objects.equals(tokens[0], bookID)) == true) {
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
}
}
} catch (IOException e) {
System.out.println("Error starting file!");
}
}
}
Your error is that you are instantiating a new UserInterface object which is wrong:
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
Your readFile() from BookIO should be like this:
public static void readFile(String bookID, UserInterface userInterface) {
try {
FileReader read = new FileReader("inventory.txt");
BufferedReader buffer = new BufferedReader(read);
StringBuffer stringBuff = new StringBuffer();
String line, delim = "[,]";
for (int i = 0; i < 12; i++) {
line = buffer.readLine();
String[] tokens = line.split(delim);
if ((Objects.equals(tokens[0], bookID)) == true) {
userInterface.setInfo(tokens[1]);
}
}
} catch (IOException e) {
System.out.println("Error starting file!");
}
}
In your UserInterface class, where you have this:
BookIO findInfo = new BookIO();
findInfo.readFile(id.getText());
Change the lines to this:
//pass the already created userInterface object.
BookIO.readFile(id.getText(), this);
Note: I have tested this and it worked. Tell me if it doesn't work for you.
You always make a new UserInterface instance
UserInterface setInfo = new UserInterface();
setInfo.setInfo(tokens[1]);
That sounds incorrect. Normally you would only have one such unstance (the visible one), and update that one.
Small side-note
if( Objects.equals(tokens[0], bookID)) == true )
can be simplified to
if( Objects.equals(tokens[0], bookID)) )
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.
Here is how I created the labels and JTextFields:
JPanel panel3 = new JPanel(new SpringLayout());
String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
"Right animation image name:","Bottom animation image name:"};
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
}
SpringUtilities.makeCompactGrid(panel3,
5, 2,
6, 6,
6, 6);
Say for example, how would I access/get the value of the text in the JTextField with the label, "Top animation image name:"?
I know that usually, one can perform JTextField.getText(), but to me it looks like that wouldn't work here.
Thanks in advance!
This is just a specific example of the question:
how can I access an object created in a loop.
The answer is the same: put them in a collection or array. Note that the collection option has greater flexibility. For instance if you create a bunch of JLabel/JTextField associations, you could use a HashMap<String, JTextField> to associate the JTextField with a String.
For example:
Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
String[] labels = {"Non-animated image name:","Left animation image name:","Top animation image name:",
"Right animation image name:","Bottom animation image name:"};
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
fieldMap.put(labels[i], n);
}
// and then later you can get the text field associated with the String:
String text = fieldMap.get(labels[2]).getText();
Or for a full example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private String[] labelTexts;
private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
public InputForm(String[] labelTexts) {
this.labelTexts = labelTexts;
setLayout(new GridBagLayout());
for (int i = 0; i < labelTexts.length; i++) {
String text = labelTexts[i];
JTextField field = new JTextField(COLUMNS);
fieldMap.put(text, field);
addLabel(text, i);
addTextField(field, i);
}
}
public String[] getLabelTexts() {
return labelTexts;
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
public String getFieldText(String key) {
String text = "";
JTextField field = fieldMap.get(key);
if (field != null) {
text = field.getText();
}
return text;
}
private static void createAndShowGui() {
String[] labelTexts = new String[] { "One", "Two",
"Three", "Four" };
InputForm inputForm = new InputForm(labelTexts);
int result = JOptionPane.showConfirmDialog(null, inputForm, "Enter Stuff Here",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
for (String text : labelTexts) {
System.out.printf("%20s %s%n", text, inputForm.getFieldText(text));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Each time you create a JLabel and a JTextField, store references to each of them inside a new instance of a container class.
For example:
private class LabelTextFieldContainer {
JLabel label;
JTextField textField;
//Constructor goes here...
}
for(int i=0; i<labels.length; i++){
JLabel l = new JLabel(labels[i],JLabel.TRAILING);
JTextField n = new JTextField(10);
panel3.add(l);
l.setLabelFor(n);
panel3.add(n);
containerList.add( new Container(l, n) ); //Instantiate List<LabelTextFieldContainer> containerList somewhere else
}
I have all of the labels working correctly but the userLabel[3] is not positioning properly
No matter what I do, the label "Color:" always shows up on the frame with a x-coordinate of 0 and a y-coordinate that is half way down the frame.
JLabel[] userLabel = new JLabel[4];
for(int p = 0; p < userLabel.length; p++){
userLabel[p] = new JLabel();
userLabel[p].setSize(100,50);
frameSetUp.add(userLabel[p]);
}
userLabel[0].setText("Width of Frame:");
userLabel[1].setText("Height of Frame:");
userLabel[2].setText("# OF Balls:");
userLabel[3].setText("Color:");
userLabel[0].setLocation(10,35);
userLabel[1].setLocation(10,85);
userLabel[2].setLocation(10,135);
userLabel[3].setLocation(0,0); //no matter what coordinates I change this too, it wont reposition
Image:
[IMG]http://i41.tinypic.com/23jfo9l.png[/IMG]
http://i41.tinypic.com/23jfo9l.png
Don't use setLocation, setBounds, null layouts or absolute positioning.
Instead use the layout managers including perhaps nested JPanels, each using its own layout manager to achieve pleasing easy to maintain GUI's.
For more help, show a picture of what you're trying to achieve, what you actually are achieving, and post a minimal working example, code that is small, that compiles and runs, and shows us your problem.
e.g.,
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputForm extends JPanel {
private static final int COLUMNS = 10;
private static final int GAP = 3;
private static final Insets LABEL_INSETS = new Insets(GAP, GAP, GAP, 15);
private static final Insets TEXTFIELD_INSETS = new Insets(GAP, GAP, GAP, GAP);
private String[] labelTexts;
private Map<String, JTextField> fieldMap = new HashMap<String, JTextField>();
public InputForm(String[] labelTexts) {
this.labelTexts = labelTexts;
setLayout(new GridBagLayout());
for (int i = 0; i < labelTexts.length; i++) {
String text = labelTexts[i];
JTextField field = new JTextField(COLUMNS);
fieldMap.put(text, field);
addLabel(text, i);
addTextField(field, i);
}
}
public String[] getLabelTexts() {
return labelTexts;
}
private void addTextField(JTextField field, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = TEXTFIELD_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(field, gbc);
}
private void addLabel(String text, int row) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = LABEL_INSETS;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(new JLabel(text), gbc);
}
public String getFieldText(String key) {
String text = "";
JTextField field = fieldMap.get(key);
if (field != null) {
text = field.getText();
}
return text;
}
private static void createAndShowGui() {
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Color:" };
InputForm inputForm = new InputForm(labelTexts);
int result = JOptionPane.showConfirmDialog(null, inputForm, "Input Form",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
for (String text : labelTexts) {
System.out.printf("%20s %s%n", text, inputForm.getFieldText(text));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which will display like so:
The beauty of this code, is if you wish to add another field, say a line thickness field, and want to add it so that it is second to last, then the only change needed to the code would be to change this:
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Color:" };
to this:
String[] labelTexts = new String[] { "Width of Frame:",
"Height of Frame:", "# OF Balls:", "Line Thickness:", "Color:" };
Which results in:
No need to have to calculate how to change the Color label or JTextField's locations as the layout manager does all the hard work for you.
Finally got the answer try increasing the size of the JLabel array by 1 and run it will work fine
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Labelss{
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(50, 50, 700, 550);
JLabel[] userLabel = new JLabel[6];
for(int p = 0; p < userLabel.length; p++){
userLabel[p] = new JLabel();
}
userLabel[0].setBounds(10,35,100,50);
userLabel[1].setBounds(10,85,100,50);
userLabel[2].setBounds(10,135,100,50);
userLabel[3].setBounds(10,185,100,50);
userLabel[4].setBounds(10,235,100,50);
userLabel[0].setText("Width of Frame:");
userLabel[1].setText("Height of Frame:");
userLabel[2].setText("# OF Balls:");
userLabel[3].setText("Color:");
userLabel[4].setText("Stack overflow:");
for(int p = 0; p < userLabel.length; p++){
frame.add(userLabel[p]);
}
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}