I'd like to have some pieces of Java code formatted in more compact way than default Netbeans formatting behaviour, however, I wasn't able to set Netbeans formatting options for code snippets bellow properly, so I'll try to ask here:
1/ Is is possible to set Netbeans formatting to leave single line method as is? For example:
public void printMessage(String message) { System.out.println(message); }
default behaviour formats this snippet as below:
public void printMessage(String message) {
System.out.println(message);
}
2/ Is it possible to have double braces initialization in this form?
private List<String> list = new ArrayList<String>() {{
// some code here
}};
Netbeans always breaks this code into
private List<String> list = new ArrayList<String>() {
{
// some code here
}
};
Thanks for tips.
Take a look at these sites for more info.
-https://netbeans.org/kb/docs/java/editor-formatting-screencast.html
-http://www.informit.com/articles/article.aspx?p=519945&seqNum=15
To adjust formatting rules for Java files:
Choose Tools -> Options.
Click Editor in the left panel and select the Indentation tab.
Adjust the properties for the indentation engine to your taste.
Reformat each file to the new rules by opening the file and pressing Ctrl + Shift + F (with no text selected).
Related
When I comment a line of code in JBoss Developer Studio with command+/, it makes the comment left-aligned. Instead, I'd like the comment to follow the indentation size of my code block. How can I accomplish this?
Current
private static String transformSymbolicName(String unformatted) {
// String formatted = unformatted.replace('-', '.').toLowerCase();
return formatted;
}
Desired
private static String transformSymbolicName(String unformatted) {
// String formatted = unformatted.replace('-', '.').toLowerCase();
return formatted;
}
Tools: JBoss Developer Studio 8, JDK 1.7.0_80, macOS Sierra
Go to
Window -> Preferences
on the left unwrap Java -> Code Style, choose
Formatter
Click Edit...
Go to Comments tab In General Settings block and remove tick for:
a. Never indent line comments on first column
b. Never indent block comments on first column
You can see how it affects in the Preview window on the right
Change profile name on the top and click Apply.
I was trying to figure out what are the input languages installed on Windows from a Java application. You can manually figure this from out Control Panel->Region and Language->Change keyboards(button)->General->Installed Services(bottom panel).
The background is that in the application I am forcing Locale.US using a following call -
Component component = getAWTComponent();
component.getInputContext().selectInputMethod(Locale.US)
But on some hosts US keyboard language is not installed (say a system in UK). I wanted to verify that the language is not available and throw an error or something.
Also, is it possible to install such services from Java (far-fetched may be..)?
Messing with the default keyboard layout is something that should only be done with great care. If you do this at all, you should give users an option to select which layout they want instead of forcing a certain layout on everyone.
Imagine your reaction if I wrote an app and tried to force you to use the German keyboard.
That said, the API will fall back to a valid keyboard layout when Locale.US isn't available. The code which does that is hidden in sun.awt.im.InputContext.selectInputMethod()
Using reflection, you should be able to replicate the part of the code which checks whether some locale is supported.
static public void main(String[]args) {
Locale al[] = DateFormat.getAvailableLocales();
for (Locale l : al) {
System.out.println(l);
}
}
Java can found your default charset :
public final static Charset CHARSET_SYSTEM =
Charset.forName(System.getProperties().get("sun.jnu.encoding").toString());
then you can use it in a Scanner to transform input charset in UniCode :
Scanner scan = null;
final void defineScan(Charset charsetCanBeNull) {
scan = new Scanner(System.in, (null == charsetCanBeNull)
? charset
: charsetCanBeNull);
}
Then you can use Scanner.methods(..)
I want to create a special Password Dialog for my eclipse product, which is used with an on screen keyboard.
It would be very nice, if i could use a component like the IPhone Password field. In this field, the added character is shown for a second and after the second it is converted into the '*' character for hiding the complete password.
Did a jar/library exists, this is implemented in AWT or SWT?
Edit:
I could trying to implement it from scratch (SWT), but for these i would have to create a very special and complicated KeyListener for the password Text component. I would have to catch the keyReleased event and set the characters manually into the field.
So far i was not able to find any libraries in the web. Suggestion how this can be implemented are welcome too.
This is not really a full answer, rather than a discussion starter and I don't know of any out-of-the-box widgets which can do that.
My first idea was to inheriting the swt Text widget and overriding setEchoChar et al., but after looking at the code this doesn't really seem feasible, because this method is merely a wrapper around:
OS.SendMessage (handle, OS.EM_SETPASSWORDCHAR, echo, 0);
If anyone would know the OS specific low-level implementation, that might be helpful.
Anyway, on to a different approach. I would avoid the KeyListener and use a ModifyListener on the Text-Widget.
void addModifyListener(ModifyListener listener)
You could then build a wrapper which catches the entered text using this listener, appends it to a locally held string/stringbuffer (or e.g. the Eclipse Preferencestore) and send a modified full text to the Text widget using setText(String s), replacing all characters except the last by an echo character (e.g. *).
myText.setText((s.substring(0, s.length()-1)).replaceAll("[\\s\\S]","*")+s.charAt(s.length()-1));
This is a bit of a kludge, but it should work.
The not so straightforward bit is the 1 second timing, without stalling the whole view...
Depending on what Jules said the following code is some kind of working.
The code is quick and fast and i would like to have a more thread safe solution.
originalString = new StringBuffer();
passwordField.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
synchronized (passwordField) {
String s = passwordField.getText();
String newS = s.replaceAll("[\\s\\S]", "*");
if (newS.equals(s)) {
while (originalString.length() > s.length()) {
originalString = originalString.deleteCharAt(originalString.length() - 1);
}
usernameField.setText(originalString.toString());
return;
}
if (originalString.length() < s.length()) {
originalString.append(s.charAt(s.length() - 1));
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
}
passwordField.setText(newS);
}
passwordField.redraw();
passwordField.setSelection(passwordField.getText().length());
}
});
Key Events are cached, so you can add more characters, also when the Thread is waiting.
Another Problem is the Cursor handling. the Cursor always moves to the first position, when you set the Text.
I think when this is working it is very near to the iphone solution.
When I started programming with the JDK6, I had no problem with text components, neither in AWT nor in Swing.
But for labels or titles of AWT components I do have a problem. I can't display Farsi characters on AWTs components (in Swing I type them into the source code).
Here's my sample code:
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Properties;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
/*
show = new MenuItem("\u0646\u0645\u0627\u06cc\u0634");
*
*/
// approach 2 = using simple utf-8 saved text file :
/*
BufferedReader in = new BufferedReader(new FileReader("farsiLabels.txt"));
String showLabel = in.readLine();
in.close();
show = new MenuItem(showLabel);
*
*/
// approach 3 = using properties file :
FileReader in = new FileReader("farsiLabels.properties");
Properties farsiLabels = new Properties();
farsiLabels.load(in);
show = new MenuItem(farsiLabels.getProperty("tray.show"));
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("greenIcon.png");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
These three approaches all work when run with an IDE, but when I make a JAR containing this class (by means of NetBeans > project > clean & build), I don't see the expected characters (it shows EMPTY/BLANK SQUARES)!
Note:
It seems I can not attach anything, so the contents of the text file would be this: نمایش and the contents of properties file:
#Sun May 02 09:45:10 IRDT 2010
tray.show=نمایش
And I think I have to let you know that I posted this question a while ago on SDN and "the Java Ranch" forums and other native forums and still I'm waiting...
By the way I am using latest version of Netbeans IDE...
I will be grateful if anybody has a solution to these damn AWT components never rendering any Farsi character for me...
I suspect that this is platform related. Your example appears to work on my platform using approach 1 in either Netbeans or the command line; I didn't try the other approaches.
There might be a disparity between the IDE and the command line with regard to the default character encoding. I've noticed that NetBeans, Eclipse and many consoles can be set to something other than the platform default. Here's code to check:
System.out.println(System.getProperty("file.encoding"));
System.out.println(Charset.defaultCharset().name());
You might look at this related question, too.
Addendum: Note show string changed to match the JFrame title for comparison. The title and menu look the same from NetBeans' Run > Run Project as well as via these command lines:
$ java -cp build/classes EmptyFarsiCharsOnAWT
$ java -jar dist/test6.jar
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class EmptyFarsiCharsOnAWT extends JFrame{
public EmptyFarsiCharsOnAWT() {
super("مثال");
setDefaultCloseOperation(3);
setVisible(rootPaneCheckingEnabled);
}
public static void main(String[] args) throws AWTException, IOException {
JFrame jFrame = new EmptyFarsiCharsOnAWT();
MenuItem show ;
// approach 1 = HardCoding :
show = new MenuItem("\u0645\u062b\u0627\u0644");
PopupMenu popUp = new PopupMenu();
popUp.add(show);
// creating Tray object
Image iconIamge = Toolkit.getDefaultToolkit().getImage("image.jpg");
TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp);
SystemTray tray = SystemTray.getSystemTray();
tray.add(trayIcon);
jFrame.setIconImage(iconIamge);
}
}
The most exciting part of your reply was:
"$ java -jar dist/test6.jar" !
Does it really shows the real characters (just like the frame title)?!
and not boxes or garbage ?
I'm sorry if I believe it hard, because the only problem in my developing work with Java took such long without any answer nor from searching, nor asking in forums is this!
So, what can I do? what font should I use? Unfortunately I'm not so familiar with fonts, until now I've just used global fonts in Java (Serif,SansSerif,etc.) and only modified their size or style, but after you suggest I examined several Persian ttf fonts through these codes:
File fontFile = new File("F_JADID.TTF");
Font font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
show.setFont(font.deriveFont(15f));
but just boxes was the result! (just using HardCoding)
I think i should mention that my envirounment is win xp and i have this problem not only in my machine, but another running xp os too. And I'm using jdk6u17.
I can be agree with you in suspecting the fonts, because encoding problem (in my experience) appears with question mark, but garbage or empty boxes related to rendering characters.
But still i have the problem, just like the first day :(
What font you use and another question i encountered is:
Why swing doesn't have any problem without specifying the font, but AWT.
Addendum: Thanks to Oscar Reyes in this page for giving this link and thanks to StackOverflow :)
They saved me! from this section i should quote:
An application using peered AWT components can only use logical font names.
and from this section should quote:
For applications using AWT peered components, Sun's JREs select fonts for Chinese, Japanese, or Korean only when running on host operating systems localized for these specific languages
Yes, you guess right! by setting the OS locale to Farsi, i got the right result.
but i still should research and see how is it possible to have the right result by not setting the right locale, from that article.
I will explain how, when i got the result, but still will listen to here. wish me luck.
I have a regular expression (\d{4}\w{3}(0[1-9]|[12][0-9]|3[01])([01][0-9]|2[0-3])([0-5][0-9]){2}) that I need to validate the input of a text field against when the user clicks the OK button or moves the cursor to another field. That I know how to do, writing the code. However, I'm interested in if it's possible to have the NetBeans GUI editor do some of the work for me, especially since I'm moving away from Eclipse and towards NetBeans as my IDE of choice, and I would like to take full advantage of the tools it provides.
Open the Properties of your JTextField, in the Properties tab look for inputVerifier. Open it
Now you'll be asked to introduce the InputVerifier code.
ftf2.setInputVerifier(new InputVerifier() {
public boolean verifyText(String textToVerify) {
Pattern p = Pattern.compile("your regexp");
Matcher m = p.matcher(textToVerify);
if (m.matches()) {
setComponentValue(textToVerify);
return true;
}
else {
return false;
}
}
});
I haven't compiled this code, so could contain errors. But I think you get the idea ;)
This isn't the easiest solution, but it is a very powerful one:
try spring rich client, where validation could be reached via:
public class Validation extends DefaultRulesSource {
private Constraint NAME_VALIDATION = all(new Constraint[]{minLength(3), required()});
public void load() {
addRules(new Rules(Person.class) {
#Override
protected void initRules() {
add("name", NAME_VALIDATION);
}
});
...
and the gui form is easily created via:
TableFormBuilder formBuilder = getFormBuilder();
formBuilder.add("firstName");
formBuilder.add("name");
formBuilder.row();
E.g. look here for validation or here for more infos. I am using this sucessfully in my open source project ...
This way you could create a more general swing component which could be added to the netbeans component palette