How to treat 4 consecutive spaces as a single character? - java

I have written a TextArea that types 4 consecutive spaces whenever I press a certain key combination (Alt + C in my case), however, I am looking for a way to make the program treat them as if they're a single character, by which I mean that:
the caret's position jumps from one end of the space sequence to the other if it moves towards it
I can only select all of them at once
if I press backspace and the caret is in front of them, all 4 get deleted at once
I've managed to complete the first two tasks by creating a caret position listener, but whenever I try to delete the 4 spaces, I get an IndexOutOfBoundsException error that redirects me to the listener, even though the code for that is written in a key event handler that checks if the key pressed is a backspace.
I'm only going to include the snippets of code that are relevant to the question, as the whole program is quite long:
textarea.caretPositionProperty().addListener((ob, old1, new1) -> {
int oldi = old1.intValue();
int newi = new1.intValue();
if (oldi > newi && oldi > 3 && textarea.getText(oldi - 4, oldi).equals(" "))
textarea.positionCaret(oldi - 4);
if (oldi < newi && oldi < (textarea.getText().length() - 3) && textarea.getText(oldi, oldi + 4).equals(" "))
textarea.positionCaret(oldi + 4);
});
textarea.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
int cp = textarea.getCaretPosition();
if (e.isAltDown() && (e.getCode() == KeyCode.C)) {
// Some other code
textarea.positionCaret(cp + 4);
}
if (e.getCode() == KeyCode.BACK_SPACE && areat.length() > 3)
if (areat.substring(cp - 4, cp).equals(" "))
textarea.setText(areat.substring(0, cp - 4) + areat.substring(cp));
});
To explain the areat variable: at one point, I thought that the problem might be caused by the textarea.getText() function, given that (presumably) it could either refer to the text before or after pressing backspace (e.g. either "Hello!" or "Hello"). Fortunately, I've already written a text property listener for a separate feature of the program, so I tried solving the problem by declaring a global variable (areat) and storing the old text there (which didn't work, needless to say):
textarea.textProperty().addListener((obs, old1, new1) -> {
areat = old1;
areatn = new1;
// Some other code
});
How should I proceed from here? Is there a problem with the event handler or with the caret listener? Or maybe there is a specific method that has all the features mentioned above built-in?
Side note: I would prefer not switching to a JTextArea, as I've never worked with swing elements before.
EDIT: If you're an admin, please don't mark this question as solved, because I'm still looking for better answers, BUT I've managed to fix the issue by storing the new text of the text property listener in a global variable (areatn) instead of the old one, which I've used in both the event handler and the caret listener. Please do let me know if you've found a solution that's less bodged-in than mine.
EDIT 2: As #kleopatra pointed out in the comments, the TextFormatter class is much better equipped for this kind of situation than my listeners are.

You may be able to do this using a NavigationFilter. You would install one by calling the setNavigationFilter() method in JTextComponent. Here's what the JavaDocs say for NavigationFilter:
NavigationFilter can be used to restrict where the cursor can be
positioned. When the default cursor positioning actions attempt to
reposition the cursor they will call into the NavigationFilter,
assuming the JTextComponent has a non-null NavigationFilter set.
In this manner the NavigationFilter can effectively restrict where
the cursor can be positioned. Similarly DefaultCaret will call into
the NavigationFilter when the user is changing the selection to
further restrict where the cursor can be positioned.
You may be able to write a NavigationFilter that doesn't let the cursor be placed inside the four spaces. Typing an arrow key will move the caret across all four spaces, and selections will include the four spaces, so they will behave for the user as a single character. I've done this kind of thing and it's very reliable and isn't very hard.

Related

Is there a way to refactor by adding an outer method call using Intellij?

