Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use multi languages in swing application

Tags:

java

swing

We can use several font styles in a swing application and can assign different font style for different swing text fields. But is there any way to configure one JTextField in java swing application to support multi languages. For example input is address.

12B "street name in other language"

JTextField field = new JTextField("example",30);
Font font = new Font("Courier", Font.BOLD,12);
field.setFont(font);

How can we achieve this? is there any font that support dual font style (English + French).

UPDATE AFTER FIRST ANSWER

Also need to send typed text into database and retrieve back with same format. So I think it is not possible to switch between font dynamically.

UPDATE 2

If we consider Microsoft word we can use multiple fonts in a single page. So there should be a algorithm to save typed letters with respective font. how can we make this kind of behavior in swing without making two text fields for different language inputs.

enter image description here

like image 928
Buru Avatar asked Jul 14 '15 11:07

Buru


1 Answers

You can mix fonts by using HTML tags if you change the component to a JTextPane. The code below will create a field containing the text "Hello world" with font Times New Roman for "Hello" and Courier for "World!":

JTextPane field = new JTextPane();
field.setContentType("text/html");
field.setText("<html><font face=\"Times New Roman\">Hello</font> <font face=\"Courier\">world!</font></html>");

Here is a runnable example:

public static void main(String[] args) throws InterruptedException {
    MultiFontField text = new MultiFontField();
    JFrame frame = new JFrame();

    text.appendText("Hello ", "Times New Roman").appendText("world!", "Courier").finaliseText();

    frame.add(text);
    frame.setSize(200, 50);     
    frame.setVisible(true);
}

Here is the MultiFontField class:

public class MultiFontField extends JTextPane {

    private StringBuilder content;

    public MultiFontField() {
        super();
        this.content = new StringBuilder("<html>");
        this.setContentType("text/html");
    }

    public MultiFontField appendText(String text, String font) {
        content.append("<font face=\"").append(font).append("\">").append(text).append("</font>");
        return this;
    }

    public void finaliseText() {
        this.setText(content.append("</html>").toString());
    }
}
like image 138
Ian2thedv Avatar answered Oct 22 '22 06:10

Ian2thedv