0

How is it possible to make an output in Java in Swing in JLabel with a string, where there are symbols with indexes and powers? For example: output of x^2 (x*x).

Jan
  • 13,738
  • 3
  • 30
  • 55
Cambronnes
  • 47
  • 4
  • You try using unicodes for the characters. You could look up the font table for the font your are using to see if it has those characters. You might be able to use superscript capabilities of HTML – MadProgrammer Dec 20 '15 at 20:40

3 Answers3

7

Wild guess - you want to make the display look nice. Well then:

Swing Components can display (limited) HTML. So this actually works:

JLabel label = new JLabel("<html>a<sup>2</sup> * x<sub>2</sub> + x<sub>3</sub>");
JOptionPane.showMessageDialog(null, label);

will create a display like

shown dialog

Use

  • <sup> for superscript or
  • <sub> for subscript
Jan
  • 13,738
  • 3
  • 30
  • 55
5

You could...

Make use of JLabel's HTML support and use <sup> (superscript), for example...

Superscript

public class TestPane extends JPanel {

    public TestPane() {
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        add(new JLabel("<html>2<sup>*</sup>2"), gbc);
        add(new JLabel("<html>2<sup>^</sup>2"), gbc);
    }

}

You could...

Make use of the unicode support (assuming your font supports it)

Unicode

public class TestPane extends JPanel {

    public TestPane() {
        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        add(new JLabel("2\u00B2"), gbc);
    }

}

Have a look at Unicode character table for more suggestions

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
4

Also consider an AttributedString in your own JComponent, illustrated here and here.

image

JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        String s = "ax [m/s2]";
        AttributedString as = new AttributedString(s);
        as.addAttribute(TextAttribute.SIZE, 24, 0, 2);
        as.addAttribute(TextAttribute.SIZE, 16, 3, 9);
        as.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, 0, 2);
        as.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUB, 1, 2);
        as.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 7, 8);
        g.drawString(as.getIterator(), 12, 32);
    }
});
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045