JTextField. Find and highlight the word in a JTextArea - java

I wrote a code to find and highlight a word in a JTextArea and I'm hitting an issue and I'm too tired and with an headache to see my mistake.
I have a search bar(TextField) where I can enter a word and the word gets highlighter in my TextArea. Problem is, after I press my "ENTER" key, the TextField gets deselected and I have to click it again to find the next word. What am I missing?
findfieldpage1 = new JTextField();
findfieldpage1.setBounds(37, 295, 63, 24);
gtapage1.add(findfieldpage1);
findfieldpage1.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode();
if(code == KeyEvent.VK_ENTER){
String find = findfieldpage1.getText().toLowerCase();
textpage1.requestFocusInWindow();
if (find != null && find.length() > 0) {
Document document = textpage1.getDocument();
int findLength = find.length();
try {
boolean found = false;
if (pos + findLength > document.getLength()) {
pos = 0;
}
while (pos + findLength <= document.getLength()) {
String match = document.getText(pos, findLength).toLowerCase();
if (match.equals(find)) {
found = true;
break;
}
pos++;
}
if (found) {
Rectangle viewRect = textpage1.modelToView(pos);
textpage1.scrollRectToVisible(viewRect);
textpage1.setCaretPosition(pos + findLength);
textpage1.moveCaretPosition(pos);
pos += findLength;
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
}
});

Youre not transfering the focus back to the text field after the search is done
Add at the end: Jtextfield.requestfocus()

Line 10 in your method is textpage1.requestFocusInWindow();, that's why it loses focus, because you're transferring it to the JTextArea.

In the end, to avoid the hassle. I added a JButton and changed the keyPressed to an actionPerformed. So everytime I click that button, it finds and highlights me the string I enter in the TextField. Thank you for your help guys, I appreciate it.

Add one more listener to textarea. After the focus is shifted to text area, this way it'll remain in textarea and the event (enter key press) etc will make the search happen.
/search filed begins/
JTextField findtext = new JTextField();
//findtext.setBounds(112,549, 63, 24);
frame.add(findtext,BorderLayout.BEFORE_FIRST_LINE);
findtext.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode();
if(code == KeyEvent.VK_ENTER){
String find = findtext.getText().toLowerCase();
tarea.requestFocusInWindow();
//findtext.requestFocus();
//findtext.requestFocusInWindow();
if (find != null && find.length()> 0) {
Document document = tarea.getDocument();
int findLength = find.length();
try {
//int pos=0;
boolean found = false;
if (pos + findLength > document.getLength()) {
pos = 0;
}
while (pos + findLength <= document.getLength()) {
String match = document.getText(pos, findLength).toLowerCase();
if (match.equals(find)) {
found = true;
break;
}
pos++;
}
if (found) {
Rectangle viewRect = tarea.modelToView(pos);
tarea.scrollRectToVisible(viewRect);
tarea.setCaretPosition(pos + findLength);
tarea.moveCaretPosition(pos);
pos += findLength;
//Thread.sleep(2000);
// findtext.requestFocusInWindow();
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}//findtext.requestFocusInWindow();
}
});
/*control back to textarea*/
tarea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int code = evt.getKeyCode();
if(code == KeyEvent.VK_ENTER){
String find = findtext.getText().toLowerCase();
tarea.requestFocusInWindow();
//findtext.requestFocus();
//findtext.requestFocusInWindow();
if (find != null && find.length()> 0) {
Document document = tarea.getDocument();
int findLength = find.length();
try {
//int pos=0;
boolean found = false;
if (pos + findLength > document.getLength()) {
pos = 0;
}
while (pos + findLength <= document.getLength()) {
String match = document.getText(pos, findLength).toLowerCase();
if (match.equals(find)) {
found = true;
break;
}
pos++;
}
if (found) {
Rectangle viewRect = tarea.modelToView(pos);
tarea.scrollRectToVisible(viewRect);
tarea.setCaretPosition(pos + findLength);
tarea.moveCaretPosition(pos);
pos += findLength;
//Thread.sleep(2000);
// findtext.requestFocusInWindow();
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}//findtext.requestFocusInWindow();
}
});
/*search filed ends*/

Related

my buttons for java gui don't seem to work, can someone help :(

Ive been trying to make buttons from checking if a factor is prime or not, the image below should be the output but im stuck trying to make the check button work.
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num = 10, i = 2;
if(e.getSource() == btnCheck) {
num=Integer.parseInt(userInput.getText().trim());
boolean flag = false;
while (i <= num / 2) {
if (num % i == 0) {
flag = true;
break;
}
++i;
}
if (!flag)
{subCenPanel.add(isPrime);}
else
{subCenPanel.add(notPrime);}
}
}
});
}
}
\\HERES THE PROJECT I NEED TO DO

Snap Box to Grid

