Is it possible to check for text in a GUI button? - java

This is a really simple code where when I click a button, the text on the button becomes "..." which is a string variable called move.
What I'm trying to figure out is if it is possible to check the text of a button in the if (e.getSource()==) command.
JButton [] button;
String move="...";
button =new JButton[25];
for (int a=0;a<25;a++)
{
button[a]=new JButton();
p1.add(button[a]);
button[a].addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
for (int a=0; a<25;a++)
{
if (e.getSource()==button[a])
{
button[a].setText(move);
}
}
}
So after the code above, a button will have the text "..." on it. Now what I want for the next if (e.getSource()==) command is: if the button I click has the text (move), run the code.
I tried hundreds of random codes to see if they'll work but no luck:
sort of like this:
if (e.getSource()==button[a].text(move))
OR
if (e.getSource()==button[a].getText.equals(move))
if (The button i click has the text (move) it will run this code)
{
button[a].setBackground(Color.GREEN);
}
I'm fairly new to programming and I need this for my Checkers game.
Is it possible to do what I am asking for?

String comparison in Java should be done with .equals() not ==.

Maybe you mean like this:
if (e.getSource() == button[a]) {
if (button[a].getText().equals(move)) {
// do some logic here
button[a].setBackground(Color.GREEN);
}
}

The examples you have checking the source against the button text doesn't make a lot of sense. You're adding an action listener on the button not a field of the button. Additionally, getSource returns an Object so if you need to get to any of its member values you'll need to cast it to the type it should be. In your case you're returned an Object with an actual type JButton.
JButton button = new JButton("Hello");
button.addActionListener((e) -> System.out.println(
e.getSource() instanceof JButton
));
button.doClick();
true
So, given a button you can get the text like so:
JButton button = new JButton("Hello");
button.addActionListener((e) -> System.out.println(
((JButton)e.getSource()).getText()
));
button.doClick();
Hello
So, to check move against it would be like so:
String move = "Howdy";
JButton button = new JButton("Hello");
button.addActionListener((e) -> System.out.println(
((JButton) e.getSource()).getText().equals(move)
));
button.doClick();
false
Another thing to note is when you get an instance of a button through getSource you don't need to find that instance in the array before using it; it's returned to you via the action listener. For example, run this code:
JButton[] buttons = new JButton[10];
Random r = new Random(System.currentTimeMillis());
String newText = "New";
for (int i = 0; i < buttons.length; ++i) {
buttons[i] = new JButton(String.valueOf(r.nextInt()));
buttons[i].addActionListener((e) -> ((JButton)e.getSource()).setText(newText + " " + r.nextInt()));
}
Arrays.stream(buttons).forEach(b -> {
System.out.println(b.getText());
b.doClick();
System.out.println(b.getText());
});

Related

Adding a new button after an event

Writing a program to increment a counter when a +1 button is pressed, then when the counter reaches a certain number, remove the +1 button and replace it with a +2 button and so on. I create both buttons at first but just set btnCount1 to setVisible(false). When the certain number passes, I make btnCount invisible and btnCount1 visible and increment by two from there. When it reaches 10 clicks, the btnCount disappears, but btnCount1 does not appear.
I have tried making an if(arg0.equals(btnCount1)), and incrementing by two from there. I tried putting the add(btnCount1) inside the else if statement to create it after the elseif condition is true.
public class AWTCounter extends Frame implements ActionListener
private Label lblCount;
private TextField tfCount;
private Button btnCount;
private Button btnCount1;
private int count = 0;
public AWTCounter() {
setLayout(new FlowLayout());
lblCount = new Label("Counter");
add(lblCount);
tfCount = new TextField(count + "",10);
tfCount.setEditable(false);
add(tfCount);
btnCount = new Button("Add 1");
btnCount1 = new Button("Add 2");
add(btnCount);
add(btnCount1);
btnCount1.setVisible(false);
btnCount.addActionListener(this);
btnCount1.addActionListener(this);
setTitle("AWT Counter");
setSize(500,500);
}
public static void main(String[]args) {
AWTCounter app = new AWTCounter();
}
public void actionPerformed(ActionEvent arg0) {
if(count <= 10) {
++count; //Increase the counter value
tfCount.setText(count + "");
}else if(count > 10) {
btnCount.setVisible(false);
btnCount1.setVisible(true);
count += 2;
tfCount.setText(count + "");
}
}
The better solution here is to just have one button object and a separate variable for the current increment amount. When you hit the required count, increase the increment amount and change the button's label to the new value.
There are also a few other things you could do better here.
Use String.valueOf() instead of int + "" for String representations of integers if you're not adding words before or after the integer.
Don't add obvious comments for code. (e.g. 'increment variable x', 'set textString to the new value')
Use descriptive names for method parameters and variables.
Use Labels instead of TextFields for text that doesn't need to be editable or selectable like counter displays.
I'd personally change the name of lblCount to something like lblTitle as well, since changing your tfCount to a Label would logically take up that name and lblTitle makes more sense.
Here's a better way to implement actionPerformed:
private int increment = 1;
private Label lblCount;
...
public void actionPerformed(ActionEvent ignore) {
if(count == 10) {
btnCount.setLabel("Add " + (++increment));
}
lblCount.setText(String.valueOf(count += increment));
}

