I am making a Java program, but I've run into a problem.
First, let me show you the code:
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerSendMessage%$%##")){
pSmsgc.setSelected(true);
}else{
pSmsg.setEnabled(false);
}
}
if (DFileLoader.getMethod(pathToSaveAs).size() <= 0){
pSmsg.setEnabled(false);
}
}else{
pSmsg.setEnabled(false);
}
pSmsgc.setFont(fDisp);
pSmsgc.setBounds(new Rectangle(50, 135, 140, 30));
pSmsg.setBounds(new Rectangle(175, 135, 150, 30));
pSmsgc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (pSmsgc.isSelected()) pSmsg.setEnabled(true);
else pSmsg.setEnabled(false);
}
});
pane.add(pSmsgc);
if (file.exists()){
for (String s : DFileLoader.getMethod(pathToSaveAs)){
if (s.startsWith("playerSendMessage%$%##")){
String[] d = s.split("%$%##");
String text;
if (d.length <= 1) text = "";
else text = d[1];
pSmsg.setText(text);
}
}
}
pane.add(pSmsg);
Here are some things to know about this:
When I use "getMethod(path)", its just returning a String List (List) which includes each line of the TXT file.
pSmsgc is a JCheckBox and pSmsg is a JTextField.
I have it so when the box is not checked, the text field is grayed out, which works fine.
If the file has a line that starts with "playerSendMessage%$%##", the box will be checked, which works.
The thing that isn't working is where it sets the text field's text to the second substring of that line.
For example, the file's line could be "playerSendMessage%$%##Hello!". This would cause the box to be checked, and the field to says "Hello!"
Everything works except for the part where the field says the text.
It might be just a simple thing that I am overlooking, or maybe not. Can anyone please help?
Your file's line name contains the character '$' which means end of a line on RegExp patterns.
So the solution would be to escaping with \\ the character in conflict with RegExp syntax like this:
String[] d = s.split("%\\$%##");
Related
can't solve this problem.
I want to retrieve the text that I write on my textfield with keyTyped and put int on a String. But If I do it, it gives me a blank String. What can I do?
textField_9.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e){
xw = textField_9.getText(); //should retrieve my input
}
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if((!(Character.isDigit(c)) && (c!='.'))){
e.consume();
}
System.out.println(xw); //gives nothing ("") not null
numero = e.getKeyChar();
String fileName = defaultx+"\\"+"Contratti"+"\\"+textField_7.getText()+"\\"+"lista"+tipo;
Scanner scanner;
try {
scanner = new Scanner(new File(fileName));
scanner.useDelimiter(":");
while(scanner.hasNext()){
num = scanner.next();
System.out.println("Numero = "+num+"\t"+xw); //debug
dat = scanner.nextLine().replaceAll(":", "");
if(num == xw){
try(Scanner scanner1 = new Scanner(dat)){
scanner1.useDelimiter(":");
giorno = scanner1.next();
meset = scanner1.next();
anno = scanner1.next();
System.out.println(giorno+"-"+meset+"-"+anno); //debug
}catch(NoSuchElementException ex){
}
}else{
System.out.println("Dato non trovato");
}
}
scanner.close();
} catch (FileNotFoundException e1) {
} catch(NoSuchElementException e1){
}
}
});
Example
I write into my JTextField the number "5" , xw should be then "5" but instead it will be ""
Basically what I'm trying to do is to read user's input, this input (that's a number) will be searched in a .txt file that contains a list of number and dates. example : 1st line of the .txt file is "1:1-01-2017" the second line is 2:8-01-2017" the third line is "3:15:01:2017 etc..
Read this data in once not with each key press as you're trying to do above, perhaps doing this in the class's constructor. Then store the data in a searchable collection, perhaps an array list of custom class.
so what I want to do is to search in this .txt file that number before ":" and when it finds it ,write in another textfield the date. example. user write in textfield1 "3", the program will search in the .txt file the number 3 that is before the ":" and when it find it , will write the date into another textfield.
The custom class that holds the text file's data should hold the separate numbers in their own fields, and again, search the ArrayList of these objects when needed.
Also:
do not add a KeyListener to a JTextField as this can prevent the JTextField from behaving correctly (as you're finding out).
We sometimes add a DocumentListener or a DocumentFilter to the JTextField's Document for similar behaviors...
But in your case I wouldn't do either. Instead add an ActionListener to the JTextField, a listener which is activated when the ENTER key is pressed, and search the ArrayList from within this listener.
You should almost never have empty catch blocks as we see in your code above. At least print out the stacktrace, as you could very well be having problems from exceptions being thrown completely without your knowledge since your code ignores them.
I've been for a while searching through here and other Java forums. Also googling it, but I haven't found anything that matches my expectations (a line break, basically). I've achieved this:
public final void messageRoom (String message, Boolean bold, Color color) {
StyledDocument document = new DefaultStyledDocument();
SimpleAttributeSet attributes = new SimpleAttributeSet();
if(bold) {
attributes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
}
attributes.addAttribute(StyleConstants.CharacterConstants.Foreground, color);
try {
document.insertString(document.getLength(), message, attributes);
} catch (BadLocationException ex) {
System.out.println("ex");
}
chatArea.setStyledDocument(document);
}
That allows me to send messages to a chat room I'm creating, how can I make the line break to go to the next line?
Thank you all! (Similar but not equal posts: First post and The second one)
how can I make the line break to go to the next line?
Maybe I don't understand the question. The text in a text pane will "wrap" automatically.
If you are attempting to start each message on a new line then you just use "\n" as the new line character.
Maybe something like:
document.insertString(document.getLength(), "\n" + message, attributes);
Of course you wouldn't want to add a new line for the first message.
public final void messageRoom (String message, Boolean bold, Color color)
Don't use an Object when a primitive variable will do. Just use a "Boolean" parameter.
I am trying to replace a word one occurrence at a time. I have been looking through other answers here, but I think what I have coded so far would be much simpler. I want to replace a word that a user selects with another word that the user also selects. I will have two text fields and a button and every time the user clicks the button, we will get the text out of both text fields and replace the word that needs to be replaced in the text area. My issue is that when the replace button is clicked, any other text that is in the text area is deleted and we are left only with the word that is doing the replacing. I know my issue is because I am setting the text of the text area to just that one word, but I do not know how to fix it. Here is my code: Any help is appreciated.
replaceButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String findText = textField.getText();
String replaceText = textField2.getText();
String text = textArea.getText();
text += text.replaceFirst(findText, replaceText);
textArea.setText(replaceText);
}
});
Like you said. You are setting the text in textArea to the text you want to replace. So set the text in textArea to the updated text returned from text.replaceFirst(findText, replaceText). Also you don't need to concatenate the result.
Try this.
replaceButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//the text you want to replace
String findText = textField.getText();
//what you want to replace it with
String replaceText = textField2.getText();
//all the text in the text area
String text = textArea.getText();
//replace first occurrence of "findText" with "replaceText"
//returns the altered string
text = text.replaceFirst(findText, replaceText);
//set text in textArea to newly updated text
textArea.setText(text);
}
});
To make sure I understand you correctly you want something like this.
Original text: I like cats, cats are cool.
find: cats; replace: dogs.
First click output: I like dogs, cats are cool.
Second click output: I like dogs, dogs are cool.
I'm trying to programatically convert a Java source file into an HTML file using PrintWriter to write to a seperate .html file
Example source file may look like this.
HelloWorld.java:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
while (true) {
System.out.println("Hello World!");
// Disregard this ridiculous example
}
}
}
All My printing works fine except I have a problem with indentation. Everyting is aligned left.
HelloWorld.html (as seen in browser):
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
while (true) {
System.out.println("Hello World!");
// Disregard this ridiculous example
}
}
}
Program Source Code Snippet: I want this program to determine for me, which line in the java source code should get indentation when it is being converted to HTML. I don't want to do it manually, because then I'd have to write a different program for every source file
PrintWriter output = new PrintWriter(newFile);
output.print("<!DOCTYPE html><html><head>"
+ "<style>"
+ ".keyword { font-weight: bold; color: blue}"
+ "</style></head><body>");
while (input.hasNextLine()) {
String line = input.nextLine();
String[] tokens = line.split(" ");
for (int i = 0; i < tokens.length; i++) {
if (keywordSet.contains(tokens[i])) {
// Gives Java keyword bold blue font
output.print("<span class=\"keyword\">");
output.print(tokens[i] + " ");
output.print("</span>");
} else {
output.print(tokens[i] + " ");
}
}
output.print("<br/>");
}
output.print("</body><html>");
output.close();
Note: The reason I split() each line is because certain keywords that may be in that line, are doing to be highlighted in the html file, which I do with a <span>, as noted in my code
In the program source code, I obviously don't have any indenting implementation, so I know why I don't have indentation in the html file. I really don't know how to go about implementing this.
How do I determine which line gets indentation, and how much indentation?
EDIT:
My Guess: Determine how much whitespace is in the line before splitting it, save the into a variable, then print those spaces in for form of  's before I print anything else in the line. But how do I determine how much whitespace is at the beginning of the line?
You can use a CSS class with white-space: pre or pre-line or pre-wrap.
You can wrap each line in a <p> with a calculated margin-left. It could be a multiple of 10px, for example. This would let you also change brace styles.
Basically, you'll have to keep a variable, indentLevel. Increment it for each { not in a string or a comment, and decrement it for each } not in a string or a comment. Indent each line, say 10px times the indent level. Test; do you want continuation lines indented more?
Use pre tag.
The tag defines preformatted text.
Text in a element is displayed in a fixed-width font (usually
Courier), and it preserves both spaces and line breaks.
You don't need to dermine which line needs to be indented because pre tag preserves ALL spaces, carriage returns and line feeds 'as-is' from the original HTML source code.
If you check the HTML that is rendered in StackOverflow in something marked as code you will see that it uses this tag.
Maybe it's better to first prepare String with your source code adding needed HTML, and replacing spaces with . This can be done with String.replace() method - iterate over you keywordSet and replace all keywords with its wrapped versions. Then you will able to write full string into your stream.
I figure out what I was trying to accomplish
...
int whiteSpace = 0;
while (whiteSpace < line.length() && Character.isWhitespace(line.charAt(j))) {
whiteSpace++;
}
String[] tokens = line.split(" ");
// Print white space
for (int i = 0; i < whiteSpace; i++) {
output.print(" ");
}
...
So I'm writing a program for this brand new, never heard of game called hangman (ha.) and I'm having a really hard time writing a loop that will give me the results I want. I'm stuck at the point where a correct letter has been guessed (via button press) and revealing the correct letters in the line of dashes that represent the hidden word. Now when I run this loop, my tester popup still pops up "Match!---" or however many dashes the current secret word has. It's literally as if the replaceAll doesn't actually replace it! I've been stumped on this for hours now with no break so it would not surprise me if it is something extremely obvious I am missing.
JButton btnA = new JButton("A\n");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String letter = "a";
char ch = 'a';
if (go.getWordInQuestion().contains(letter)) {
for(int i = 0; i<go.getWordInQuestion().length(); i++) {
//Replace dashes with correctly guessed letter
if(go.getWordInQuestion().charAt(i)== 0)
go.getGuessLength().replaceAll("[^" + letter + "]", "_").charAt(i);
}
//check to see what the new value of the "hidden word" getGuessLength looks like
JOptionPane.showMessageDialog(null, "Match! " + go.getGuessLength());
txtGuess.setText("" + go.getGuessLength());
} else
JOptionPane.showMessageDialog(null,"No Match :(");
}
});
*****EDIT*******
Ok so I've made progress (I think). I have now written a loop that changes the dashes to letters!! The only problem? it changes all of them. -___- So now when I press button A, if theres a match, instead of ---, it will read aaa. I definitely realize this issue is probably extremely elementary but when it comes to java, I'm a slow learner! I appreciate all the positive and informative feedback!
JButton btnA = new JButton("A\n");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String letter = "a";
StringBuilder guessA = new StringBuilder('a');
for(int i = 0; i<go.getGuessLength().length();i++) {
if(go.getWordInQuestion().charAt(i)=='a') {
String partialWord = go.getGuessLength().replace("-", letter);
txtGuess.setText(partialWord);
JOptionPane.showMessageDialog(null,"Match! " + partialWord);
}
}
}
});
*****EDIT TWO******
Alright! I think I have finally resolved the issue thanks to your guys help! When a user presses the 'A' button, and if there is an A in the hidden word, it is now successfully replaced with a dash! woohoo!
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String letter = "a";
StringBuilder guessA = new StringBuilder(go.getGuessLength());
if(go.getWordInQuestion().contains(letter)) {
for(int i = 0; i<go.getGuessLength().length();i++) {
if(go.getWordInQuestion().charAt(i)=='a') {
StringBuilder partialWord = guessA.replace(i,i+1, letter);
txtGuess.setText(guessA.toString());
JOptionPane.showMessageDialog(null,"Match! " + partialWord);
}
}
} else
JOptionPane.showMessageDialog(null, "Incorrect");
}
});
This line of code doesn't do anything:
go.getGuessLength().replaceAll("[^" + letter + "]", "_").charAt(i);
replaceAll() doesn't modify the String (Strings are immutable in Java). It returns a new String where the characters have been replaced. You're calling charAt(i) on this new String, and don't do anything with this char.
replaceAll() uses a regex as its target for replacement. You probably just want replace(), which still replaces all matches but uses plain characters for its target.
That said, the simplest solution is just one line of code that uses replaceAll() and turns the guessed letters into a regex that matches all other letters.
Given:
String word = "foo"; // the word people are trying to guess
String guesses = "one"; // the characters guessed so far
Here's the one line that will produce the required output:
String display = word.replaceAll("[^" + guesses + "]", "-");
When executed with the above values, display will be -oo.