I have this:
Arrays.asList(from(A, 14), from(A, 21), ...
What I need is:
Arrays.asList(of(from(A, 14), 1), of(from(A, 21), 2), ...
The call from(A, number) should be turned into of(from(A, number), anotherNumber).
In other words: I have to update a lengthy list of such from() calls by enclosing them within an of() and adding a second parameter. Ideally, that second parameter would simply count upwards.
Is there a way to that with IntelliJ refactoring tools?
( instead of doing it all manually )
And note: I am not asking for a tools recommendation. I am asking whether a known tool supports a specific refactoring situation.
You can highlight from( and use the "select next occurrence" hot key. Once you have selected all occurrences just replace it with of(from. Once you are done adding of you can use the "alt + left arrow key" to move the cursor to the position where you want to add the number OR use the "select next occurrence" by highlighting the ),.
On Mac the hot key is "CTRL + G" and on Windows\Linux "ALT + J". Here is a list of the hot keys https://resources.jetbrains.com/storage/products/intellij-idea/docs/IntelliJIDEA_ReferenceCard.pdf
It is still a bit manual, but beats doing it one by one.
You can try the following:
Extract method with replacing the duplicates for from(A, param)
Inside the extracted method write something like of(from(A, param), NNN)
Inline method
Replace NNN with numbers you need (this has to be performed manually)
If there is some formula that can calculate anotherNumber based on number, you can use it instead of NNN.
"Replace structurally" can do some of what you need.
Select Edit > Find > Replace Structurally...
Enter from($a$, $b$) as the search template
Enter of(from($a$, $b$), i) as the replacement template
Choose Scope: Current File (or Selection, if you prefer)
Hit Find
Hit Replace all
Assuming i is undefined you'll then be left with lots of errors. You can cycle through the errors with F2 and replace the undefined i with the values you want.
Bonus tip: on a Mac, run seq 1 100 | pbcopy at a terminal to put the numbers 1-100 into your clipboard. Then, with multiple cursors in IntelliJ, hit Paste. 1 will be pasted at the first cursor, 2 at the second, etc.

Proximity checker for a ButtonGrid (like minefield game)

I'm writing a code for a treasure hunt game, a grid of buttons and one of them hide the treasure behind it. I want to ad a proximity checker: if the button clicked touch the button with the treasure behind a message appear telling the player that he is near.
This is what i managed to write but i always get a mistake for the arrays going out of bound (this happens because the last row and column aren't surrounded by buttons).
As you can see i put a lot of "if" to contain the chance of goig out of bound but it keeps happening. Any suggestion?
You can use switch-cases here.
switch(grid){
case treasure[x1][y1]:
// your logic
break;
// other cases
default:
// default scenario
}
You need to check the length of the array before you try to access a row beyond it. It appears that you are doing this for values that too low like this:
if (y1 < 0){
y1 = 0;
}
But you need to have a similar check for values that are too high.
Alternatively,
This design could be much cleaner/simpler if you just passed in the X/Y location of the treasure. Instead of the actual JButtons. Then you could just subtract the values to determine if you were close or not.
The way I would do it is to write a function to do the check for a match that also checks for the bounds. For example:
private boolean isTreasureAt(int x, int y) {
if (x<0 || y<0 || x>width || y>height)
return false;
return treasure[x][y]; // need your correct checking logic here
}
Now you can just call isTreasureAt() for whatever co-ordinates you like and its always safe, no need to put range checks everywhere in your code.

Tagboxes or similar in JavaFX Textareas

In a Textarea, containing a boolean expression I want to mark individual terms using something similar to tagboxes (as for instance they are used here on stackoverflow to enter tags).
For instance, if the user enters a string, such as
A > 0 && B == 1
the terms A > 0 and B == 1, respectively, shall be encapsulated in a box.
My question only concerns the GUI-aspect. My question is not about how to parse the string.
Has anyone got an idea on how to go about this?
you cannot achieve this with TextArea, but you could probably use CodeAreaFX
There is no solution to your request.
TextAreas cannot have different styles applied to different text strings within the TextArea.

Find/Replace dialog on jTextArea

I have assigment to make notepad using NetBeans Java. I already made the whole thing, I just don't know how to implement find/replace dialog, can you help me with this. I'm using jTextArea.
I will assume that you already know about Swing and how to make the appropriate dialog box (since you apparently have already made the JTextArea for the Notepad equivalent), and that you just want to know how to make it work on the back end.
What I would do is have a Scanner object go through your file to perform the find and replace.
String myAlteredText = "";
Scanner scanner = new Scanner(myText);
while(scanner.hasNext()) {
String next = scanner.next();
if(next.equals(userFindInput)) {
myAlteredText += userReplaceInput;
}
else {
myAlteredText += next;
}
myAlteredText += " ";
}
You can use .equalsIgnoreCase() if case doesn't matter. Likewise, you can tweak to adjust to your user parameters (i.e., if it doesn't have to match the whole word, use .contains() instead). There may be some nit-picky other things you need to do to maintain abnormal spacing and line breaks, but this is the general approach I would use.
You could use a JTable although this is rather unconventional. You could load each word into a new cell. This way when you need to replace 1 word you don't need to update the entire jtextarea for just 1 character unless I am mistaken. This would require a lot of work however in order to get this to work

Hidden features of Eclipse [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Alright it can be a lame question, but everybody uses these things differently. What's some of the best time savers out there for this IDE.
Tom
Don't forget Ctrl+Shift+L, which displays a list of all the keyboard shortcut combinations (just in case you forget any of those listed here).
Ctrl-2 something
Seems that nobody mentioned Ctrl-2 L (assign to new local variable) and Ctrl-2 F (assign to a new field), these ones have changed how I write code.
Previously, I was typing, say (| is cursor location):
Display display = new |
and then I pushed Ctrl-Space to complete the constructor call. Now I type:
new Display()|
and press Ctrl-2 L, which results in:
Display display = new Display()|
This really speeds things up. (Ctrl-2 F does the same, but assigns to a new field rather than a new variable.)
Another good shortcut is Ctrl-2 R: rename in file. It is much faster than rename refactoring (Alt-Shift-R) when renaming things like local variables.
Actually I went to Keys customization preference page and assigned all sorts of additional quick fixes to Ctrl-2-something. For example I now press Ctrl-2 J to split/join variable declaration, Ctrl-2 C to extract an inner class into top-level, Ctrl-2 T to add throws declaration to the function, etc. There are tons of assignable quick fixes, go pick your favourite ones and assign them to Ctrl-2 shortcuts.
Templates
Another favourite of mine in my “npe” template, defined as:
if (${arg:localVar} == null)
throw new ${exception:link(NullPointerException,IllegalArgumentException)}("${arg:localVar} is null");
This allows me to quickly add null argument checks at the start of every function (especially ones that merely save the argument into a field or add it into a collection, especially constructors), which is great for detecting bugs early.
See more useful templates at www.tarantsov.com/eclipse/templates/. I won't list them all here because there are many, and because I often add new ones.
Completion
A few code completion tricks:
camel case support mentioned in another answer: type cTM, get currentTimeMillis
default constructor: in the class declaration with no default constructor push Ctrl-Space, the first choice will be to create one
overloading: in the class declaration start typing name of a method you can overload, Ctrl-Space, pick one
getter/setter creation: type “get”, Ctrl-Space, choose a getter to create; same with “is” and “set”
Assign To A New Field
This is how I add fields.
If you have no constructors yet, add one. (Ctrl-Space anywhere in a class declaration, pick the first proposal.)
Add an argument (| is cursor position):
public class MyClass {
public MyClass(int something|) {
}
}
Press Ctrl-1, choose “assign to a new field”. You get:
public class MyClass {
private final Object something;
public MyClass(Object something) {
this.something = something;
}
}
Add a null-pointer check if appropriate (see “npe” template above):
public class MyClass {
private final Object something;
public MyClass(Object something) {
npe|
this.something = something;
}
}
Hit Ctrl-Space, get:
public class MyClass {
private final Object something;
public MyClass(Object something) {
if (something == null)
throw new NullPointerException("something is null");
this.something = something;
}
}
A great time saver!
ctrl-shift-r and its buddy, ctrl-shift-t, to open a resource or type, respectively. Resources includes all files in your open projects (including non-java files), and types includes java types either in your projects, or in a library included in the projects.
Crtl+1 is my favorite. The quick fixes for the red-squiggles.
It is also located in the Edit Menu -> Quick Fix.
Ctrl+Shift+O to organize imports, which will format them nicely, remove unneeded imports, and add missing imports.
Ctrl-J starts an incremental find.
Hit Ctrl-J, then start typing. Use up/down to find previous/next instances of what you typed.
Ctrl-Shift-J searches backwards.
Type 'syso' then press Ctrl+Space to expand it to System.out.println().
Tres handy.
CTRL+3 brings up a type-ahead list of any menu command.
CTRL-SHIFT-g : finds usages of the method or field under the cursor, absolutely necessary for understanding code
CTRL-F6 : navigate between the list of open editor windows, if you just type it once and let go you toggle back to the previous editor window, doing this successively is a nice way to jump back and forth
CTRL-t : on a class or method will show you the type hierarchy, very useful for finding implementations of an interface method for example
Clicking on the return type in a method's declaration highlights all exit points of the method.
for instance:
1: public void foo()
2: {
3: somecode();
4: if ( blah ) return;
5:
6: bar();
7: }
clicking on void will highlight the return on line 4 and the close } on line 7.
Update: It even works for try{} catch blocks. If you put cursor on exception in the catch block and eclipse will highlight the probable methods which may throw that exception.
Code completion supports CamelCase, e.g., typing CWAR will show a result for ClassWithAReallyLongName. Start using this feature and you'll never type another long classname again.
(parts copied from another answer because i think answers w/ just one hint/tip are best for polling)
Alt-Up Arrow moves the current selection up a line, Alt-Down Arrow moves it down. I also use Alt-Shift-Up/Down Arrow all the time. Ctrl-K and Ctrl-Shift-K is quite handy, finding next/previous occurrence of the current selection (or the last Find, if nothing is selected).
There's an option to place the opening curly brace and a semicolon automagically in the "correct" position. You'll have to enable this - Choose Window/Preferences and type "brace" in the searchbox - should be easily findable (no eclipse on this computer). The effect:
Typing a semicolon anywhere on the line will place it at this lines end (as in word/openoffice: Backspace if you'd like to have it in the original place)
Typing an opening curly brace when you're just inside another pair of braces will place it at the end of this line - as in this example
("|" is the cursor):
if(i==0|)
typing "{" now will result in
if(i==0) {|
Hippie expand/Word Complete, afaik inspired by Emacs: will autocomplete any word in any editor based on other words in that file. Autocomplete inside String literals in Java code, in xml files, everywhere.
Alt + /
Alt-Shift-R stands for rename, not refactor. Refactoring is a more general term (as defined by the book).
Nevertheless, it is one of my favorite refactorings. Others include:
Alt-Shift-M: Extract Method (when a code block or an expression is selected)
Alt-Shift-L: Extract Local Variable (when an expression is selected)
Extract Local Variable is especially useful when I don't remember (or bother to type) the result type of a method. Assuming you have a method JdbcTemplate createJdbcTemplate() in your class, write some code such as this:
void someQuery() {
createJdbcTemplate()
}
Select the expression createJdbcTemplate(), click Alt-Shift-L, type the name of variable and press enter.
void someQuery() {
JdbcTemplate myTemplate = createJdbcTemplate();
}
CTRL + D - to delete current line
Absolutely, Ctrl+Q to go to last edit location.
It is very useful just after being interrupted by phone, boss or others.
Ctrl + Shift + M: changes a static method or static attribute reference of a class to a static import.
Before
import X;
...
X.callSomething();
After
import static X.callSomething;
...
callSomething();
Alt+Shift+Up Arrow does escalating selection. Alt+Shift+Down does the opposite.
Alt+Up or Alt+Down to move lines
Nobody's mentioned the best one yet. Click on a class or method name and press Ctrl+T.
You get a quick type hierarchy. For a class name you see the entire class hierarchy. For a method name you get the hierarchy showing superclasses and subclasses, with implementations of that method distinguished from abstract mentions, or classes that don't mention the method.
This is huge when you are at an abstract method declaration and quickly want to see where it is implemented.
F3 has been my favorite, opens the definition for the selected item.
Ctrl+Shift+R has an interesting feature, you can use just the uppercase camel letters from a class when searching (such as typing CWAR will show a result for ClassWithAReallyLongName).
Alt+Shift+W > Package Explorer makes life easier when browsing large projects.
A non-keyboard shortcut trick is to use commit sets in your Team->Synchronise view to organise your changes before committing.
Set a change set to be the default, and all changes you make on files will be put in that set, making it easy to see what you have changed while working on a specific defect/feature, and other changes you had while testing etc.
CTRL+SPACE, for anything, anywhere.
Generate getters and setters.
Create Constructors using Fields
Extract Method...
Refactor->Rename
CTRL+O for the quick outline. CTRL+O+CTRL+O for the inherited outline.
F4 to display a type hierarchy
Open Call Hierarchy to display where a method is called from.
CTRL+SHIFT+T to open a Java Type
CTRL+SHIFT+R to open any resource.
ALT + left or right to go forward or backwards through edit places in your documents (easy navigation)
Override/Implement methods if you know you're going to do a lot of methods (otherwise, CTRL+SPACE is better for one at a time selection.
Refactor->Extract Interface
Refactor->Pull up
Refactor->Push down
CTRL+SHIFT+O for organize imports (when typing the general class name such as Map, pressing CTRL+SPACE and then selecting the appropriate class will import it directly for you).
CTRL+SHIFT+F for formatting (although Eclipse's built in formatter can be a little braindead for long lines of code)
EDIT: Oh yeah, some debugging:
F5: Step into (show me the details!)
F6: Step over (I believe you, on to the next part...)
F7: Step out (I thought I cared about this method, but it turns out I don't, get me out of here!)
F8: Resume (go until the next breakpoint is reached)
CTRL+SHIFT+I: inspect an expression. CTRL+SHIFT+I+CTRL+SHIFT+I: create a watch expression on the inspected expression.
Conditional breakpoints: Right click a breakpoint and you may set a condition that occurs which triggers its breaking the execution of the program (context assist, with Ctrl+Space, is available here!)
F11 - Debug last launched (application)
CTRL+F11 - Run last launched (application)
Breakpoint on Exception
Eclipse let you set breakpoints based on where an Exception occurs.
You access the option via the "j!" alt text http://help.eclipse.org/stable/topic/org.eclipse.jdt.doc.user/images/org.eclipse.jdt.debug.ui/elcl16/exc_catch.png icon in the debugging window.
alt text http://blogs.bytecode.com.au/glen/2007/04/06/images/2007/AddExceptionWindow.png
The official help topic "Add Java Exception Breakpoint " has more on this.
The Uncaught Exception option is to suspend execution when an exception of the same type as the breakpoint is thrown in an uncaught location.
The Caught Exception option is to suspend execution when an exception of the same type as the breakpoint is thrown in a caught location.
do not forget the Exception Breakpoint Suspend on Subclass of this Exception:
to suspend execution when subclasses of the exception type are encountered.
For example, if an exception breakpoint for RuntimeException is configured to suspend on subclasses, it will also be triggered by a NullPointerException.
alt text http://help.eclipse.org/stable/topic/org.eclipse.jdt.doc.user/reference/breakpoints/images/ref-breakpoint_suspendsubclass.PNG
Ctrl+Alt+H on a method to get the call hierarchy for it. Fast way to see where it is called from.
Ctrl+Alt+UP or Ctrl+Alt+DOWN to copy lines
Alt + Shift + R to refactor and rename.
Here is my collection of the most useful keyboard shortcuts for Eclipse 3:
Eclipse 3 Favorite Keyboard Shortcuts.
by -=MaGGuS=-
Navigate:
• Ctrl + Shift + L – Shows useful keyboard shortcuts in popup window
• Ctrl + H – Search.
• Ctrl + K – Goes to next search match in a single file. Shift + Ctrl + K – goes to previous match.
• F3 - Goes to ‘declaration’ of something. Same as Ctrl + Click.
• Ctrl + Shift + G - Use this on a method name or variable. It will search for references in the code (all the code) to that item.
• Ctrl + O – Shows outline view of the current class or interface.
• Ctrl + T – Shows class hierarchy of the current class or interface. F4 – shows the same in separate tab.
• Ctrl + Shift + T - Open Type. Search for any type globally in the workspace.
• Ctrl + Shift + R – Open Resource. Search for any file inside workspace.
• Ctrl + J – Incremental search. Similar to the search in firefox. It shows you results as you type. Shift + Ctrl +J - Reverse incremental search.
• Ctrl + Q – Goes to the last edit location.
• Ctrl + Left|Right – Go Back/Forward in history.
• Ctrl + L – Go to line number.
• Ctrl + E – This will give you a list of all the source code windows that are currently open. You can arrow up or down on the items to go to a tab.
• Ctrl +PgUp|PgDown – Cycles through editor tabs.
• Ctrl + Shift + Up|Down - Bounces you up and down through the methods in the source code.
• Ctrl + F7 – Switches between panes (views).
• Ctrl + ,|. – Go to the previous/next error. Great in combination with Ctrl + 1.
• Ctrl + 1 on an error – Brings up suggestions for fixing the error. The suggestions can be clicked.
• Ctrl + F4 – Close one source window.
Edit:
• Ctrl + Space – Auto-completion.
• Ctrl + / – Toggle comment selected lines.
• Ctrl + Shift + /|\ – Block comment/uncomment selected lines.
• Ctrl + Shift + F – Quickly ‘formats’ your java code based on your preferences set up under Window –> Preferences.
• Ctrl + I – Correct indentations.
• Alt + Up|Down – move the highlighted code up/down one line. If nothing is selected, selects the current line.
• Ctrl + D – Delete row.
• Alt + Shift + Up|Down|Left|Right – select increasing semantic units.
• Ctrl + Shift + O – Organize Imports.
• Alt + Shift + S – Brings up “Source” menu.
o Shift + Alt + S, R – Generate getter/setter.
o Shift + Alt + S, O – Generate constructor using fields.
o Shift + Alt + S, C – Generate constructor from superclass.
• Alt + Shift + T – Brings up “Refactor” menu.
• Alt + Shift + J – Insert javadoc comment.
• F2 – Display javadoc popup for current item. Shift + F2 – Display javadoc in external browser.
Run/Debug:
• F11 / Ctrl + F11 – Execute/debug.
• Ctrl + Shift +B – Toggle breakpoint.
• When paused: F5 – Step into, F6 – Step over, F7 – Step out, F8 – Resume.
• Ctrl + F2 – Terminate.
EOF
Not so Hidden but IMO the best Trick.
Assuming Default Settings (and you have'nt added new snippets)
Highlight (or select) a Text (String or Variable)...Press Ctrl+Space. Hit End+Enter.
the "sysout" snippet is triggered which wraps the selection around as its parameter.
eg.
"hello world!"
becomes
System.out.println("hello world!");
I love it so much that i've implemented a similar snippet for Android's Toast and Log.i()
HUGE Time saver during Manual Debugging....

Categories