I had a problem with editing labels
, which was fixed using JTextPane
.
Would the problem be the way I tried to use the component method? :
campo.setText(campo.formatar("Texto", "" + string, 0)); //aplicar o método do componente
I tried to do it as follows:
import java.awt.Color;
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class JTextPaneExample {
private String string = "10";
public void createAndShowGUI() {
JFrame f = new JFrame("JTextPaneExample");
MeuCampoJTextPane campo = new MeuCampoJTextPane();
f.getContentPane().add(new JScrollPane(campo));
campo.setText(campo.formatar("Texto", "" + string, 0)); //aplicar o método do componente
f.setSize(400, 300);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new JTextPaneExample().createAndShowGUI();
});
}
}
class MeuCampoJTextPane extends JTextPane {
// cria um StyleContext e um Document para o jtextpane
StyleContext sc = new StyleContext();
final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
// cria um estilo e adiciona atributos personalizados nele
final Style redStyle = sc.addStyle("RED", null);
final Style blueStyle = sc.addStyle("BLUE", null);
public MeuCampoJTextPane() {
this.setEditable(false);
}
public String formatar(String texto, String valor, int tipo) {
String stringFormatada = "";
try {
switch (tipo) {
case 0:
blueStyle.addAttribute(StyleConstants.Foreground, Color.blue);
blueStyle.addAttribute(StyleConstants.FontSize, 14);
blueStyle.addAttribute(StyleConstants.Bold, true);
doc.insertString(0, texto, blueStyle);
DecimalFormat formatoDecimal2 = new DecimalFormat("## 00");
String d2 = formatoDecimal2.format(Float.valueOf(valor));
redStyle.addAttribute(StyleConstants.Foreground, Color.red);
redStyle.addAttribute(StyleConstants.FontSize, 12);
doc.insertString(this.getText().length(), d2, redStyle);
stringFormatada = d2;
break;
case 1:
break;
default:
break;
}
return stringFormatada;
} catch (Exception e) {
}
return "";
}
}