I am making a little Sudoku game with a GUI and use a MaskFormatter for the JFormattedTextFields:
formatter = new MaskFormatter(s);
formatter.setValidCharacters("123456789");
But my problem is that when the window opens and i click into one of those fields, it is not possible to type something,
it only works on second try, namely when I click into another field and then back to the first one.
Is it like it has to lose focus first to activate?
If some of my code is necessary please let me know.
Here's what it looks like
EDIT: The problem was here:
if (guessMatrix[i][j] == 0) {
tfM[j][i].setBackground(Color.yellow);
tfM[j][i].setText("");
Without the setText("") it works perfectly fine.
I think you have problem in create object of MaskFormatter.
you create object with pattern of masking and then after set valid characters.
MaskFormatter formatter = new MaskFormatter("#");
formatter.setValidCharacters("123456789");
JFormattedTextField txt = new JFormattedTextField(formatter);
This work perfectly, when you click on textfield and type any number(1-9 only) it allow but you type any non-number then not allow.
Thanks,
Jignesh Gothadiya
Related
I am working on a school coding project, which involves using the JFugue library in Java. However, I am having significant difficulty saving loaded and edited patterns to a file. So far, I have tried both the player.saveMidi (which is not recognized) and MidiFileManager.savePatternToMidi functions, but the edits do not save.
Here is a snippet of the aforementioned code:
Pattern pattern = new Pattern(MidiFileManager.loadPatternFromMidi(new File(filePath.getText())));
TextField midiData = new TextField(pattern.toString());
midiData.setFont(Font.font(14));
pattern = new Pattern(midiData.getText());
Button save = new Button("Save Edits");
Pattern finalPattern = pattern;
save.setOnAction(e -> {
try {
MidiFileManager.savePatternToMidi(finalPattern, new File(filePath.getText()));
Load.playAndEdit(filePath);
} catch (Exception ex) {
ex.printStackTrace();
}
});
Any help would certainly be appreciated!
Although your suspicion is that this is an issue with JFugue, the underlying issue is in the JavaFX pieces of the code.
The main issue is that the way the code is written, it looks like the expectation is that the TextField will be displayed, the user will make a change, and the code will remember that change in "pattern = new Pattern(midiData.getText())". That's not how the JavaFX TextField works. UI elements are not sequential like this; instead, they work with actions (or in JavaFX, you can "bind" the value of a UI component with a data element). If you get the text from the TextField in the action that triggers when the user presses the Save button, you will have the most recent data from the text field. As the code is written, the user's change is never placed into a variable.
Two other notes:
In your first line, MidiFileManager.loadPatternFromMidi returns a Pattern, so you don't need to put it into a "new Pattern()".
There is no need to say "Pattern finalPattern = pattern". That just creates a new variable that points to the same data as the existing variable. You can just save "pattern", if it has the information you expect from the text field (but again, this isn't the right place to say it, so it won't have the information that you're expecting).
One way to test that this is not a JFugue issue is to create a simple program that does, for example:
Pattern pattern = MidiFileManager.loadPatternFromMidi(new File(filePath.getText()));
pattern.add(" C D E");
MidiFileManager.savePatternToMidi(pattern, new File(filePath.getText()));
Then you would see that the resulting pattern has three new notes added to the end.
I am working on a project. I want a user string (no trouble with that) to be typed out by java. Is that possible and if yes, then how?
Thank you!
I don't blame for the down votes
You can't just blindly make the program type it out on the keyboard as it is not getting displayed anywhere. You have to either use some third-party module that I have no idea about that presses keys for you, or you should actually store the string somewhere, some sort of text box. If you are using a java swing to make a GUI app, then simply create a JTextBox and set the text to your string like this:
JTextbox textbox = new JTextbox();
textbox.setText("your string goes here");
I will do my best to explain-- I am trying to make a choose-your-own-adventure type game while using a TextField and a TextArea, where what is written in the TextField is appended into the TextArea (this I know how to do via ActionListener).
However, I need to have the TextArea start with a pre-written 'intro', which asks the user at the end if they want to continue or not. Therefore, I need it to be able to scan the user's response ('yes' or 'no') and choose the appropriate selection of pre-written text to follow.
I don't want to overwrite what is already in the TextArea, I want to add to it. I suppose what I'm confused about it how I'm supposed to lay out the entire file so that it functions properly, because the different choices for the adventure span different methods. Having
"String text = textField.getText();" only within the actionPerformed method means I can't use 'text' elsewhere, but moving that line up with my other variables tells me it can't reference the field before it's defined.
I am fairly new to Java and am working on this as a project for a non-programming school course. I've been through many iterations thus far and this is what seems to be my final attempt, as I've remade it repeatedly and don't have much time left. :(
Your questions/comments and my attempts to answer:
I am trying to make a choose-your-own-adventure type game while using a TextField and a TextArea, where what is written in the TextField is appended into the TextArea (this I know how to do via ActionListener).
As per my comment, be sure to create a Swing GUI which would use a JTextField and a JTextArea. You would then add your java.awt.event.ActionListener to the JTextArea, and the ActionListener would respond whenever the user pressed <ENTER> within the JTextField.
However, I need to have the TextArea start with a pre-written 'intro', which asks the user at the end if they want to continue or not. Therefore, I need it to be able to scan the user's response ('yes' or 'no') and choose the appropriate selection of pre-written text to follow.
This can be done easily, but sounds as if you may be trying to shoe-horn a linear console type program into a GUI. If so, consider reconsidering your program design since what works best for one often doesn't work well for another. If you do re-write, then you should consider redoing most including your program flow, but excepting perhaps the "model" portion of your previous program, the "business logic" that underlies everything.
I don't want to overwrite what is already in the TextArea, I want to add to it. I suppose what I'm confused about it how I'm supposed to lay out the entire file so that it functions properly, because the different choices for the adventure span different methods. Having "String text = textField.getText();" only within the actionPerformed method means I can't use 'text' elsewhere, but moving that line up with my other variables tells me it can't reference the field before it's defined.
Again as per comments a JTextArea has an append(String text) method that will add new text to existing text that is already displayed in your JText Area. So on that note, your ActionListener's actionPerformed method could be very simple and look something like:
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
textArea.append(text):
}
Although you may need to add line feeds, "\n" either before and/or after the text you are going to append.
My question is the inverse of this one: Is there a way to only have the OK button in a JOptionPane showInputDialog (and no CANCEL button)?
One solution to that was (if I read correctly) to add an arbitrary JPanel, in that instance a label. My problem is that I need a JComboBox object in the message window, and (in the same way that solved Coffee_Table's problem) having the JComboBox seemingly removes the cancel button. It doesn't matter if I replace YES_NO_CANCEL_OPTION with OK_CANCEL_OPTION or QUESTION_MESSAGE.
I'm still at the mindless-copying stage of learning about the JOptionPane family, so I presume the solution is obvious and I just don't know it because I haven't seen any specific examples to mindlessly copy. (Which also means that once I learn how to add a cancel button, I'll need to work on how to access whether the user hit it. EDIT: And I'm half-sure how I'd do it, so you don't need to answer it if you don't want to.)
public static void main(String[] args) {
int numCh1 = 1;
String[] moves = {"rock","paper","scissors"};
JComboBox<?> optionList = new JComboBox<Object>(moves);
JOptionPane.showMessageDialog(
null,
optionList,
"Player One: Choose a Move",
JOptionPane.YES_NO_CANCEL_OPTION
);
numCh1 = optionList.getSelectedIndex();
System.out.println(moves[numCh1]);
}
Note: The combo box is non-negotiable (as opposed to, say, three buttons) because my actual project is to simulate rps101; I just figured you didn't need to see all 100 moves (or anything else irrelevant to this question).
You're using the showMessageDialog() method, which shows just that: a message. It doesn't have a cancel option. For that, use one of the other methods.
In fact, that last parameter isn't even valid. It's not looking for an option type like you provided, it's looking for a message type (ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE).
As always, the API is your best friend: http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html
In my application I have a JTextField that will only allow the user to fill it with input formatted in a certain way. I have a method that checks if input into the field is valid and if not it displays a dialog. After this occurs I would like the focus to return to the text field so that the user can correct there mistake and type in the appropriately formatted input. I tried to do this by having the JTextField call requestFocus() on itself but this seems to only half work. The JTextField displays the flashing cursor but I cannot actually type in any text until I click on the text field again. Is there another method I need to call? I could not find anything else in the documentation.
It's not exactly the solution you asked for, but you might want to look at javax.swing.InputVerifier. This object allows you to verify the input to a field and prevent taking focus away from it if the format isn't right. I don't think it would allow you to put up a dialog explaining the error (though it might - try it) but it would certainly allow you to put a message in a 'message area'.
What you do is set an InputVerifier on the JComponent, have it test the contents for validity; if it isn't right then the JComponent won't release focus (and can write an error message).