L'idea e' questa, il codice e' lungi dall'esser perfetto pero'.
codice:
import java.awt.*;
import javax.swing.*;
/**
* @author Simone
*/
public class FractionLabel extends JLabel {
private String numeratore;
private String denominatore;
public final static int OFFSET = 5;
int width, height, numW, denW;
public FractionLabel(String num, String den) {
this.numeratore = num;
this.denominatore = den;
FontMetrics fm = this.getFontMetrics(this.getFont());
numW = fm.stringWidth(numeratore);
denW = fm.stringWidth(denominatore);
if(numW<denW) {
width = denW;
} else {
width = numW;
}
height = fm.getHeight();
this.setPreferredSize(new Dimension(width+(OFFSET*2), (height*2)+(OFFSET*3)));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int numOff = (int)((width/2.0f)-(numW/2.0f));
int denOff = (int)((width/2.0f)-(denW/2.0f));
g.drawString(numeratore, OFFSET+numOff, OFFSET+height);
g.drawLine(OFFSET+0, height+(OFFSET*2), OFFSET+width, height+(OFFSET*2));
g.drawString(denominatore, OFFSET+denOff, (height*2)+(OFFSET*2));
}
public String getDenominatore() {
return this.denominatore;
}
public String getNumeratore() {
return this.denominatore;
}
public static void main(String[] args) {
JFrame f = new JFrame("test");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setSize(200,200);
FractionLabel label = new FractionLabel("2+2", "2");
label.setOpaque(true);
label.setBackground(Color.YELLOW);
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JPanel p = new JPanel();
p.add(label);
f.add(p);
f.setVisible(true);
}
}