How to Check if all the JTexFields are empty or not? - java

I am using a for loop to create 9 JTextFields and this is working fine. My problem is, I want to check of all the these JTextField is empty or not' at one time. I know there is a method like:
if (textbox.getText().trim().equals(""))
to check if the JTextField is empty or not, But I am not sure if it is suitable for the method that I am using for JTextField. Below is my for loop:
for (int index = 1; index <=9; index++)
{
JTextField field = new JTextField(3);
field.setPreferredSize(new Dimension(150, 50));
field.setHorizontalAlignment(JTextField.CENTER);
field.setEditable(false);
second.add(field);
second.add(Box.createHorizontalStrut(10));
second.add(Box.createVerticalStrut(10));
}

Store your text fields in a List so that you can iterate over them later.
public class ClassContainingTextFields {
private final ArrayList<JTextField> textFields = new ArrayList<>();
// ... inside the method that creates the fields ...
for (int i = 0; i < 9; i++) {
JTextField field = new JTextField(3);
// .. do other setup
textFields.add(field);
}
/**
* This method returns true if and only if all the text fields are empty
**/
public boolean allFieldsEmpty() {
for (JTextField textbox : textFields) {
if (! textbox.getText().trim().isEmpty() ) {
return false; // one field is non-empty, so we can stop immediately
}
}
return true; // every field was empty (or else we'd have stopped earlier)
}
// ....
}

Consider this code.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Test extends JFrame implements ActionListener {
JTextField tfs[];
JButton btn;
public Test(){
setLayout( new FlowLayout());
tfs = new JTextField[9];
for( int i=0; i< tfs.length; i++) {
tfs[i] = new JTextField(10);
add(tfs[i]);
}
add( btn = new JButton("Check"));
btn.addActionListener(this);
setSize(200,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed (ActionEvent ae){
boolean pass = true;
for(int i=0; i<tfs.length; i++)
if( tfs[i].getText().trim().equals(""))
pass = false;
System.out.println(pass?"Passed":"Failed");
}
public static void main (String args[]){
new Test();
}
}

How about implementing your own DocumentListener? You could have a Boolean that turns true when all fields are empty, and you could do your various hangman-related checks directly after every change in a fields Document.

Related

Buggy JCombobox - KeyPressed

With a JComboBox containing some elements beginning with repeated letters, typing in the character twice will return the character typed, followed by the first character of its type. For example, typing "bb" in a list containing ba, bb, and bc will return ba. However, if this list also contains bbd, continuing to press a "d" will return the bbd option. This is the same with numbers: Typing "33" returns 30, while typing "334" returns 334.
Is there a way to fix this so that a double keyPress really returns what is typed in?
Quick sample program:
String[] range = new String[401];
for (int i = 0; i <= 400; i++) {
range[i] = "" + i;
}
private javax.swing.JComboBox<String> jComboBox1;
jComboBox1 = new javax.swing.JComboBox<>();
getContentPane().setLayout(new java.awt.GridLayout());
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(range));
getContentPane().add(jComboBox1);
pack();
Item selection via keyboard is controlled by the JComboBox.KeySelectionManager, which, surprisingly, you can actually implement and change 😱
The one thing that the default implementation does is, it will try and find items which match the key stroke based on the first character of the item (when converted to a String via toString). The "neat" thing about this is, it will search from the currently selected item (if not null), if it can't find another matching item, it will start at the beginning of the model instead.
What this means is, if you type 3 repeatedly, it will, progressively move through all the items that start with 3. (30, 31, 32 ... 39, 300 ...)
Buuuut, this isn't what you apparently want, so, instead, you're going to have to supply your own algorithm.
One, very important consideration is, what happens when the user stops typing? If the user has typed 33, stops, then types 3 again, what should happen? Should it select 3 or 333?
The following is a VERY basic example, based on the DefaultKeySelectionManager used by JComoBox by default. It uses a StringBuilder to keep track of the key strokes and a Swing Timer which provides a 250 millisecond timeout, which will clear the StringBuilder after 250 milliseconds of inactivity (you could pass this value into the constructor to define your own)
When called by the JComboBox, it will simply do a linear search of the model for a item whose toString result starts with what's been typed.
This example is a case insensitivity, but you can modify it to meet your particular needs
public class MyKeySelectionManager implements KeySelectionManager {
private Timer timeout;
private StringBuilder pattern = new StringBuilder(32);
public MyKeySelectionManager() {
timeout = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pattern.delete(0, pattern.length());
}
});
timeout.setRepeats(false);
}
#Override
public int selectionForKey(char aKey, ComboBoxModel<?> model) {
timeout.stop();
pattern.append(Character.toLowerCase(aKey));
String match = pattern.toString();
for (int index = 0; index < model.getSize(); index++) {
String text = model.getElementAt(index).toString().toLowerCase();
if (text.startsWith(match)) {
timeout.start();
return index;
}
}
timeout.start();
return -1;
}
}
Runnable example
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JComboBox.KeySelectionManager;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
for (int index = 0; index < 50; index++) {
model.addElement(Integer.toString(index));
}
JComboBox cb = new JComboBox(model);
cb.setKeySelectionManager(new MyKeySelectionManager());
JFrame frame = new JFrame();
JPanel content = new JPanel(new GridBagLayout());
content.setBorder(new EmptyBorder(32, 32, 32, 32));
content.add(cb);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyKeySelectionManager implements KeySelectionManager {
private Timer timeout;
private StringBuilder pattern = new StringBuilder(32);
public MyKeySelectionManager() {
timeout = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pattern.delete(0, pattern.length());
}
});
timeout.setRepeats(false);
}
protected int indexOf(Object item, ComboBoxModel<?> model) {
for (int index = 0; index < model.getSize(); index++) {
if (model.getElementAt(index) == item) {
return index;
}
}
return -1;
}
#Override
public int selectionForKey(char aKey, ComboBoxModel<?> model) {
timeout.stop();
pattern.append(Character.toLowerCase(aKey));
String match = pattern.toString();
for (int index = 0; index < model.getSize(); index++) {
String text = model.getElementAt(index).toString().toLowerCase();
if (text.startsWith(match)) {
timeout.start();
return index;
}
}
timeout.start();
return -1;
}
}
}
Don't forget to take a look at JComboBox#setKeySelectionManager for more details

