alignment using StyledDocument in drag and drop java - java

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) {}

Related

Changing print margins on JTextPane

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

Highlighting keywords in JTextArea (Netbeans)

I'm using a text area in Netbeans(Java), and I want to highlight certain keywords in the text, something like syntax-highlighting in programming. How could I do that but within a JTextArea in Netbeans?
You can't use a JTextArea to highlight individual pieces of text.
I would suggest a JTextPane so you can use styled attributes.
The basic code would be something like:
JTextPane textPane = new JTextPane();
textPane.setText( "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight" );
StyledDocument doc = textPane.getStyledDocument();
// Define a keyword attribute
SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
// Change attributes on some text
doc.setCharacterAttributes(0, 5, keyWord, false);

JEditorPane HTMLDocument adds p-implied into HTML unnecessarily when setCharacterAttributes called

I am creating an editor using JEditorPane, HTMLDocument and HTMLEditorKit. I have a toolbar which has various components to change style attributes of the editor. One of them is a JComboBox to change the ZOOM_FACTOR attribute. The code below is the code that executes when that JComboBox 's value changes.
final SimpleAttributeSet attrs = new SimpleAttributeSet();
zoomCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = (String) zoomCombo.getSelectedItem();
s = s.substring(1, s.length());
double scale = new Double(s).doubleValue() / 100;
editorPane.getDocument().putProperty("ZOOM_FACTOR", new Double(scale));
try {
StyledDocument doc = (StyledDocument) editorPane.getDocument();
doc.setCharacterAttributes(0, 1, attrs, true);
doc.insertString(0, "", null); // refresh
} catch (Exception ex) {
logger.error("Hata", ex);
}
}
});
doc.setCharacterAttributes(0, 1, attrs, true); is the line where root of my problem starts. After this line of code executes, <p-implied> is added into the <head></head> part of the HTML text in the JEditorPane.getText. And after this happens, if some certain pattern of events occur my HTML text gets corrupted. Is there any way how not to create <p-implied> along? If not so what could be the best workaround for this problem?
PS : There is something old reported here in the JDK Bug System. It is reported for a different reason, but it is shown there also, that the same <p-implied> is being added into <head></head> afterwards. I know the problem reported in this link uses JTextPane (a subclass of JEditorPane) and setCharacterAttributes method in the JTextPane class but that method also calls same setCharacterAttributes method I used inside itself.
You use 0 position, but for HTMLDocument the positions belong to HEAD (not BODY) section.
Looks like you use it just to refresh the content. You can apply the same code for the end of the document.
doc.setCharacterAttributes(doc.getLength(), 1, attrs, true);
Thus the attribute change event is applied to the BODY.

How to set different JTextArea text alignment per line?

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!

Convert url of image to actual image when opening document

When I open up my file in my text editor. I am only getting the file's location in the text pane. Am I making a simple mistake somewhere or is there a better way to do this? Should I use an ArrayList to store the images locations?
Example of what is happening: I have a file that has two lines...
C:\...\pic.png
(picture description)
When I try to open up the file (after I save it in the text editor) it shows the actual location of the picture. I want to be able to use BufferedImage to get the directory and add the image to the JTextPane. Otherwise (if the text isn't a location), simply add the text to the text pane.
FYI: textArea is of type JTextPane
Code that opens my file
// sb is my StringBuffer
try
{
b = new BufferedReader(new FileReader(filename));
String line;
while((line=b.readLine())!=null)
{
if (line.contains("C:\\...\\Pictures\\"))
{
BufferedImage image = ImageIO.read(new File(line));
ImageIcon selectedPicture = new ImageIcon(image);
textArea.insertIcon(selectedPicture);
}
sb.append(line + "\n");
textArea.setText(sb.toString());
}
b.close();
}
If you have any questions about this code or need clarification, don't hesitate to ask.
OK. The way you are setting content on to the JTextPane is incorrect.
The basic trick is to get StyleDocument out of the JTextPane and then set a Style on the document. A style basically explains how the component needs to be rendered. For example, text formatting, image icons, spacing etc.
Given that following code will get you started.
JTextPane textPane = new JTextPane();
try {
BufferedReader b = new BufferedReader(
new FileReader("inputfile.txt"));
String line;
StyledDocument doc = (StyledDocument) textPane.getDocument();
while ((line = b.readLine()) != null) {
if (line.contains("/home/user/pictures")) {
Style style = doc.addStyle("StyleName", null);
StyleConstants.setIcon(style, new ImageIcon(line));
doc.insertString(doc.getLength(), "ignore", style);
} else {
Style textStyle = doc.addStyle("StyleName", null);
//work on textStyle object to get required color/formatting.
doc.insertString(doc.getLength(), "\n" + line, textStyle);
}
}
b.close();
} catch (Exception e) {
e.printStackTrace();
}

Categories