I've got a problem with formatting a string using javas String.format.
I'm adding the string containing a description and a price to a swing JList component. I want that the prices are always under each other.
So I use:
String ret = String.format( "%s %-" + Integer.toString(articleNameLength) + "s %3s %9.2f EUR",
(new SimpleDateFormat("dd.MM.yyyy")).format(date), article, " ", price );
You can also see the code at line 205 at:
https://github.com/hanneseilers/MyBudget/blob/master/MyBudget/src/de/hanneseilers/core/Article.java
That's working fine if I start the application using eclipse or a simple batch file that runs
java -jar MyBudget.ja
But if i use a doubleclick in file explorer to start the jar, the layout breaks up and the prices aren't under each other.
Any idea why this happens?
I found a working solution for this.
The problem was that the application only can load a speficic monospaced font (that has same width for each character) if I start the jar using a batch script. Using a double script, java can not find the spefific font and uses default not-monospaced (irregular width for each character).
I changed the font of the JList swing component that displays the string to a not further specified monospaced font. That causes the application to load any monospaced font and it's working!
list.setFont(new Font("Monospaced", Font.BOLD, 12));
Related
How can I embed a custom font in a JavaFX Application? I've tried making a fonts.mf file, and following the instructions to a similar question linked below. I don't want to use CSS if I don't have to. I want to focus on learning core JavaFX stuff.
Here is what I've been messing around with:
private static Label makeTitle() {
Label title = new Label("Bandit King");
Font font = new Font("OldStyle", 40);
title.setFont(font);
return title;
}
my fonts.mf file contains just this line:
OldStyle = /home/myName/Desktop/My_Java_Projects/Bandit_King/banditKing/OLDSH.TTF
This is not a duplicate of this question. Eclipse says, "CustomFontApp, cannot be resolved to a type".
I've tried making a fonts.mf file
You don't need it.
This is not a duplicate of this question. Eclipse says, "CustomFontApp, cannot be resolved to a type".
CustomFontApp is just the name of a class used in the answer you linked - your class name is obviously different, and you should've changed it.
This line:
Font font = new Font("OldStyle", 40);
will load OldStyle font only if it's installed on your system. You aren't using an installed font, but the embedded one, so that won't work.
You need to use Font.loadFont(InputStream, double) or Font.loadFont(String, double) to load your custom font from disk:
// use this to load font from your application's resource folder (`res/fonts/OLDSIH.TTF`)
Font font = Font.loadFont(getClass().getResourceAsStream("/fonts/OLDSIH.TTF"), 40);
// or this one to load font from the specified (absolute) path
// (not recommended, use the method above or, at least, change this into relative path):
Font font = Font.loadFont("file:///home/myName/Desktop/My_Java_Projects/Bandit_King/banditKing/OLDSH.TTF", 40);
I use Eclipse Luna 4.4.2
using the "externalize strings" wizard (from right click on the class in the package explorer) it replaces my original strings by another string pointing to the key in the property file.
For example, having this label defined in a class "myFrame" :
JLabel mylabel = new JLabel("original text");
after the wizard the result is:
JLabel mylabel = new JLabel(Messages.getString("myFrame.1")
I would prefer a behavior where the key would be constructed by the component name. It is what happen if I use the other wizard from the windowbuilder view. But this wizard has less options (you can't set to ignore..)
So this result would be better :
JLabel mylabel = new JLabel(Messages.getString("myFrame.mylabel.text")
or even something like
JLabel mylabel = new JLabel(Messages.myFrame_mylabel_text)
I spent a lot of time on searching and found this thread Configuring string externalization in Eclipse to use ${key} as field name
but it is old and I do not have the checkbox "use Eclipe's externalization mechanism" ?!
Also this thread says that the features have been implemented inside Eclipse http://blog.vogella.com/2013/08/12/eclipse-internationalization-part-44-new-features-by-dirk-fauth/
Did I miss some updates ? I installed te latest build of Eclipse-Mars, but it does not help..
Thank you for help !
I am working on a text editor for Malayalam in Java.
Unicode font is not rendering correctly in Swing - JTextArea.
Combination of characters. Instead of blending two characters, Text area displaying it separately. Both swing and font support those characters but in key combinations it is not working Even though supported font is used.
For Example:
What is needed
ക്രാ
What is getting
്രക
Code
jButton69.setFont(new java.awt.Font("Meera", 0, 12)); // NOI18N
jButton69.setText(" ്ര");
jTextArea1.append(jButton69.getText());
EDIT: (Complementary information from author's commentary):
When combine three characters ക (\u0D15) + ് (\u0D4D) + ര (\u0D30), I am getting ര്ക instead of ക്ര.
Language is Malayalam, Font is Meera
You must set the JTextArea font to a Unicode font.
Besides that, the button69 has nothing to do with the problem, so I don't use it.
The following code is showing the text the way you want:
String problemText = "ഔ";
Font font = new Font("Arial Unicode MS", Font.PLAIN, 18);
JTextArea jTextArea1 = new JTextArea();
jTextArea1.setFont(font);
jTextArea1.append(problemText);
I hope it helps.
Please check out Zero Width Joiners and Zero Width Non-joiners. For your requirement, I got the correct output by using a zero width joiner as: \u0d15 + \u0d4d + \u200d + \u0d30.
Please check out Zero Width Joiners and Zero Width Non-joiners. For your requirement, I got the correct output by using a zero width joiner as: \u0d15 + \u0d4d + \u200d + \u0d30 (Please ignore my previous answer, it is the same but posted with the wrong user account).
I use Netbeans 7.0 with JDK6 under Windows 7 to design the user interface of my Java application. I apply System look and feel. But it looks the way I want in Windows but differs in MacOS and even worse, it looks different in different window managers in Linux (LXDE, GNOME, KDE, XFCE).
By different I mean the fonts look and their size. In Windows, if a label looks "v 1.23", it looks like "v ..." in other OSes because the fonts become bigger in that OS and the JLabel do not have enough place to show. This happens in several places.
I don't want to increase the label width. I want the label to look the same in that given width in all OS. By default, Netbeans uses the font Tahoma 11pt on my pc. I think it's not available in all OSes so the other OSes use different font.
Is Arial a common font?
Should I change the font of every element to Arial manually? Or any other options?
Instead, use a layout manager and a logical font family. This example with the Font below adds 24-point italic serif text to the center of a (default) BorderLayout to achieve a pleasing result on disparate platforms.
ta.setFont(new Font("Serif", Font.ITALIC, 24));
Mac OS X:
Windows 7:
Ubuntu Linux:
When it comes to window managers there is a lot more to it than just font size, for instance the width between 2 controls are handled differently in gnome & KDE. when it comes down to using the same font size across all platforms you can use Sans Serif font, this is available in all the OS'es I've worked with.
it would also be better (if you can't find serif in an OS where you want to run your app) you can download a font (free ones from GNU Free Fonts).
when it comes to setting the font sizes & the fonts, why don't you try using a theme & set the font there...
you can use the UIManager.setLookAndFeel() method to change themes.
here is a link on Look & Feel
An old question, but I've found it because I was looking for a solution.
And my solution is: use DejaVu fonts.
The Java dialog font looks different in Linux and Windows, but DejaVuSans 12 is very like the dialog font in Linux and looks the same in Windows (in Windows 8.1 at least).
My code:
...
static Font dejaVuSans;
static final String resPath = "<classpath>/resources/"; // no leading "/"
...
public static void main(String[] args) {
/* See:
* https://stackoverflow.com/questions/7434845/setting-the-default-font-of-swing-program
* https://stackoverflow.com/questions/8361947/how-to-get-getclass-getresource-from-a-static-context
*/
dejaVuSans = null;
Font f;
try {
InputStream istream = <ClassName>.class.getClassLoader().getResourceAsStream(
resPath + "DejaVuSans.ttf");
dejaVuSans = Font.createFont(Font.TRUETYPE_FONT, istream);
f = dejaVuSans.deriveFont(Font.PLAIN, 12);
} catch (Exception e) {
System.err.println(e.getMessage());
f = null;
}
if (f == null)
f = new Font("Dialog", Font.PLAIN, 12);
java.util.Enumeration keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource)
UIManager.put (key, f);
}
...
}
Of course, if DejaVuSans.ttf is not embedded in the jar file you can import it at runtime. See How do you import a font?.
Lucida Sans Regular is always bundled with Java but I don't think it will solve the problem that some text/labels go out of format. That depends also on the users's screen resulotion.
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.