How to set an array in Jtextfield using netbeans - java

I am creating a small application . In this application I have 5 words. I have one JtextField and JButton.The name of JtextField is set as name1 and JButton name set as next.
I want to set a default word in name1 from 1st word of string array ( from this code I am giving one example is need to see in JtextField is as "me") when application run I want to see the word from String array before the the next button click. how I can set the data to name1?
code is as follows:
String s[]={"me","and","my","friends","are"};
int i=0;
private void nextActionPerformed(java.awt.event.ActionEvent evt) {
if(i>=s.length)
i=0;
name1.setText(s[i]);
i++;
}

Call the method after you created your fields with null as argument as you don't use the argument.
nextActionPerformed(null);
This will simulate that the button is pressed when the program starts up.

Assuming you have a button which has action Listener attached. If not then it should be something like below:
nextButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
nextActionPerformed(e);
// Or move your code here from nextActionPerformed(e)
}
});
//And you can also initialize your text filed with first value of array:
textField.setText(s[0]);

Related

Changing ActionListener to append StringBuilder

Within two statements that have drastically shortened my code I need to add a statement that adds the text of a JButton to a StringBuilder. The ActionListener statement exists to disable the JButtons when clicked (a nice aesthetic), but I want to include if possible the ability to append the StringBuilder within the ActionListener as well. The following is the two parts of this code.
theModel.randomLetters();
ActionListener disableButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
theModel.currentWord.append((JButton)event.getSource());
((JButton)event.getSource()).setEnabled(false);
}
};
for (int i = 0; i < 16; i++) {
JButton dice = new JButton(theModel.letters.get(i));
dice.addActionListener(disableButton);
boggleGrid.add(dice);
}
The .addActionListener(disableButton) adds the above ActionListener to each button when it is produced by the for loop. However,
theModel.currentWord.append((JButton)event.getSource());
is what I thought would properly append the StringBuilder "currentWord" with whatever value the clicked button holds (hence "((JButton)event.getSource())"). There are no errors per say but I have written separate lines of code in my main class to test whether there are any changes to the StringBuilder when any buttons are clicked. There isn't.
Where and what do I need to do to properly add the value of the clicked JButton to currentWord?
Using (JButton)event.getSource() will cause the StringBuilder to invoke the objects toString method. This isn't what you want, instead, either use the JButton's text property or the ActionEvent's actionCommand property, for example...
theModel.currentWord.append(((JButton)event.getSource()).getText());
or
theModel.currentWord.append(event.getActionCommand());
instead
Unless you specify the JButton's actionCommand yourself, it will use the buttons text as the actionCommand

Having Trouble in Callin the ArrayList

So I am making a java program that quizzes students on the capital of the USA states.(I am fairly new to JAVA) Okay guys so here is part of my program:
class SetUpButtonActionListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
for(int i=0; i < state.size(); i++)
{
question = (String)(state.get(i));
//i++;
countryName.setText(question);
}
}
}
The problem is when I am trying to call the ArrayList one by one in the SetUpButtonActionListener class. It runs fine, but when I click on the New Problem button its supposed to show each one state and ask the user for the capital(haven't gotten to this part yet). However, when I click the button it doesn't show up with anything. I am not really to sure what I am doing wrong. Any help would be awesome!
state is and will remain empty until you call stateName(). This explain the observed behavior.
You probably want to add a call to stateName() at the beginning of your constructor.
you should call filling method of your list in the constructor
public QuizPanel()
{
stateName()
setUpButton = new JButton("New problem!");
add(setUpButton);
setUpButton.addActionListener(new SetUpButtonActionListener());
...
}
First of all, you need to call stateName() to fill the array.
Second, this way you did, every time the button is clicked, the method actionPerformed is called, and the loop runs with all the values of the array, always finishing getting the last value.
What you need is to maintain a value pointing to the next value of the array, so this way, every time you click the button, only the next item is got.
class SetUpButtonActionListener implements ActionListener{
int currentIndex = 0;
public void actionPerformed(ActionEvent e) {
//verify if the index is inside the array (reseting it if not)
//get the value
//increase the index
}
}

Problems with KeyEvent

I have a panel just with a Jtextfield that only accept numbers. So, when I press enter will load a user profile. this is just to see his profile.
What I want: When I press ENTER again all the profile will be cleared, and when I press the numbers and press ENTER again and load the profile again and again...
My problem: I pressed enter and the profile is cleared (Ok all fine), but when I enter the number and press the ENTER, The numbers are cleared and nothing happens, it is like a loop in matriculaTxt.addKeyListener(new KeyAdapter() { ... }
Sorry for my bad English.
private void matriculaTxtActionPerformed(java.awt.event.ActionEvent evt)
{
String matricula = matriculaTxt.getText().trim();
if (!matricula.matches("[0-9]+")) {
matriculaTxt.setText("");
} else {
fc = new FrequenciaController();
matriculaTxt.setEditable(false);
matriculaTxt.requestFocus();
fc.checkinManual(Integer.parseInt(matricula));
}
// the problem is here.
matriculaTxt.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
nomeTxt.setText("");
statusTxt.setText("");
imageLb.setIcon(null);
acessoLabel.setText("");
matriculaTxt.setText("");
observacaoTxt.setText("");
System.err.println("ENTER");
PendenciasTableModel ptm = new PendenciasTableModel();// vazio
pendenciasTabela.setModel(ptm);
matriculaTxt.setEditable(true);
matriculaTxt.requestFocus();
}
}
});
}
What I wanted to do was simple. The user types in the text field their numbers, pressing ENTER: their data are loaded. requestFocus() into the text field and it will not be editable anymore, because when I press Enter again the field will be editable but everything will be deleted, and so on.
First off, you should never use a KeyListener for this sort of thing. Consider instead using either a JFormattedTextField or using a DocumentFilter to prevent non-numeric entry. Next, you should use an ActionLIstener to have the JTextField accept and react to the user's pressing the Enter key.
Edit
You state:
my exact requirements is, when i press ENTER again all data will be cleaned for a new data be inserted.
Why not simply have in your JTextField's ActionLIstener:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText();
// do what you want with text here
// clear the text
textComp.setText("");
}
Again, you should not use a KeyListener for any of this stuff.
Edit 2
If you want a multi-state action listener, one that reacts differently depending on the state of the program, then give it some if blocks to allow it to react to the state of the JTextField. If the field is empty, do one thing, if it has numbers, do another, if it has text, show a warning and clear it:
#Override
public void actionPerformed(ActionEvent e) {
// get the text
JTextComponent textComp = (JTextComponent) e.getSource();
String text = textComp.getText().trim(); // trim it to rid it of white space
if (text.isEmpty()) {
// code to show a profile
return; // to exit this method
}
// if we're here, the field is not empty
if (!text.matches("[0-9]+")) {
// show a warning message here
} else {
// numeric only data present
// do action for this state
}
// clear the text
textComp.setText("");
}
The key again is to not use a KeyListener, but rather to "listen" for the enter key press with the ActionListener only, but to react differently depending on the state of the program, here likely being depending on what content is present in the JTextField.
I think that your problem that the KeyListener it'll not trigger, it will not execute the code inside it, because whenever you press ENTER it will trigger the matriculaTxtActionPerformed then declared the KeyLister, so the ENTER will effect it.

