I have a JTextArea in which i want to display messages aligned to right or left, depending on a variable I pass along with the message. Can I do that?
What did I do wrong? Nothing gers added to the text pane when i run my GUI
battleLog = new JTextPane();
StyledDocument bL = battleLog.getStyledDocument();
SimpleAttributeSet r = new SimpleAttributeSet();
StyleConstants.setAlignment(r, StyleConstants.ALIGN_RIGHT);
try {
bL.insertString(bL.getLength(), "test", r);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
Not with a JTextArea.
You need to use a JTextPane which supports different text and paragraph attributes. An example to CENTER the text:
JTextPane textPane = new JTextPane();
textPane.setText("Line1");
StyledDocument doc = textPane.getStyledDocument();
// Define the attribute you want for the line of text
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
// Add some text to the end of the Document
try
{
int length = doc.getLength();
doc.insertString(doc.getLength(), "\ntest", null);
doc.setParagraphAttributes(length+1, 1, center, false);
}
catch(Exception e) { System.out.println(e);}
if("left".equals(input)){
setAlignmentX(Component.LEFT_ALIGNMENT);
}
Have a try!
Related
I have come across various solutions to changing the margins when printing in Java but none seem to work. Here and Here.
What I have so far is,
TextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Define a keyword attribute
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setBold(keyWord, true);
Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(qrcode));
doc.insertString(0, "Title Here\n", null );
doc.insertString(doc.getLength(), "Ignored", style);
textPane.print();
When using the inbuilt print method the margins are set to default as 25.4mm. I'd like to be able to edit these margins while still being able to have a print dialog.
What I "can" verify is, something like this will effect the page size and margins of the output
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
// Define a keyword attribute
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setBold(keyWord, true);
Style style = doc.addStyle("StyleName", null);
//StyleConstants.setIcon(style, new ImageIcon(qrcode));
doc.insertString(0, "Title Here\n", null);
doc.insertString(doc.getLength(), "Ignored", style);
Paper paper = new Paper();
paper.setSize(fromCMToPPI(21.0), fromCMToPPI(29.7)); // A4
paper.setImageableArea(fromCMToPPI(5.0), fromCMToPPI(5.0),
fromCMToPPI(21.0) - fromCMToPPI(10.0), fromCMToPPI(29.7) - fromCMToPPI(10.0));
PageFormat pageFormat = new PageFormat();
pageFormat.setPaper(paper);
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(textPane.getPrintable(null, null), pageFormat);
PageFormat pf = pj.pageDialog(pageFormat);
if (pj.printDialog()) {
pj.print();
}
Normal output vs modified output (border added after to highlight change)
And the conversation methods...
protected static double fromCMToPPI(double cm) {
return toPPI(cm * 0.393700787);
}
protected static double toPPI(double inch) {
return inch * 72d;
}
What I can't verify is if those values appear in either page setup or printer dialogs, as MacOS has decided I don't need to see them :/
From previous experience on Windows, I seem to remember it working
I tired from search the solution for this: i want to align text pane from left to right however but drag and drop java this is last code i written :
` StyledDocument doc = txtio.getStyledDocument();
Style style = txtio.addStyle("right",null);
StyleConstants . setAlignment (style, StyleConstants .ALIGN_RIGHT);
try {
doc.insertString(0,txtio.getSelectedText(), style);
}
catch (BadLocationException ex) {
Logger . getLogger ( mswordframe.class.getName() ).log(Level.SEVERE,null, ex);
}
txtio.setStyledDocument(doc);`
txtio : is the name of text pane;
it doesn't work ,
Sorry i am weak in english
JTextPane supports character and paragraph attributes. Character attributes are for pieces of text and paragraph attributes are for a whole line of text.
Alignment of text is a paragraph attribute because you can't have part of the text center aligned and part right aligned for the same line of text.
Try the following:
SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setForeground(green, Color.GREEN);
SimpleAttributeSet right = new SimpleAttributeSet();
StyleConstants.setAlignment(right, StyleConstants.ALIGN_RIGHT);
try
{
doc.insertString(0, txtio.getSelectedText(), green);
doc.setParagraphAttributes(0, 1, right, false);
}
catch(Exception e) {}
I want to add a global AttributeSet to my JTextPane.
I found this:
SimpleAttributeSet style = new SimpleAttributeSet();
StyleConstants.setLeftIndent(style, 20);
StyleConstants.setFirstLineIndent(style, -20);
From http://java-sl.com/tip_hanging_first_line.html
I'm wondering how I can set the "default stylesheet"? (not using HTML). I then tried this:
StyleContext style = new StyleContext();
Style s = style.addStyle("test", null);
StyleConstants.setForeground(s, Color.BLUE);
StyledDocument d = (StyledDocument) console.getOutputField().getDocument();
From http://www.java2s.com/Code/Java/Swing-JFC/JTextPaneStylesExample1.htm without luck.
I know StyledDocument has specific properties for setting stuff like foreground colour - which is why this may not work - but can anyone point me as to how to use the other style attributes? Such as the left indent and first line indent.
JTextPane textPane = new JTextPane();
StyledDocument doc = textPane.getStyledDocument();
SimpleAttributeSet style = new SimpleAttributeSet();
StyleConstants.setLeftIndent(style, 20);
StyleConstants.setFirstLineIndent(style, -20);
StyleConstants.setForeground(style, Color.BLUE);
doc.setParagraphAttributes(0, doc.getLength(), style, true);
Is there a way in Java Swing to show text in small caps (small capitals)?
http://en.wikipedia.org/wiki/Small_caps
I have loaded a custom font which supports small caps via Font.createFont(). The text should be rendered somehow in small caps. Is this possible in JLabel, JTextPane or some other component?
You can try that, it works : (I get the font here for test : http://www.fonts101.com/fonts/view/Uncategorized/28374/Tahoma_Small_Cap.aspx)
String labelText ="Dfd";
JLabel lbl = new JLabel(labelText);
Font g=null;
Font g2=null;
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("/home/alain/Bureau/tahomscb/tahomscb.ttf"));
g = Font.createFont(Font.TRUETYPE_FONT, myStream);
g2 = g.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("font not loaded.");
}
lbl.setFont(g2);
this.add(lbl); //this is the parent component
This question already has answers here:
Multiline text in JLabel
(11 answers)
Closed 8 years ago.
I want JLabel text in multiline format otherwise text will be too long. How can we do this in Java?
If you don't mind wrapping your label text in an html tag, the JLabel will automatically word wrap it when its container's width is too narrow to hold it all. For example try adding this to a GUI and then resize the GUI to be too narrow - it will wrap:
new JLabel("<html>This is a really long line that I want to wrap around.</html>");
I recommend creating your own custom component that emulates the JLabel style while wrapping:
import javax.swing.JTextArea;
public class TextNote extends JTextArea {
public TextNote(String text) {
super(text);
setBackground(null);
setEditable(false);
setBorder(null);
setLineWrap(true);
setWrapStyleWord(true);
setFocusable(false);
}
}
Then you just have to call:
new TextNote("Here is multiline content.");
Make sure that you set the amount of rows (textNote.setRows(2)) if you want to pack() to calculate the height of the parent component correctly.
I suggest to use a JTextArea instead of a JLabel
and on your JTextArea you can use the method .setWrapStyleWord(true) to change line at the end of a word.
It is possible to use (basic) CSS in the HTML.
MultiLine Label with auto adjust height.
Wrap text in Label
private void wrapLabelText(JLabel label, String text) {
FontMetrics fm = label.getFontMetrics(label.getFont());
PlainDocument doc = new PlainDocument();
Segment segment = new Segment();
try {
doc.insertString(0, text, null);
} catch (BadLocationException e) {
}
StringBuffer sb = new StringBuffer("<html>");
int noOfLine = 0;
for (int i = 0; i < text.length();) {
try {
doc.getText(i, text.length() - i, segment);
} catch (BadLocationException e) {
throw new Error("Can't get line text");
}
int breakpoint = Utilities.getBreakLocation(segment, fm, 0, this.width - pointerSignWidth - insets.left - insets.right, null, 0);
sb.append(text.substring(i, i + breakpoint));
sb.append("<br/>");
i += breakpoint;
noOfLine++;
}
sb.append("</html>");
label.setText(sb.toString());
labelHeight = noOfLine * fm.getHeight();
setSize();
}
Thanks,
Jignesh Gothadiya