how do I filter what I entered in the JTextField and display the filtered result?

package javaisnotbannana;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class Javaisnotbannana{
public static void main(String[] args) {
window();
}
////////////////////////////////////////////////////
public static void window()
{
JFrame window= new JFrame();
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField(30);
JButton jb = new JButton("Enter");
window.setTitle("ThisisTitleofWindow");
window.setVisible(true);
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//textfield
jp.add(jt);
jt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String inoutt = jt.getText();
jl.setText(inoutt);
}
});
Why dose this lower section have the problem "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range:(how ever many characters i entered)".str is receiving what is typed in the Jtextfield and im trying to filter the input to give a different output. With out a filter it works fine like above just press enter,but when i try to press the button i and filter i get an error.
//button
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String str = jt.getText();
String text="";
int A=0;
int B=1;
int C=2;
for(int num=0;num<=str.length()/3;num++)
{
if (str.charAt(A) == 'T'&&str.charAt(B) == 'A'&&str.charAt(C)=='S')
{
text+="smell tasty";
}
else if(str.charAt(A) == 'B'&&str.charAt(B) == 'A'&&str.charAt(C)=='N')
{
text+="bannanas";
}
A+=3;
B+=3;
C+=3;
}
jl.setText(text);
}
});
jp.add(jl);
window.add(jp);
}
}
your index is overshooting use this instead
for(int num=0;num<str.length()/3;num++)
just < not <=
The problem seems to the fact that you are overthinking the it. Remember, Java Strings are zero indexed so num<=str.length()/3 should be something more like num < str.length()/3
But, having said that, the whole thing seems woefully inefficient (not to mention confusing)
You could use something like...
for (int num = 0; num + 3 < str.length(); num++) {
String test = str.substring(num, 3);
if ("tas".equalsIgnoreCase(test)) {
text = "smell tasty";
break;
} else if ("ban".equalsIgnoreCase(test)) {
text = "bannanas";
break;
}
}
But even that's a long way around an otherwise simple problem.
Instead, you could simply use something like...
String str = "tas";
String text = "";
if (str.toLowerCase().contains("tas")) {
text = "smell tasty";
} else if (str.toLowerCase().contains("ban")) {
text = "bannanas";
}

Null Pointer with JButton Array