How to add set of integers in a JTextArea

I have added set of integers to a JTextArea for each button click.
what exactly I want is that I want to add all the integers and display in a separate JTextArea,Also I want to ask whether we can access the value of a variable within an action listener outside the action listener.
Here is the code:
private ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals(t.getText()))
{
onec=one.calone(n);
td.append(Double.toString(onec));
td.append("\n");
}
res=Integer.parseInt(td.getText());
}
};
When the user presses button 't' It will keep on adding the integer 'onec' to
textarea 'td' using append method.And I have stored the result from the action
listener into a variable 'res' of double datatype.
private ActionListener listener2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals(tot.getText()))
{
totd.setText(Double.toString(res));
}
}
};
When the user clicks the button 'tot',It should add all the integers in the
textarea 'td' and display it in the textarea 'totd'.
This code is not working.
Please help me this is the last part of my project.
As I don't know what is not working - it would of been good if you explained more clearly - my guess is...
Instead of Double.toString(onec)
Use String.valueOf(onec)
EDIT: If this is not the case, please elaborate on what your problem is, and a fuller code listing.
converting the contents of the textArea to double does not calculate sum. Try looping throught the first textArea reading each value while calculating the sum

Comparing components via setName() .

I am coding an image puzzle game and one part of the code is to compare the pieces the user has selected to the pieces of the correct image.
Each image piece is already added to a JButton as an ImageIcon.
An identifier is required to differentiate each image piece apart and also for comparision.
I am setting a setName() for each JButton created as the identifier.
The comparison starts when the user releases the mouse after he drags the puzzle pieces from the original 3x3 grid where the shuffled pieces are to the other 3x grid for matching.
I have problems removing the error from the comparison if statement.
I got the comparison idea from this SO thread - link
private JButton[] button = new JButton[9];
private JButton[] waa = new JButton[9];
private String id;
private int cc;
private String id2;
private int cc2;
// setName for each of the 9 buttons in the original 3x3 grid being created
// which stores the shuffled puzzle pieces
for(int a=0; a<9; a++){
button[a] = new JButton(new ImageIcon());
id += Integer.toString(++cc);
button[a].setName(id);
}
// setName for each of the 9 buttons in the other 3x3 grid
// where the images will be dragged to by the user
for(int b=0; b<9; b++){
waa[b] = new JButton();
id2 += Integer.toString(++cc2);
waa[b].setName(id2);
}
// check if puzzle pieces are matched in the correct place
// compare name of original 'button' array button with the name of 'waa' array buttons
button[a].addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent m){
if(m.getbutton().getName().equals (waa.getName())){
}
else{
JOptionPane.showMessageDialog(null,"Wrong! Try Again.");
}
}
}
In your mouseReleased event m.getButton() is returning the mouse button that was clicked. You'll want to do something more like this that will get you closer:
if (m.getComponent().getName().equals(waa.getName())) {
m.getComponent() returns the Component object (your JButton) that the event was fired from. From there you can do the comparison with the getName approach you are using.
There's an additional issue in that your waa variable is an array. I'm not sure how you want to compare them, whether running through the arrays and making sure the index and names match, but that's an additional issue you need to look into.
JButton uses an ActionListener to trigger notifications back to your program to indicate when it's been triggered. This allows the button to respond to different types of event, including the mouse, keyboard and program triggers.
As apart of the action API, you can supply an action command for each button. See JButton#setActionCommand
Basically you would integrate it in a simular way to your mouse listener...
public void actio Performed(ActionEvent evt) {
if (command.equals(evt.getActionCommand()) {...}
}
Depending on your requirements, it might even be easier to use the Action API
The problem you are actually having is waa is an array, therefore, it doesn't have a getName method. I'm also unclear as to why you have two arrays of buttons?

Categories

Resources