JFormattedTextField not returning correct text

I am trying to make a simple dialog box in Beanshell - it should read the contents of three editable text fields and, on button press, carry out a simple task accordingly. I am totally stumped by an error that I am getting where I cannot read the text in some of the fields.
Here’s the code:
// Set up the text fields
textField_Y= new JFormattedTextField();
textField_Y.setValue(150);
textField_Y.setColumns(4);
textField_Y.setEditable(true);
textField_X= new JFormattedTextField();
textField_X.setValue(0);
textField_X.setColumns(4);
textField_X.setEditable(true);
textField_n= new JFormattedTextField();
textField_n.setValue(20);
textField_n.setColumns(4);
textField_n.setEditable(true);
button = new JButton("Generate Stage Position List");
// some Code here to arrange the items within a GUI window
// Try to read the values
button.addActionListener(new ActionListener() {
actionPerformed(ActionEvent eText) {
//Get info from dialog
yShift = textField_Y.getText();
xShift = textField_X.getText();
nPos = Integer.parseInt(textField_n.getText());
print(xshift+" "+yshift+" "+nPos);
});
I run this and the dialog box displays correctly. I don’t change any values, just click the button, and it should print “150 0 20”. Instead it prints “void void 20”. I don’t have the faintest clue why one field is returning a correct number and the other two are returning void. They should all be identical! Can anyone help?
First, looking at this code...
button.addActionListener(new ActionListener() {
actionPerformed(ActionEvent eText) {
//Get info from dialog
yShift = textField_Y.getText();
xShift = textField_X.getText();
nPos = Integer.parseInt(textField_n.getText());
print(xshift+" "+yshift+" "+nPos);
});
yShift != yshift and xShift != xshift. Remember, Java is case sensitive.
I would also recommend making use of getValue instead of getText

How can I make a javafx program that takes a number or two and calls a method from another class with that information?

public ComplexNum add(ComplexNum c){
double addedReal = (this.real + c.real);
double addedImag = (this.imag + c.imag);
System.out.println(addedReal);
return new ComplexNum(addedReal,addedImag);
}
This is one of the simpler methods. I want to make a controller class that lets a user enter the first number, press an addition button, enter the second number, press enter, and then have the string representation of the return value printed to a label. I'm not sure how I can call the right method using the controller. I though that maybe I should have a method that checks for specific text(say "add") from the button pressed and executes the correct method for it but I feel like that's not the right way.
I basically want the first number entered to be treated as the "this" pointer for each of the methods, and any following numbers as the parameter.
You have to set an action listener on the button. Example using JavaFX 8:
Button button = new Button();
button.setText("Button Text");
button.setOnAction((ActionEvent event) -> {
System.out.println("Button Clicked!");
});
For you ENTER input, you need to add an event handler to your node. E.g.:
Scene scene = new Scene(root);
scene.addEventHandler(KeyEvent.KEY_PRESSED, (KeyEvent key) -> {
if(key.getCode().equals(KeyCode.ENTER)) {
System.out.println("ENTER pressed");
}
}
You could do something like this (this obviously is incomplete) hopefully can point you in a direction:
long runningTotal = 0;
Button plusButton = new Button("+");
Button enterButton = new Button("Enter");
TextField tf = new TextField();
Label displayLabel = new Label();
//Setup you UI here
plusButton.setOnAction(event -> {
String stringValue = tx.getText();
long value = Long.parseLong(stringValue);
runningTotal = runningTotal + value;
});
enterButton.setOnAction(event -> {
//if you need to remember your last pressed button, you could have done that also, then perform that action here
displayLabel.setText("" + runningTotal);
});

Using the same actionListener to open individual GUI's for each button on a grid

I have a loop that makes a 3x3 grid of buttons. I'm trying to make it so when the button is pressed, a window opens for the user to add data about the button. The window opens up and everything works for the first time. Once I save this window and click a new button, there is a white square (probably the panel) covering everything. If I make the window bigger I can see the text fields behind it but the white square stays at the same size (size of non expanded window). After ex;anding the window I cab se that the data I added for the last button is still present in the 'new' window, letting me know that I am probably opening the same window and new ones aren't being created. Is there a way to create a totally new window each time?
Here is the loop to create the buttons
for (int i = 0; i < addButtons3.length; i++) {
addButtons3[i] = new JButton(" Add Bed "); // make text big
addButtons3[i].addActionListener(new RoomListener());
addButtons3[i].setActionCommand("" + i);
gbc.fill = GridBagConstraints.BOTH;
room3Panel.add(addButtons3[i]);
}
here is the actionListener for each button
class RoomListener implements ActionListener{
public void actionPerformed(ActionEvent event){
AbstractButton btn = (AbstractButton) event.getSource();
source = event.getActionCommand();
System.out.println(source);
x = Integer.parseInt(source);
y = Integer.parseInt(roomSource);
btn.setText("Adding bed..");
intFrame8.setMaximizable(true); //Add maximize
intFrame8.setIconifiable(true); //Make it configurable
intFrame8.setResizable(true); //Make it resizable
intFrame8.setClosable(true); //How will it react on close?
intFrame8.setDefaultCloseOperation(DISPOSE_ON_CLOSE); //Like this
intFrame8.setSize(320,240);
desktopPane.add(intFrame8);
JPanel addRoomPanel = new JPanel();
addRoomPanel.setLayout(new GridLayout(7,1,5,5)); //row/col/rspace/cspace
addRoomPanel.setBackground(Color.white);
intFrame8.getContentPane().add(addRoomPanel);
intFrame8.toFront();
//Name text field
nameLabel.setText("Name: ");
name.addActionListener(new nameListener());
addRoomPanel.add(nameLabel);
addRoomPanel.add(name);
//DoB text field
dobLabel.setText("Date of Birth: ");
dob.addActionListener(new dobListener());
addRoomPanel.add(dobLabel);
addRoomPanel.add(dob);
//Passport Number text field
passNum.addActionListener(new passNumListener());
addRoomPanel.add(passNumLabel);
addRoomPanel.add(passNum);
//Start Date text field
startDate.addActionListener(new startDateListener());
addRoomPanel.add(startDateLabel);
addRoomPanel.add(startDate);
//End Date text field
endDate.addActionListener(new endDateListener());
addRoomPanel.add(endDateLabel);
addRoomPanel.add(endDate);
//Comments section text field
comments.addActionListener(new commentsListener());
addRoomPanel.add(commentsLabel);
addRoomPanel.add(comments);
addBedSave.addActionListener(new bedSaveListener());
addRoomPanel.add(addBedSave);
intFrame8.setVisible(true);
}
}
Here is the actionListener for the 'save' button that closes the window
class bedSaveListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.out.println(nameTemp);
nameList[x][y] = nameTemp;
dobList[x][y] = dobTemp;
startDateList[x][y] = startDateTemp;
endDateList[x][y] = endDateTemp;
passNumList[x][y] = passNumTemp;
commentsList[x][y] = commentsTemp;
intFrame8.dispose();
switch(y){
case 0:
intFrame4.toFront();
addButtons1[x].setText(nameTemp);
break;
case 1:
intFrame5.toFront();
addButtons2[x].setText(nameTemp);
break;
case 2:
intFrame6.toFront();
addButtons3[x].setText(nameTemp);
break;
case 3:
intFrame7.toFront();
addButtons4[x].setText(nameTemp);
break;
}
}
}
Recommendation: Use if(e.getSource == some_JButton){//code} for your ActionListeners.

Adding ActionListeners to an array of buttons in an applet

I have made a game where a user must input a binary number equivalent to a decimal. User clicks on buttons that toggle between 0 and 1. This worked fine as an application in eclipse but when I tried to run as an applet it did not run correctly. Only the first button registered any events( only the first action listener was added?) How can I get this to work? Any helpful suggestions welcomed!
for(int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("0");
buttons[i].setActionCommand("0");
buttons[i].setEnabled(true);
bpanel.add(buttons[i]);
}
for (int i = 0; i<size;){
buttons[i].addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = (String) e.getActionCommand();
You have set same action command on all your buttons:
buttons[i].setActionCommand("0");
and here this particular code:
String choice = (String) e.getActionCommand();
returns 0 for every button click
Try setting different action commands for each button
All your buttons have the same text and the same action command.
You should probably change the first lines in the first loop to something like:
buttons[i] = new JButton(i + "");
buttons[i].setActionCommand(i + "");

Categories