I'm creating a small application where a user can take a Box and arrange it on a Pallet. I've managed to get it working using a 50x100 Box and making it snap to a grid by rounding the mouse position to the closest 50 value.
The problem is that when I use an odd sized Box, e.g. 50x110, the boxes will overlap or have gaps, since I am forcing them to move to the closest 50 value. If I increase this value I get gaps between the boxes and if I make it too small, it becomes hard for a user to align the boxes so there is no gap between them
I was wondering if anyone had anyway to approach this problem of getting the boxes to snap/align themselves with each other regardless of the size and ratio?
Here is part of the code that generates and places the buttons onto the pallet, explanation of the missing functions at the bottom
int package_width = 60;
int package_height = 100;
int snap_size = 50; //snap everything into 5 pixel limits
int count = 0;
int pallet_width = 400;
int pallet_height = 400;
JButton package_left = new JButton("<");
package_left.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Selector.selected = "<";
}
});
JPanel pallet = new JPanel();
pallet.setLayout(null);
pallet.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(Selector.selected != "" && Selector.selected != null) {
Point position = e.getPoint();
JButton pack = new JButton(Selector.selected + Selector.count);
int x_pos = -1;
int y_pos = -1;
int pack_height = -1;
int pack_width = -1;
if(Selector.selected == "<" || Selector.selected == ">") {
pack_width = package_height;
pack_height = package_width;
}else {
pack_width = package_width;
pack_height = package_height;
}
pack.setSize(pack_width, pack_height);
//snap using the height and width
x_pos = (int)((int)(position.x-pack_width/2)/(pack_width/2))*pack_width/2;
y_pos = (int)((int)(position.y-pack_height/2)/(pack_height/2))*pack_height/2;
pack.setLocation(x_pos, y_pos);
if(collision(pack.getLocation(), snap_size)) {
x_pos = -1;
y_pos = -1;
}
//If the position failed to set, its overlapping
if (x_pos != -1 && y_pos != -1) {
Selector.point_list.add(pack.getLocation());
if(Selector.selected == "<" || Selector.selected == ">") {
Selector.point_list.add(new Point(pack.getLocation().x+snap_size, pack.getLocation().y));
}else{
Selector.point_list.add(new Point(pack.getLocation().x, pack.getLocation().y+snap_size));
}
pallet.add(pack);
main_page.repaint();
Selector.selected = "";
}
}
}
}
Collision Function
public static boolean collision(Point pack, int snap_size) {
Iterator<Point> it = Selector.point_list.iterator();
Point next;
while(it.hasNext()) {
next = it.next();
if(pack.x == next.x && pack.y == next.y) {
return true;
}
if(Selector.selected == "<" || Selector.selected == ">") {
if(pack.x+snap_size == next.x && pack.y == next.y) {
return true;
}
}else {
if(pack.x == next.x && pack.y+snap_size == next.y) {
return true;
}
}
}
return false;
}
The class Selector holds 2 static variables. One is the point_list which holds a list of all the points that have a button in them already. The other is selected which is used to determine the orientation of the button based on if the first button pressed has ^,v,< or > on it.

how update Jtextfield text simultaneously when typing on it?

I have a JTextField.I want after each character the user types,a method call and change the order of character in same JTextField,but in my code displayArrestNo2() method call and print in consol right answer but dont update content of JTextField.How can do it?
public static void main(String args[]) {
final JTextField textField = new JTextField();
textField.setSize(100, 100);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
}
public void removeUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
try{
Stringx=displayArrestNo2(e.getDocument().getText(0,e.getDocument().getLength()));
System.out.println(x);
}catch(Exception ex){
ex.printStackTrace();
}
}
public void warn() {
}
public String displayArrestNo2(String aValue){
System.out.println("oroginal value: " + aValue);
aValue = " "+aValue+" ";
System.out.println("space added value: "+aValue);
final String validStr = " ابپتثجچحخدرزژسشصضطظعغفقکگلمنوهیي";
int lPos, fPos, i, j, k;
boolean flgEnterIntSection, lastWasChar;
String result = "";
flgEnterIntSection= false;
lastWasChar = false;
lPos = 0;
i = aValue.length()-1;
while( i >= 0) {
char[] aValueArr = aValue.toCharArray();
/* char[] tmpArr = aValue.toCharArray();
char[] aValueArr = new char[tmpArr.length];
for(int x=0; x<tmpArr.length; x++)
aValueArr[x]= tmpArr[tmpArr.length-x-1]; */
if (aValueArr[i] == 'ß')
aValueArr[i] = '˜';
if (convert(aValueArr[i]) == -1)
{
if(validStr.indexOf(aValueArr[i]) > 0)
{
j = 0;
while ( ( (i - j) > 0) && (validStr.indexOf(aValueArr[i-j]) > 0 ))
j = j + 1;
if (j >1)//j>1
{
k = j;
while (j > 0)
{
result = result + aValueArr[i - j+1];//i-j+1
j--;
}
i = i - k+1;//i-k+1
}
else
result = result + aValueArr[i];
}
else
result = result + aValueArr[i];
i--;
flgEnterIntSection = false;
}
else
{
fPos = i;
j = i;
while ((j >= 0) && ((!flgEnterIntSection) || (convert(aValueArr[j]))!=-1))// (StrToIntDef(AValue[j], -1) <> -1)
{
flgEnterIntSection = true;
while ((j >= 0) && (convert(aValueArr[j]))!=-1) // StrToIntDef(AValue[j], -1) <> -1)
j--;
if ((j > 0) && ((aValueArr[j] == '.') || (aValueArr[j] == '/')) )
if (((j-1) >= 0) && (convert(aValueArr[j-1]))!=-1) //StrToIntDef(AValue[j - 1], -1) <> -1)
j--;
}
lPos = j + 1;
for (j = lPos; j <= fPos; j++)
{
result = result + aValueArr[j];
}
i = lPos-1;
}
}
// return result;
// System.out.println("before reverse "+result);
return reverseOrder(result);
}
String reverseOrder(String input){
String [] inArr = input.split(" ");
String reversed = "";
for(int i = inArr.length-1; i>=0; i--){
reversed += inArr[i] + " ";
}
return reversed;
}
public int convert(char ch) {
try {
int m = Integer.parseInt(String.valueOf(ch));
return m;
} catch (Exception e) {
return -1;
}
}
TestJTextField x=new TestJTextField();
x.add(textField);
x.setVisible(true);
}
in insertUpdate() method ,displayArrestNo2() is called per character but dont change content of JTextField.

