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).
Asked
Active
Viewed 106 times
0
-
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 Answers
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
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...
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)
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.
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);
-
As suggested [here](http://stackoverflow.com/q/23975076/230513), use `TextLayout` for bounds. – trashgod Dec 21 '15 at 00:18