So basically I am learning some basic java and I am currently writing a little "game" that tells you which button to click and if you click the correct one you receive a point. The buttons are defined as b1, b2, b3, and b4. The text on them says "Button 1", "Button 2", "Button 3", and "Button 4".
What I wish to accomplish is each time I click a button, the values are reassigned randomly so that the b1 text for example might say "Button 3". But it would be random. I used Java random to get it to work how I want but now I need to solve the problem of having the buttons being assigned the same values. For example, b1 and b3 might both be named "Button 2". I'm not sure how to go about solving this problem, any help would be greatly appreciated. It is kind of frustrating me.
Ok so here is my code.... finally. Have a terrible internet connection atm.
I put comments where I need the help
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui extends JFrame implements ActionListener {
private JButton b1 = new JButton("Button 1");
private JButton b2 = new JButton("Button 2");
private JButton b3 = new JButton("Button 3");
private JButton b4 = new JButton("Button 4");
private static JLabel label = new JLabel();
private static JLabel label2 = new JLabel("You currently have 0 points.");
private JPanel p = new JPanel(new GridBagLayout());
private int points = 0;
private int randomButton;
public Gui() {
super("Button Game");
newLabel();
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.gridx = 2;
c.gridy = 1;
p.add(b1,c);
c.gridx = 1;
c.gridy = 2;
p.add(b2, c);
c.gridx = 3;
c.gridy = 2;
p.add(b3, c);
c.gridx = 2;
c.gridy = 3;
p.add(b4, c);
c.gridx = 2;
c.gridy = 2;
p.add(label, c);
c.gridx = 2;
c.gridy = 4;
p.add(label2, c);
add(p);
}
public void rearrangeButtons() {
//HERE IS WHERE I AM HAVING THE PROBLEM
//b1.setText("Button " + randomButton);
//b2.setText(newText);
//b3.setText(newText);
//b4.setText(newText);
}
public static int random(int range) {
return (int)(java.lang.Math.random() * (range+1));
}
public static void newLabel() {
switch(random(3)) {
case 0:
label.setText("Press button 1");
break;
case 1:
label.setText("Press button 2");
break;
case 2:
label.setText("Press button 3");
break;
case 3:
label.setText("Press button 4");
break;
}
}
#Override
public void actionPerformed(ActionEvent e) {
String number = label.getText();
if (e.getSource() == b1) {
if (number.endsWith("1")) {
points++;
newLabel();
} else {
points = 0;
}
}
if (e.getSource() == b2) {
if (number.endsWith("2")) {
points++;
newLabel();
} else {
points = 0;
}
}
if (e.getSource() == b3) {
if (number.endsWith("3")) {
points++;
newLabel();
} else {
points = 0;
}
}
if (e.getSource() == b4) {
if (number.endsWith("4")) {
points++;
newLabel();
} else {
points = 0;
newLabel();
}
}
rearrangeButtons();
label2.setText("You currently have " + points + " points.");
}
}
Collections gives you an easy way to do this:
Declare your button text in a List:
List<String> myList =
new ArrayList<String>(Arrays.asList("text1", "text2", "text3", "text4"));
Every time you want to change the text on the buttons, shuffle List and assign:
Collections.shuffle(myList);
b1.setText(myList.get(0));
b2.setText(myList.get(1));
b3.setText(myList.get(2));
b4.setText(myList.get(3));
Edit: Brian's way of using Shuffle is better; forgot about that method, haha. My bad. Ignore this answer and use that.
Create an ArrayList of your strings with "button 1", "button 2", "button 3", "button 4"
Every time a button is clicked, create an ArrayList that is a copy of the above array (not a copy of the reference). eg: ArrayList<String> copy = new ArrayList<String>(intialArrayList);
Then use JButton#setText and Math.Random() to choose one of those strings for the first button. Every time you choose a string, delete the string from the copy. (that would make it impossible to set a button text twice).
Then repeat with the remaining buttons, but make sure the random number generated is first between 0-3, then 0-2, then 0-1.
eg:
int j = 3;
ArrayList<String> copy = new ArrayList<String>(initialArrayList);
for(int i = 0; i< 3; i++) {
//int rand = generate random number between i and j
String text = copy.get(rand);
// setText(text) for each b1, b2, b3, b4;
// copy.remove(text);
j--;
}
Create a separate method for this so you don't have to keep typing this in for each actionPerformed method.
That's just how I would do it.
Maybe each time you want to reset the text of your buttons you build a list of the 4 texts "Button 1", "Button 2", "Button 3", "Button 4". Randomly pick one, assign it to b1, and then remove it from your list which would now have only 3 available texts left. Randomly choose again from your remaining list of 3 and assign that to b2. Continue until your list of available texts is empty (or 4 times in this case). When you need to reset these texts again just reset your list of available texts back to "Button 1", "Button 2", "Button 3", "Button 4" and repeat.
Related
I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();
I am working on a GUI (that this community has been extremely helpful with so far) and I have reached another important step I need to achieve.
Currently my GUI consists of a JOptionsPane. Inside this pane is a panel that contains two lists and four buttons. Two of the buttons are arrows who's text is ">" and "<". (The buttons are in between both lists.)
Those buttons work correctly. A user can select one of the objects from the first list and then click the > and it will move to the second list and visa versa.
Next I need to add a feature where there is a ">>" button. This will move all the items in the first list to the second. I really have no idea how to handle this part. I am assuming it is some type of while loop although I'm not entirely sure.
First allow me to post the simple snipplet that shows the > button.
buttonin = new JButton(" > ");
buttonin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int[] fromindex = outputDetails.getSelectedIndices();
Object[] from = outputDetails.getSelectedValues();
for(int i=0; i< from.length; i++){
output.addElement(from[i]);
System.out.println(output);
}
for(int i = (fromindex.length-1); i>=0; i--){
input.remove(fromindex[i]);
}
}
});
Next I will post the full code in case that is needed to understand what I am trying to achieve. I hope this is enough information for someone to assist me if not I apologize, the actual program is very long and I couldn't think of an easy way to isolate this test case.
public static void displayGUI(){
int result = JOptionPane.showOptionDialog(null, getPanel(),"JOptionPane Example : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Confirm","Create Return"}, "default");
if(result == 1){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
}
private static JPanel getPanel(){
JPanel panel = new JPanel();
JPanel panelTop = new JPanel();
JPanel topButtons = new JPanel();
JPanel bottomButtons = new JPanel();
String text = "<html>"
+"Batch <font size=6 color=>"+MainWriter.batchHeaderCounter+"</font> of <font size=6>"+BatchCounter.BatchTotal+"</font>"
+"<br>Batch Header: <font size=5><font color=red>"+MainWriter.BatchHeader+"</font>"
+"</html>";
JLabel topLabel = new JLabel(text);
panelTop.add(topLabel);
input = new DefaultListModel();
output = new DefaultListModel();
String[] shoppingItems = new String[MainWriter.entryDetails.size()];
shoppingItems = MainWriter.entryDetails.toArray(shoppingItems);
for(int i = 0; i < shoppingItems.length; i++){
input.addElement(shoppingItems[i]);
}
outputDetails = new JList(input);
outputDetails.setVisibleRowCount(10);
outputDetails.setFixedCellHeight(20);
outputDetails.setFixedCellWidth(400);
outputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane list1 = new JScrollPane(outputDetails);
inputDetails = new JList(output);
inputDetails.setVisibleRowCount(10);
inputDetails.setFixedCellHeight(20);
inputDetails.setFixedCellWidth(400);
inputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane list2 = new JScrollPane(inputDetails);
JPanel buttonPanel = new JPanel();
buttonin = new JButton(" > ");
buttonin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int[] fromindex = outputDetails.getSelectedIndices();
Object[] from = outputDetails.getSelectedValues();
for(int i=0; i< from.length; i++){
output.addElement(from[i]);
System.out.println(output);
}
for(int i = (fromindex.length-1); i>=0; i--){
input.remove(fromindex[i]);
}
}
});
buttonPanel.add(buttonin);
buttonout = new JButton(" < ");
buttonout.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Object[] to = inputDetails.getSelectedValues();
int[] toindex = inputDetails.getSelectedIndices();
for(int i = 0; i < to.length; i++){
input.addElement(to[i]);
}
for(int i = (toindex.length-1); i >=0; i--){
output.remove(toindex[i]);
}
}
});
buttonall = new JButton(" >> ");
buttonall.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(initialScreenDecisions.equals("DEFAULT")){
JOptionPane.showMessageDialog(null, "You have selected to add all entry details. Please " +
"\nclick okay on the next scren to confirm or click " +
"\n'>>' again to cancel the apply all option.");
initialScreenDecisions="ADDALL";
}else if(initialScreenDecisions.equals("ADDALL")){
JOptionPane.showMessageDialog(null, "You have canceled the apply all option.");
initialScreenDecisions="DEFAULT";
}else{
JOptionPane.showMessageDialog(null, "You must disable the '<<' option before you can use this.");
}
}
});
buttonnone = new JButton(" << ");
buttonnone.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(initialScreenDecisions.equals("DEFAULT")){
JOptionPane.showMessageDialog(null, "You have selected to skip the current batch and" +
"\nomit all of it's entries. Click okay on the next" +
"\nscreen to confirm or click '<<' again to" +
"\ncancel the option.");
initialScreenDecisions="NONE";
}else if(initialScreenDecisions.equals("NONE")){
JOptionPane.showMessageDialog(null, "You have canceled the omit all option.");
initialScreenDecisions="DEFAULT";
}else{
JOptionPane.showMessageDialog(null, "You must disable the '>>' option before you can use this.");
}
}
});
buttonhelp = new JButton("HELP");
buttonhelp.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "This screen allows you to determine the entry details from" +
"\nthe current batch that will be included in the final return." +
"\nSelect the details you wish to include and click the > arrow to" +
"\nmove them to the right side. Pressing the >> button will" +
"\ninclude all entry details for the current batch in the final" +
"\nreturn. Clicking the < button will move a detail back."+
"\nClick << to omit the entire batch. Use confirm to continue"+
"\nto the next step or 'create return' to finish the Nacha return"+
"\nwith all past additions.");
}
});
buttonPanel.setLayout(new BorderLayout());
topButtons.add(buttonin);
topButtons.add(buttonall);
topButtons.add(buttonnone);
topButtons.add(buttonout);
bottomButtons.add(buttonhelp);
buttonPanel.add(topButtons,BorderLayout.NORTH);
buttonPanel.add(buttonhelp,BorderLayout.SOUTH);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
bottomPanel.add(list1);
bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
bottomPanel.add(list2);
bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
panel.setLayout(new BorderLayout());
panel.add(panelTop,BorderLayout.NORTH);
panel.add(bottomPanel,BorderLayout.CENTER);
panel.setOpaque(true);
return panel;
}
You can ignore the above >> button contents. Right now it will allow the user to select all of the items in the list it just doesn't visually show the selection. If I get the >> button to move all the items at once then I won't need the extra steps you can see I have implemented.
I'm not too sure what all your variable types are, but I think this should work in your ActionListener for >>.
for (int i = 0; i < input.getSize(); i++) {
output.addElement(input.get(i));
}
input.clear();
Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.
I've made a simple calculator
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
GridLayout layout = new GridLayout(5, 1);
JLabel l1 = new JLabel("Number 1:");
JLabel l2 = new JLabel("Number 2:");
JLabel l3 = new JLabel("Answer:");
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(30);
JTextField t3 = new JTextField(30);
JButton add = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div= new JButton("/");
Float ans;
public Calculator()
{
super("Calculator");
setSize(250, 200);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(add);
add(sub);
add(mul);
add(div);
setLayout(layout);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String n1 = t1.getText();
String n2 = t2.getText();
Float num1 = Float.parseFloat(n1);
Float num2 = Float.parseFloat(n2);
Object clicked = e.getSource();
if(add == clicked)
{
t3.setText(String.valueOf(num1+num2));
}
else if(sub == clicked)
{
t3.setText(String.valueOf(num1-num2));
}
else if(mul == clicked)
{
t3.setText(String.valueOf(num1*num2));
}
else
{
if(num2 == 0)
t3.setText("Can't Divide By Zero");
else
t3.setText(String.valueOf(num1/num2));
}
}
}
And a class to read it
public class UseMyFrame
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setVisible(true);
}
}
My problem is I want to add another feature and put 9 buttons 1-9 that when pressed will place their respective numbers on the textfield, but I don't know how to set them to appear at the textfield, I first wanna do set.text but i realized how will the button know where to put its number because if I do set.text i need to either put it on textfield1 or textfield 2. I wanna make the number appear in textfield1 first then on textfield2 if there is already a number on textfield1
but I don't know how to set them to appear at the textfield
The Action you add to your JButton should extend TextAction. The TextAction has access to the last focused text component (so you don't have to keep track of this information yourself). Your code would be something like:
public class AddDigitAction extends TextAction
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String digit = button.getActionCommand();
JTextComponent target = getTextComponent(e);
target.replaceSelection(digit);
}
You can use the same Action for all your buttons. The replaceSelection() method is an easy way to add text to the textfield. It will insert text at the last location of the caret in the text field.
So you need to create a boolean variable that will help you keep track of which field to put the number in. Then in the action of the button you can use that to decide.
if(first){
textField1.setText("1");
first = false;
}else{
textField2.setText("1");
first = true;
}
Now, this snippet is very simple and does not consider all the possibilities. It simply toggles between the two fields. You can extend it to what you need.
If you only want to have single digits:
if(t1.getText().length() == 0)
t1.setText(...);
else
t2.setText(...);
Better: Find out which textfield has the current focus (see javadocs) and put the digit at the end of that text:
tFocused.setText(tFocused.getText() + digit)
first set global int curs = 0 and global string screen
then at each numeric button put that code (all about concatenation of strings )
if(curs==0){
screen="1"; // change the number for each button
jTextField1.setText(screen);
a=Double.parseDouble(screen);
curs++;
}else{
screen=screen+"1"; // // change the number for each button
jTextField1.setText(screen);
a=Double.parseDouble(screen);
curs++;
}
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