I am writing a Hangman program for school in java and I cant get user input

I have been working on this program for a couple of days now and thought I figured out a good way to do user input. When I tried it, Java appeared to just skip the loop. The while loop being skipped is:
while(textIN.getText() == "1")
{
final String text = textIN.getText();
key = text.charAt(0);
}
while (length < lengthtemp)
{
Word = Word + WordD[length];
length++;
}
while (lives > 0)
{
JOptionPane.showMessageDialog(null,"EnterLoop");
while(textIN.getText() == "1")
{
final String text = textIN.getText();
key = text.charAt(0);
JOptionPane.showMessageDialog(null,"WORK");
}
JOptionPane.showMessageDialog(null,"KeyPressed");
length = 0;
String TextTemp = Text.toString();
while (length < lengthtemp)
{
if (key == WordD[length])
{
Text.setCharAt(length, WordD[length]);
JOptionPane.showMessageDialog(null,"Correct Letter");
Label.setText(Text.toString());
if (Text.toString() == Word)
{
lives=-1;
}
}
length++;
}
if (TextTemp == Text.toString())
{
lives--;
}
}
if (lives == -1)
{
JOptionPane.showMessageDialog(null,"You Win");
}
Thanks for the help.

Delaying Attacks With TimerTask Not Working Well

I'm making a fighting game and I want the actions of the player to be timed so you can't spam the attack key and win easily.
Here is where I do the keyboard stuff and delay. It does delay the first time, but then it the delay slowly decreases in time and ends up being 0 and lets you spam the key. As you can see I've done many things to try and stop the key from registering in the delay etc.
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (isAction == false) {
if (key == KeyEvent.VK_LEFT) {
dx = -1;
if (nHeroX < -10) {
dx = 0;
}
isRight = false;
isMoving = true;
} else if (key == KeyEvent.VK_RIGHT) {
dx = 1;
if (nHeroX > 1200) {
dx = 0;
}
isRight = true;
isMoving = true;
} else if (key == KeyEvent.VK_C) {
dx = 0;
isAction = true;
isMoving = false;
isBlock = true;
nImage = 1;
} else if (key == KeyEvent.VK_X) {
dx = 0;
isAction = true;
isMoving = false;
isWeak = true;
nImage = 2;
} else if (key == KeyEvent.VK_Z) {
dx = 0;
isAction = true;
isMoving = false;
isStrong = true;
nImage = 3;
} else if (key == KeyEvent.VK_P) {
if (!pause) {
pause = true;
} else if (pause) {
pause = false;
}
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT && !isAction) {
dx = 0;
isMoving = false;
nState = nImage = 1;
} else if (key == KeyEvent.VK_C && !isWeak && !isStrong) {
delayTask = new DelayTask();
tmrDelay.schedule(delayTask, 0, 500);
} else if (key == KeyEvent.VK_X && !isBlock && !isStrong) {
z = new DelayTask();
tmrDelay.schedule(z, 0, 450);
} else if (key == KeyEvent.VK_Z && !isBlock && !isWeak) {
x = new DelayTask();
tmrDelay.schedule(x, 0, 1200);
}
nImgNum = (int) (Math.random() * 6 + 1);
nDelay = 0;
}
//http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-tmrDelay-java.html
class DelayTask extends TimerTask {
public int nTimes = 0;
#Override
public void run() {
nTimes++;
if (nTimes == 2) {
isAction = isBlock = isStrong = isWeak = false;
nState = nImage = 1;
}
}
}
Can someone explain why my delay is messed up? Thank you.
Also this code:
private class Keys extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
hero.keyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
hero.keyReleased(e);
if (hero.getPause()) {
repaint();
}
}
}
The simplest way to do this is just to remember the last time.
So:
private long lastTime = 0;
void doAction() {
long timeNow = System.currentTimeMillis()
if (lastTime + MIN_DELAY < timeNow) {
return;
}
lastTime = timeNow;
// Do action
}
All the stuff with timers etc is just approaching this from a much more complicated architecture than you need to.

Categories