My first question here. Already got a lot of help but now I don't know how to do.
My code:
package view;
import javax.swing.*;
public class OptionPlayerNames {
JPanel playerPanel = new JPanel();
JTextField playerNames = new JTextField();
public OptionPlayerNames() {
for (int i = 0; i < 8; i++) {
// JTextField playerNames = new JTextField();
playerPanel.add(new JLabel("Player " + (i + 1)));
playerPanel.add(playerNames);
}
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
playerPanel.add(Box.createHorizontalStrut(5));
}
public JPanel getPanel(){
return playerPanel;
}
public String getPlayerNames() {
return playerNames.getText();
}
I want to have 8 Jlabels with just under it 8 JTextFields for user input.
Then get the text of the textfields.
Now I get only 1 text from 1 textField. Off course I only add 1 field.
When I put the JTextField under the for loop I get what I want but how to I get the text from all the JTextFields then? playerNames is then not known in the getter.
Thank you for your help.
You can do as follows, creating a Listof JTextField:
JPanel playerPanel = new JPanel();
List<JTextField> playerNames = new ArrayList<JTextField>();
public OptionPlayerNames() {
for (int i = 0; i < 8; i++) {
JTextField playerName = new JTextField();
playerPanel.add(new JLabel("Player " + (i + 1)));
playerPanel.add(playerName);
playerNames.add(playerName);
}
playerPanel.setLayout(new BoxLayout(playerPanel, BoxLayout.Y_AXIS));
playerPanel.add(Box.createHorizontalStrut(5));
}
public JPanel getPanel() {
return playerPanel;
}
public String getPlayerNames() {
String output = "";
// Compound you exit from the playerNames List
// Or better, return a List of String
return output;
}
You need to declare a Vector or array of JTextField as an instance variable (not just one, as you've commented out) and fill it in as you loop. Then you have random (arbitrary) access to any text value. Conveniently, the index i is already there for you to index into the array.
There should be a tip-off that the type: JTextField is singular, but your variable name: playerNames is plural. :-)
Note that getPlayerNames() also needs to be re-done to handle an array not a single field.
While this will work, ultimately, the whole code block isn't good separation of Model & View, so as you advance in programming, be sure to pay attention to that concept.
Related
Hey guys I'm very new to Java and started in July with an intro to Java class.
I am currently working on a project which is a translator with arrays. The main applet shows 10 words in english that when typed into a JTextField outputs the spanish translation of that work. And vice versa. The program also shows a picture associated with that word.
The program is all done in that case, the only portion I am missing currently is that if a user inputs ANY other word than the 20 given words (10 spanish and 10 english) the JTextArea where translations are displayed is supposed to show "That word is not in the dictionary".
I'm having issues creating an ELSE statement that shows this error message. Here is the complete code. I'm not sure what to do to make it so eg
if (textFieldWord.!equals(englishWords[english])){
translate.setText("That word is not in the Dictionary");}
Here is the complete code - - - -
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DictionaryArrays extends JApplet implements ActionListener{
String[] spanishWords = {"biblioteca","reloj",
"alarma", "volcan", "ventana",
"autobus", "raton", "lago", "vaca", "encendedor"};
String[] englishWords = {"library", "clock", "alarm",
"volcano", "window", "bus", "rat",
"lake","cow","lighter"};
String textFieldWord;
Image[] photos;
ImageIcon icon;
ImageIcon icontwo;
JButton getTranslation;
JTextField entry;
JLabel imageviewer;
TextArea translate;
static int defaultX = 10;
static int defaultY = 10;
static int defaultW = 780;
static int defaultH = 50;
public void init() {
photos = new Image[10];
photos[0] = getImage(getCodeBase(), "library.jpg");
photos[1] = getImage(getCodeBase(), "clock.jpg");
photos[2] = getImage(getCodeBase(), "alarm.jpg");
photos[3] = getImage(getCodeBase(), "volcano.jpg");
photos[4] = getImage(getCodeBase(), "window.jpg");
photos[5] = getImage(getCodeBase(), "bus.jpg");
photos[6] = getImage(getCodeBase(), "rat.jpg");
photos[7] = getImage(getCodeBase(), "lake.jpg");
photos[8] = getImage(getCodeBase(), "cow.jpg");
photos[9] = getImage(getCodeBase(), "lighter.jpg");
final JPanel outer = new JPanel(new BorderLayout());
JPanel inner = new JPanel(new BorderLayout());
JPanel viewer = new JPanel(new BorderLayout());
JPanel visualviewer = new JPanel(new BorderLayout());
// here is the main component we want to see
// when the outer panel is added to the null layout
//JButton toSpanish = new JButton("English to Spanish");
//JButton toEnglish = new JButton("Spanish to English");
final JLabel list = new JLabel("<HTML><FONT COLOR=RED>English</FONT> - library, clock, alarm, volcano, window, bus, rat, lake, cow, lighter"
+"<BR><FONT COLOR=RED>Spanish</FONT> - biblioteca, reloj, alarma, volcan, ventana, autobus, raton, lago, vaca, encendedor<BR>");
translate = new TextArea("Your translation will show here");
imageviewer = new JLabel(icon);
viewer.add("West",translate);
visualviewer.add("East",imageviewer);
inner.add("Center",list);
//inner.add("West",toSpanish);
//inner.add("East", toEnglish);
outer.add("Center", inner);
JPanel c = (JPanel)getContentPane();
final JPanel nullLayoutPanel = new JPanel();
nullLayoutPanel.setLayout(null);
c.add("Center", nullLayoutPanel);
// set the bounds of the panels manually
nullLayoutPanel.add(outer);
nullLayoutPanel.add(viewer);
nullLayoutPanel.add(visualviewer);
outer.setBounds(defaultX, defaultY, defaultW, defaultH);
viewer.setBounds(20, 75, 300, 300);
visualviewer.setBounds(485, 75, 300, 300);
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
entry = new JTextField("Enter English or Spanish word to translate here");
entry.addActionListener(this);
entry.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
entry.setText("");
}});
getTranslation = new JButton("Translate");
getTranslation.addActionListener(this);
controlPanel.add(entry);
controlPanel.add(getTranslation);
c.add("South", controlPanel);
viewer.setBackground(Color.blue);
controlPanel.setBackground(Color.red);
inner.setBackground(Color.yellow);
visualviewer.setBackground(Color.black);
outer.setBackground(Color.black);
}
public void paint(Graphics g) {
super.paint(g);
}
public void actionPerformed (ActionEvent ae){
if(ae.getSource()==getTranslation){
textFieldWord=(entry.getText().toLowerCase());
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translate.setText(spanishWords[english]);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translate.setText(englishWords[spanish]);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
}
}
Any help would be appreciated guys. If the top paragraph was TLDR. Im trying to make it so typing in ANY other word in the JTextField (entry) other than the 10 english and 10 spanish words will output an error msg of "That word is not in the Dictionary" in the TextArea (translate)
This is (obviously) wrong...
if (textFieldWord.!equals(englishWords[english])){
and should be...
if (!textFieldWord.equals(englishWords[english])){
Try and think of it this way, String#equals returns a boolean, you want to invert the result of this method call, it would be the same as using something like...
boolean doesEqual = textFieldWord.equals(englishWords[english]);
if (!doesEqual) {...
You need to evaluate the result of the method call, but in oder to make that call, the syntax must be [object].[method], therefore, in order to invert the value, you must complete the method call first, then apply the modifier to it ... ! ([object].[method])
Updated...
Now having said all that, let's look at the problem from a different perspective...
You need to find a matching word, in order to do that, you must, at worse case, search the entire array. Until you've search the entire array, you don't know if a match exists.
This means we could use a separate if-else statement to manage the updating of the output, for example...
String translatedWord = null;
int foundIndex = -1;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = englishWords[english];
foundIndex = english;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icon= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icon);
} else {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[english];
foundIndex = spanish;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icontwo);
} else {
translate.setText("That word is not in the Dictionary");
}
Basically, all this does is sets the translatedWord to a non null value when it finds a match in either of the arrays. In this, you want to display the results, else you want to display the error message...
Equally, you could merge your current approach with the above, so when you find a work, you update the output, but also check the state of the translatedWord variable, displaying the error message if it is null...
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = spanishWords[english];
translate.setText(translatedWord);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[spanish];
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
Updated
Okay, you have a logic problem. You're never quite sure which direction you are translating to.
The following basically changes the follow by not translating the work from Spanish IF it was translated to English
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == getTranslation) {
textFieldWord = (entry.getText().toLowerCase());
translate.setText(null);
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++) {
if (textFieldWord.equals(englishWords[english])) {
translatedWord = spanishWords[english];
translate.append(translatedWord + "\n");
icon = new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
for (int spanish = 0; spanish < englishWords.length; spanish++) {
if (textFieldWord.equals(spanishWords[spanish])) {
translatedWord = englishWords[spanish];
translate.append(translatedWord + "\n");
icontwo = new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
if (translatedWord == null) {
translate.append("A Spanish-English match is not in the Dictionary\n");
}
}
}
Now, I would suggest that you replace TextArea with a JTextArea, but you will need to wrap it in a JScrollPane
translate = new JTextArea("Your translation will show here");
viewer.add("West", new JScrollPane(translate));
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Basically, this was really painful to try and use for this very reason...
I am designing a GUI for my research project. I want to create a dialog box that gets information from the user. Here is the screenshot:
Here is the code for the screenshot above:
JTextField projnameField = new JTextField(10);
JTextField nField = new JTextField(5);
JTextField mField = new JTextField(5);
JTextField alphaField = new JTextField(5);
JTextField kField = new JTextField(5);
JFileChooser inputfile = new JFileChooser();
inputfile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
File file = inputfile.getSelectedFile();
String fullpath = file.getAbsolutePath();
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Project Name:"));
myPanel.add(projnameField);
myPanel.add(new JLabel("Number of instances:"));
myPanel.add(nField);
myPanel.add(new JLabel("Number of attributes:"));
myPanel.add(mField);
myPanel.add(new JLabel("Alpha:"));
myPanel.add(alphaField);
myPanel.add(new JLabel("Number of patterns:"));
myPanel.add(kField);
myPanel.add(new JLabel("Please select your datset:"));
myPanel.add(inputfile);
myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.Y_AXIS));
int result = JOptionPane.showConfirmDialog(
null, myPanel, "CPM Program", JOptionPane.OK_CANCEL_OPTION);
double alpha = Double.parseDouble(alphaField.getText());
int numpat = Integer.parseInt(kField.getText());
int num_inst = Integer.parseInt(nField.getText());
int num_attr = Integer.parseInt(mField.getText());
String projname = (projnameField.getText());
In reference to the above image I have two questions:
Notice the labels are centered. How can I put those in the left side like this:
Project name: --textbox--
Number of instances: --textbox--
In the label, "Please select you dataset", I want to browse the file, select it and copy the full path in a blank box in the front of "Please select you dataset" label, but I do not know how I should do it.
1- The first problem is that all of the labels such as project name or number of instances are centered (it seems!). How can I put those in the left side?
JLabel has a constructor that takes an int as one of the parameters, and you can use it to position your text held in the JLabel.
2- The second problem is that text fields are not in the front of labels and are below of them. I want to have each text field in the front of the label such as:
Layouts are the key here. Consider using GridBagLayout (which can be somewhat difficult to use initially) or MigLayout (easier to use but you have to download it first) to allow use of a more tabular structure for your GUI.
For example, please have a look at my code in this answer for an example of tabular structure using GridBagLayout.
You might use a GroupLayout for that first section. E.G.
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
class TwoColumnLayout {
/**
* Provides a JPanel with two columns (labels & fields) laid out using
* GroupLayout. The arrays must be of equal size.
*
* Typical fields would be single line textual/input components such as
* JTextField, JPasswordField, JFormattedTextField, JSpinner, JComboBox,
* JCheckBox.. & the multi-line components wrapped in a JScrollPane -
* JTextArea or (at a stretch) JList or JTable.
*
* #param labels The first column contains labels.
* #param fields The last column contains fields.
* #param addMnemonics Add mnemonic by next available letter in label text.
* #return JComponent A JPanel with two columns of the components provided.
*/
public static JComponent getTwoColumnLayout(
JLabel[] labels,
JComponent[] fields,
boolean addMnemonics) {
if (labels.length != fields.length) {
String s = labels.length + " labels supplied for "
+ fields.length + " fields!";
throw new IllegalArgumentException(s);
}
JComponent panel = new JPanel();
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
// Turn on automatically adding gaps between components
layout.setAutoCreateGaps(true);
// Create a sequential group for the horizontal axis.
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
GroupLayout.Group yLabelGroup = layout.createParallelGroup(GroupLayout.Alignment.TRAILING);
hGroup.addGroup(yLabelGroup);
GroupLayout.Group yFieldGroup = layout.createParallelGroup();
hGroup.addGroup(yFieldGroup);
layout.setHorizontalGroup(hGroup);
// Create a sequential group for the vertical axis.
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
layout.setVerticalGroup(vGroup);
int p = GroupLayout.PREFERRED_SIZE;
// add the components to the groups
for (JLabel label : labels) {
yLabelGroup.addComponent(label);
}
for (Component field : fields) {
yFieldGroup.addComponent(field, p, p, p);
}
for (int ii = 0; ii < labels.length; ii++) {
vGroup.addGroup(layout.createParallelGroup().
addComponent(labels[ii]).
addComponent(fields[ii], p, p, p));
}
if (addMnemonics) {
addMnemonics(labels, fields);
}
return panel;
}
private final static void addMnemonics(
JLabel[] labels,
JComponent[] fields) {
Map<Character, Object> m = new HashMap<Character, Object>();
for (int ii = 0; ii < labels.length; ii++) {
labels[ii].setLabelFor(fields[ii]);
String lwr = labels[ii].getText().toLowerCase();
for (int jj = 0; jj < lwr.length(); jj++) {
char ch = lwr.charAt(jj);
if (m.get(ch) == null && Character.isLetterOrDigit(ch)) {
m.put(ch, ch);
labels[ii].setDisplayedMnemonic(ch);
break;
}
}
}
}
/**
* Provides a JPanel with two columns (labels & fields) laid out using
* GroupLayout. The arrays must be of equal size.
*
* #param labelStrings Strings that will be used for labels.
* #param fields The corresponding fields.
* #return JComponent A JPanel with two columns of the components provided.
*/
public static JComponent getTwoColumnLayout(
String[] labelStrings,
JComponent[] fields) {
JLabel[] labels = new JLabel[labelStrings.length];
for (int ii = 0; ii < labels.length; ii++) {
labels[ii] = new JLabel(labelStrings[ii]);
}
return getTwoColumnLayout(labels, fields);
}
/**
* Provides a JPanel with two columns (labels & fields) laid out using
* GroupLayout. The arrays must be of equal size.
*
* #param labels The first column contains labels.
* #param fields The last column contains fields.
* #return JComponent A JPanel with two columns of the components provided.
*/
public static JComponent getTwoColumnLayout(
JLabel[] labels,
JComponent[] fields) {
return getTwoColumnLayout(labels, fields, true);
}
public static String getProperty(String name) {
return name + ": \t"
+ System.getProperty(name)
+ System.getProperty("line.separator");
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JTextField projnameField = new JTextField(10);
JTextField nField = new JTextField(5);
JTextField mField = new JTextField(5);
JTextField alphaField = new JTextField(5);
JTextField kField = new JTextField(5);
JTextField[] components = {
projnameField,
nField,
mField,
alphaField,
kField
};
String[] labels = {
"Project Name:",
"Number of instances:",
"Number of attributes:",
"Alpha:",
"Number of patterns:"
};
JOptionPane.showMessageDialog(null,
getTwoColumnLayout(labels,components));
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
these are my code I've problem with label when i read line from the text filed i can add the labels "_" that they are equal to the size of the word the program road it before.
I've problem creating label , I hope you understand my problem & please if you can can you give me a solution ?
public class HangGame extends JFrame {
JLabel lbl;
JLabel word ;
private String[]myword = new String [20];
Game() {
}
void readfile () {
Properties prob = new Properties();
try{
for(int x=0; x<n; x++){
}
}}
private void initLabelPanel() {
//craete array of labels the size of the word
letterHolderPanel = new JPanel();
int count =0;
//if you run my code I've problem with this array [myword.length()] the compiler can not find it.
wordToFindLabels = new JLabel[myword.length()];
//Initiate each labels text add tp array and to letter holder panel
for (int i = 0; ih; i++) {JLabel lbl = new JLabel("_");
letterHolderPanel.add(lbl);
lbl.setBounds();
}
}
}
myword is an array of Strings, not a single String so you need to replace:
wordToFindLabels = new JLabel[myword.length()];
with
wordToFindLabels = new JLabel[myword.length];
You could rename the variable to, say, mywordArray, to avoid confusion.
Also use a layout manager rather than using absolute positioning(null layout).
See: Doing Without a Layout Manager (Absolute Positioning)
length is property not method change the code accordingly
wordToFindLabels = new JLabel[myword.length];
and now youre code will be
for (int i = 0; i < wordToFindLabels.length; i++) {
String labelValue="";
if(myword[i] != null) {
for (int j = 0; j < myword[i].length(); j++){
labelValue+="_"
}
}
JLabel lbl = new JLabel(labelValue);
wordToFindLabels[i] = lbl;
letterHolderPanel.add(lbl);
lbl.setBounds(30, 60, 20, 20);
}
So I have a small amount of objects (10 JLabels) and I want to change their text depending on the users input.
The Initializer for the labels goes like this:
private JLabel j1 = new JLabel();
private JLabel j2 = new JLabel();
private JLabel j3 = new JLabel();
...etc
and continues on to 10.
How do I mass change the text of each JLabel without writing each variable name every time?
I had an idea like below, but I don't know how to access the variable by name from strings.
for(int x=1;x<=10;x++){
String d = (String) x; //this isn't what d equals, it's example.
String label = "j"+x;
label.setText(d); //I know this won't work, but this is what I want to do
}
Is there any way this can be done without errors?
This is an excellent chance to use an array to store your JLabel objects:
private JLabel[] labels = new JLabel[10];
for (int i=0; i<10; i++) {
labels[i] = new JLabel();
}
/* ... */
for (int i=0; i<10; i++) {
labels[i].setText("Hello from label " + i);
}
If you have created the JLabel as an array like JLabel j[10] = new JLabel[10]. Then you can use the for loop to create an instance for each index and then set the text as well.
for(int x=0;x<10;x++){
j[x] = new JLabel();
String d = String.valueOf(x);
String label = "j"+x;
j[x].setText(d);
}
I am working on a program that needs to determine which JCheckBox was selected. I am using three different button groups, two of which have overlapping text. I need to be able to determine which triggered the event so I can add the appropriate charge (COSTPERROOM vs COSTPERCAR) to the total(costOfHome). What I cant figure out is how to differentiate the checkbox source if the text is the same. I was thinking of trying to change the text on one button group to strings like "one" "two" etc, but that introduces a bigger problem with how I have created the checkboxes in the first place. Any ideas would be appreciated, thanks in advance!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JMyNewHome extends JFrame implements ItemListener {
// class private variables
private int costOfHome = 0;
// class arrays
private String[] homeNamesArray = {"Aspen", "Brittany", "Colonial", "Dartmour"};
private int[] homeCostArray = {100000, 120000, 180000, 250000};
// class constants
private final int MAXROOMS = 3;
private final int MAXCARS = 4;
private final int COSTPERROOM = 10500;
private final int COSTPERCAR = 7775;
JLabel costLabel = new JLabel();
// constructor
public JMyNewHome ()
{
super("My New Home");
setSize(450,150);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Font labelFont = new Font("Time New Roman", Font.BOLD, 24);
setJLabelString(costLabel, costOfHome);
costLabel.setFont(labelFont);
add(costLabel);
JCheckBox[] homesCheckBoxes = new JCheckBox[homeNamesArray.length];
ButtonGroup homeSelection = new ButtonGroup();
for (int i = 0; i < homeNamesArray.length; i++)
{
homesCheckBoxes[i] = new JCheckBox(homeNamesArray[i], false);
homeSelection.add(homesCheckBoxes[i]);
homesCheckBoxes[i].addItemListener(this);
add(homesCheckBoxes[i]);
}
JLabel roomLabel = new JLabel("Number of Rooms in Home");
add(roomLabel);
ButtonGroup roomSelection = new ButtonGroup();
JCheckBox[] roomCheckBoxes = new JCheckBox[MAXROOMS];
for (int i = 0; i < MAXROOMS; i++)
{
String intToString = Integer.toString(i + 2);
roomCheckBoxes[i] = new JCheckBox(intToString);
roomSelection.add(roomCheckBoxes[i]);
roomCheckBoxes[i].addItemListener(this);
add(roomCheckBoxes[i]);
}
JLabel carLabel = new JLabel("Size of Garage (number of cars)");
add(carLabel);
ButtonGroup carSelection = new ButtonGroup();
JCheckBox[] carCheckBoxes = new JCheckBox[MAXCARS];
for (int i = 0; i < MAXCARS; i++)
{
String intToString = Integer.toString(i);
carCheckBoxes[i] = new JCheckBox(intToString);
carSelection.add(carCheckBoxes[i]);
carCheckBoxes[i].addItemListener(this);
add(carCheckBoxes[i]);
}
setVisible(true);
}
private void setJLabelString(JLabel label, int cost)
{
String costOfHomeString = Integer.toString(cost);
label.setText("Cost of Configured Home: $ " + costOfHomeString + ".00");
invalidate();
validate();
repaint();
}
public void itemStateChanged(ItemEvent e) {
JCheckBox source = (JCheckBox) e.getItem();
String sourceText = source.getText();
//JLabel testLabel = new JLabel(sourceText);
//add(testLabel);
//invalidate();
//validate();
//repaint();
for (int i = 0; i < homeNamesArray.length; i++)
{
if (sourceText == homeNamesArray[i])
{
setJLabelString(costLabel, costOfHome + homeCostArray[i]);
}
}
}
}
I would
Use JRadioButtons for this rather than JCheckBoxes since I think it is GUI standard to have a set of JRadioButtons that only allow one selection rather than a set of JCheckBoxes.
Although you may have "overlapping text" you can set the button's actionCommand to anything you want to. So one set of buttons could have actionCommands that are "room count 2", "room count 3", ...
But even better, the ButtonGroup can tell you which toggle button (either check box or radio button) has been selected since if you call getSelection() on it, it will get you the ButtonModel of the selected button (or null if none have been selected), and then you can get the actionCommand from the model via its getActionCommand() method. Just first check that the model selected isn't null.
Learn to use the layout managers as they can make your job much easier.
For instance, if you had two ButtonGroups:
ButtonGroup fooBtnGroup = new ButtonGroup();
ButtonGroup barBtnGroup = new ButtonGroup();
If you add a bunch of JRadioButtons to these ButtonGroups, you can then check which buttons were selected for which group like so (the following code is in a JButton's ActionListener):
ButtonModel fooModel = fooBtnGroup.getSelection();
String fooSelection = fooModel == null ? "No foo selected" : fooModel.getActionCommand();
ButtonModel barModel = barBtnGroup.getSelection();
String barSelection = barModel == null ? "No bar selected" : barModel.getActionCommand();
System.out.println("Foo selected: " + fooSelection);
System.out.println("Bar selected: " + barSelection);
Assuming of course that you've set the actionCommand for your buttons.
Checkboxes have item listeners like any other swing component. I would decouple them, and simply add listeners to each
{
checkBox.addActionListener(actionListener);
}
http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxItemListener.htm