So far I have created a frame at adds my ControlPanel class, the class takes an int, and that int is used to fill an array with JButton objects which are the added to a Panel and displayed.
However I am getting a Null Pointer error when I try to add JButtons to the array. I'm not sure why (since I thought null pointers were from when you try to reference something that isn't in the spot in the array?)
Any help on this would be great appreciated.
Error Message:
Exception in thread "main" java.lang.NullPointerException
at elevator.ControlPanel.<init>(ControlPanel.java:22)
at elevator.Elevator_Simulator.main(Elevator_Simulator.java:27)
Main Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Elevator_Simulator extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame ("Elevator Simulation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ControlPanel(8));
frame.pack();
frame.setVisible(true);
}
}
Control Panel Class:
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
public class ControlPanel extends JPanel implements ActionListener {
public JButton[] floorButton; // an array of floor buttons.
public int[] floorIn; // state of button. 0 == not click >= 1 means clicked (how many times).
public ControlPanel(int x) {
JPanel floors = new JPanel();
for (int i = 0; i < x; i++) { // interates through user input and creates that many JButtons.
floorButton[i].add(new JButton("F" + Integer.toString(i))); // adds a button to button array. Sets text to F(floorNo).
floors.add(floorButton[i]); // adds buttons to the floor panel.
floorButton[i].addActionListener(this); // adds action listener to the buttons.
}
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < floorButton.length; i++) {
if (e.getSource() == floorButton[i]) { // checks which button the event occured on.
floorButton[i].setBackground(Color.red); // sets button background to red.
floorButton[i].setText(floorButton[i].getText() + "(1)"); // marks button as clicked.
}
}
}
}
floorButton is not initalised to anything...
public JButton[] floorButton; // I'm null
public ControlPanel(int x) {
//...
for (int i = 0; i < x; i++) { // in
// Still null
floorButton[i].add(new JButton("F" + Integer.toString(i)));
Initalise the array to reflect what you need, also, don't use floorButton[i].add, you don't want to add the button to (what is currently a null element) button, you want to assign it to the position of the array...
public ControlPanel(int x) {
//...
floorButton = new JButton[x];
for (int i = 0; i < x; i++) { // in
floorButton[i] = new JButton("F" + Integer.toString(i));
I'm guessing you'll want to do the same with floorIn...
You have to initialize your floorButton.
floorButton = new JButton [yourCount];
You created the array of JButton, but you didn't create every element in the array. To do this:
Replace this:
floorButton[i].add(new JButton("F" + Integer.toString(i)));
by this:
floorButton[i] = new JButton("F" + Integer.toString(i));

Calculator issue with simple logic

I'm new to Java and have set myself the task of trying to create a simple calculator (and GUI) to advance my understanding and skills of the language.
Take this code:
import java.awt.FlowLayout;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class calc extends JFrame {
public JTextField input;
public JTextField output;
public JPanel Window;
public JButton math_button[] = new JButton[5];
public JButton number_button[] = new JButton[10];
public String[] number_button_name = {"1","2","3","4","5","6","7","8","9","0"};
public String[] name = {"Add", "Mulitply", "Divide", "Subtract", "Equals"};
public JFrame frame = new JFrame();
public JPanel math_panel = new JPanel();
public JPanel number_panel = new JPanel();
public JTextField math_input = new JTextField();
boolean trrgger = false;
thehandler handler = new thehandler();
public void go()
{
for(int b=0; b<number_button.length; b++)
{
number_button[b] = new JButton(number_button_name[b]);
number_button[b].addActionListener(handler);
number_panel.add(number_button[b]);
}
for(int i=0; i<math_button.length;i++)
{
math_button[i] = new JButton(name[i]);
math_button[i].addActionListener(handler);
math_panel.add(math_button[i]);
}
frame.getContentPane().add(BorderLayout.NORTH, math_input);
frame.getContentPane().add(BorderLayout.SOUTH, math_panel);
frame.getContentPane().add(BorderLayout.CENTER, number_panel);
frame.setSize(400,400);
frame.setVisible(true);
}
//Method to handle the math and return the results of whichever 'button' was pressed
static int Math(String button_num, int first_num, int second_num)
{
int total = 0;
if(button_num == "Add")
{
total = first_num + second_num;
}
else if (button_num == "Mulitply") //multiply
{
total = first_num * second_num;
}
else if (button_num == "Divide") //divide
{
total = first_num / second_num;
}
else if (button_num == "Substract") //subtract
{
total = first_num - second_num;
}
else if (button_num == "Equals") //subtract
{
total = total;
}
return total;
}
//Action Events - Code that is triggered once the associated button is clicked
public class thehandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
for (int h = 0; h <math_button.length; h++)
{
if(event.getSource()==math_button[h])
{
int firstn = Integer.parseInt(math_input.getText());
math_input.setText("");
int secondn = Integer.parseInt(math_input.getText());
System.out.println(calc.Math(math_button[h].getText(), firstn, secondn));
}
}
for(int n=0; n<number_button.length; n++)
{
if(event.getSource()==number_button[n])
{
String number_clicked = (number_button[n].getText());
String number = math_input.getText();
math_input.setText(number + number_clicked);
}
}
}
}
}
The idea behind this code is to create a simple GUI and allows the user to input the desired amount of numbers and then press the 'equals' button to display the result. However, as stated I'm having a problem with the logic. I can get the first entered number from the JTextField, clear the text once the first variable has been initialized but this is where the program falls over. The variable 'second_num' is passed to the 'Math' method as blank (which throws up errors) because that's what I tell the ActionEvent to do in order to allow for more fluid use of the program, no user wants to have to keep clearing the input box when using a calculator.
Anybody got any ideas?
Thanks
int firstn = Integer.parseInt(math_input.getText());
math_input.setText("");
int secondn = Integer.parseInt(math_input.getText());
What exactly do you expect the above lines to do? You are getting the text from math_input. Then you set it to an empty string. And by immediately getting the string back you are expecting to get something other than empty string?
The correct approach would be:
First time the handler is called (i.e. a "math" button is clicked) collect the input. Store it somewhere.
Next time this handler will be called you will have your next input. And so on until the user clicks on "=" to evaluate the whole expression.
Advice: If you are new to java, you might find it easier to create a calculator on the command line first. The functionality of a calculator does not require a GUI. In command line collecting the input is more simple. If you get that working then you can proceed to more fancy stuff like Swing
I looked at your code but its sound complicated for me. I recommend you to use IDE like Netbeans. Create swing application. To add two number all you need to do is as follow
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int input_1 = Integer.parseInt(jTextField1.getText());
int input_2 = Integer.parseInt(jTextField2.getText());
jTextField3.setText(String.valueOf((input_1+input_2)));
}
http://i.stack.imgur.com/1G4v7.jpg

drop down list within JTextField

I wnt that when i enter some letter in the textfield then the related items should be picked up from my database and should appear as a drop down list.
For Example:
I typed 'J' in text Field, in my database is having names such as {"Juby','Jaz','Jasmine','Joggy'....}
Theses names should appear as a list. So that i could select one from them.and so on for other leters as well.
Is there any predefined control in awt??
Thnx
Why not just use a JComboBox? By default, when the user types a keystroke in a read-only combobox and an item in the combobox starts with the typed keystroke, the combobox will select that item.
Or you could set the JComboBox to be editable using setEditable(true), and use a KeySelectionManager. The link explains selecting an item in a JComboBox component with multiple keystrokes.
This is a small example implementing what ( i think) you asked for.. the database in this example is a vector of strings.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Answer extends JFrame {
public static final int MAXITEMS = 100;
JPanel panel = new JPanel();
JTextField textField = new JTextField(10);
String[] myDataBase = { "Juby", "Jaz", "Jasmine", "Joggy", "one", "dog","cat", "parot" };
String[] listItems;
JList theList = new JList();
public Answer() {
this.add(panel);
panel.setPreferredSize(new Dimension(500, 300));
panel.add(textField);
panel.add(theList);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ke) {
String compareString = ("" + textField.getText() + ke.getKeyChar());
listItems = new String[MAXITEMS];
if (compareString.trim().length() > 0 ){
int counter = 0;
for (int i = 0; i < myDataBase.length; i++) {
if (counter < MAXITEMS) {
if (myDataBase[i].length() >= compareString.length() &&
myDataBase[i].substring(0, compareString.length()).equalsIgnoreCase(compareString)) {
listItems[counter] = myDataBase[i];
counter++;
}
}
}
}
theList.setListData(listItems);
}
});
}
public static void main(String[] args) {
final Answer answer = new Answer();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
answer.pack();
answer.setVisible(true);
}
});
}
}
One option is to use GlazedLists, as it has some support for auto-completion.

Categories