My JEditorPane automatically wraps words; I don't want that. All I want is a horizontal bar to appear that allows the user to write as much as desired. How can I do that? I have tried several methods. I have overridden the getScrollableTracksViewportWidth(), but that didn't help. Does any one know how I can turn off the word wrap?
A quick google search lead me to this page, which implements it by subclassing the text pane and overriding the getScrollableTracksViewportWidth() method:
// Override getScrollableTracksViewportWidth
// to preserve the full width of the text
public boolean getScrollableTracksViewportWidth() {
Component parent = getParent();
ComponentUI ui = getUI();
return parent != null ? (ui.getPreferredSize(this).width <= parent
.getSize().width) : true;
}
Try this
http://java-sl.com/wrap.html
If you can control the text which is going into, and you are using features of JEditorPane, you can mark the code via html, and use white-space:nowrap; stile property.
jEditorPane1.setContentType("text/html");
StringBuilder sb = new StringBuilder();
sb.append("<div style='");
if (!wordWrap.isSelected()) { //some checkbox
sb.append("white-space:nowrap;");
}
sb.append("font-family:\"Monospaced\">'");
sb.append("your very interesting long and full of spaces text");
/*be aware, more then one space in row will be replaced by single space
to avoid it you need to substitute by .
Also rememberer that \n have to be repalced by <br>
so filering like:
line = line.replaceAll("\n", "<br>\n"); //be aware, <br/> do not work
line = line.replaceAll(" ", " ");
line = line.replaceAll("\t", " ");
may be usefull.*/
sb.append("</div>");
jEditorPane1.settext(sb.toString()); //jeditor pane do not support addition/insertion of text in html mode
why don't you use a jTextField?
it's only one line.
Related
This is a problem I've been trying to deal with for a good hour now, so I figured I might as well ask this question. My goal/question is about the behaviour of the list supplied by pane.getChildren(). To explain better, here's a bit of example code.
VBox pane1 = new VBox();
Label label1 = new Label("a");
Label label2 = new Label("b");
pane1.getChildren().addAll(label1,label2);
System.out.println(pane1.getChildren().size());
for (int i=0; i<pane1.getChildren().size(); i++) {
System.out.println(i + pane1.getChildren().get(i).(??????????)
}
The list pane1.getChildren() is of a size 2, but the pane1.getChildren().get(i) doesn't allow me to use Label related methods (such as getText(), which is the one I'm interested in accessing). What exactly is happening here, why isn't pane1.getChildren().get(i) acknowledged as a Label?
Also worth adding, that if i run
for (int i=0; i<pane1.getChildren().size(); i++) {
System.out.println(i + pane1.getChildren().get(i).getClass().getName());
}
the console output says, that the name of the class is "javafx.scene.control.Label".
I'd love some clarification on this little problem, and thank you in advance!
Pane.getChildren() returns an ObservableList<Node>, so pane1.getChildren().get(i) has a compile-time type of Node, not Label.
It's not clear why you need to do this: you already have the references to the labels without iterating through the pane's list of children. So you can just do
Stream.of(label1, label2).map(Label::getText).forEach(text -> {
// whatever you need to do with the text...
});
If you really want to get this from the pane's children list, just do the obvious downcast:
for (Node n : pane1.getChildren()) {
String text = ((Label) n).getText();
// ...
}
or
pane1.getChildren().stream()
.map(Label.class::cast)
.map(Label::getText)
.forEach(text -> {
// whatever you need to do with text...
});
but of course this will not work (without extra checks) if you put something in the pane that is not a label.
If you need to downcast it can be done in a stream:
pane1.getChildren()
.stream()
.filter(Label.class::isInstance)
.map(Label.class::cast)
.forEach(label -> System.out.println(label.getText()));
This filters all children to just be labels, then maps them as such.
I want to change the text of selected text in JTextArea.
For example when i press button i want the selected text to be change (Original Text Selected - I want to replace like this when i press the button : Replace:Original Text Selected) this is what i am trying to do in my code,
String replacement = "Replace:" + messageBodyText.getSelectedText() ";
but i have no idea how to change only selected text i am trying to do something but i am changing entire text of JTextArea Hope you understood my question ?
Thanks to Hovercraft Full Of Eels he solved my problem this is my code for other people who are facing the same problem :
int start = messageBodyText.getSelectionStart();
int end = messageBodyText.getSelectionEnd();
StringBuilder strBuilder = new StringBuilder(messageBodyText.getText());
strBuilder.replace(start, end, "Replace:" + messageBodyText.getSelectedText() + ".");
messageBodyText.setText(strBuilder.toString());
textComponent.replaceSelection(newText);
JTextComponent (and thus JTextArea) has getSelectionStart() and getSelectionEnd() methods that will help you. Get your text from the JTextArea or its Document, and using these int values you can change your text and replace it into the text component.
For example,
int start = myTextField.getSelectionStart();
int end = myTextField.getSelectionEnd();
StringBuilder strBuilder = new StringBuilder(myTextField.getText());
strBuilder.replace(start, end, newText);
myTextField.setText(strBuilder.toString());
I am usign GWT2.3.
We developed CustomPager by overriding SimplePager.
We override createText() method such a way that we are showing string like "Page 1 of 4" using following code
public String createText() {
if(searchRecordCount%pageSizeForText == 0){
totalPages = searchRecordCount/pageSizeForText;
}else{
totalPages = (searchRecordCount/pageSizeForText) + 1;
}
NumberFormat formatter = NumberFormat.getFormat("#,###");
return "Page "+formatter.format(this.getPage()+1) + " of " + formatter.format(totalPages);
}
Now I want to use TextBox for CurrentPage so that user can enter page Number in textBox. (Functionality GoTo entered pageNumber)
createText() returns string so I cant user textBox ;) + Can't provide css
How can I do this ? Is there any way to solve this problem? Workaround if any or Sample code
There are two ways how to achieve this:
1.) Use HTML code to create a TextBox:
In the createText() function you can create the textbox manually by using HTML code (better use SafeHTML templates for avoiding XSS):
String textbox_str = "<input type='textbox' name='goto'>";
However you have to write code for handling the actual event (i.e. ChangeEvent) and call setPage() of your SimplePager using JSNI.
2.) Add TextBox widget to SimplePager and override constructor:
SimplePager is basically a Composite which adds ImageButtons in its constructor for the forward and backward links.
You can extend SimplePager add a TextBox and override the constructor to add the TextBox between the forward and backward ImageButtons.
I am looking for a way to put example text into a swing JTextField and have it grayed out. The example text should then disappear as soon as any thing is entered into that text field. Some what similar to what stackoverflow does when a user is posting a question with the title field.
I would like it if it was already a extended implementation of JTextField so that I can just drop it in as a simple replacement. Anything from swingx would work. I guess if there is not an easy way to do this my option will probably be to override the paint method of JTextField do something that way maybe.
Thanks
The Text Prompt class provides the required functionality without using a custom JTextField.
It allows you to specify a prompt that is displayed when the text field is empty. As soon as you type text the prompt is removed.
The prompt is actually a JLabel so you can customize the font, style, colour, transparency etc..:
JTextField tf7 = new JTextField(10);
TextPrompt tp7 = new TextPrompt("First Name", tf7);
tp7.setForeground( Color.RED );
Some examples of customizing the look of the prompt:
If you can use external librairies, the Swing components from Jide software have what you are looking for; it's called LabeledTextField (javadoc) and it's part of the JIDE Common Layer (Open Source Project) - which is free. It's doing what mklhmnn suggested.
How about initialize the text field with default text and give it a focus listener such that when focus is gained, if the text .equals the default text, call selectAll() on the JTextField.
Rather than overriding, put a value in the field and add a KeyListener that would remove the value when a key stroke is registered. Maybe also have it change the foreground.
You could wrap this up into your own custom JTextField class that would take the default text in a constructor.
private JLabel l;
JPromptTextField(String prompt) {
l = new JLabel(prompt, SwingConstants.CENTER);
l.setForeground(Color.GRAY);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.getText().length() == 0) {
// Reshape the label if needed, then paint
final Rectangle mine = this.getBounds();
final Rectangle its = l.getBounds();
boolean resized = (mine.width != its.width) || (mine.height != its.height);
boolean moved = (mine.x != its.x) || (mine.y != its.y);
if (resized || moved)
l.setBounds(mine);
l.paint(g);
}
}
You can't do that with a plain text field, but you can put a disabled JLabel on top of the JTextField and hide it if the text field gets the focus.
Do it like this:
Define the string with the initial text you like and set up your TextField:
String initialText = "Enter your initial text here";
jTextField1.setText(initialText);
Add a Focus Listener to your TextField, which selects the entire contents of the TextField if it still has the initial value. Anything you may type in will replace the entire contents, since it is selected.
jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
if (jTextField1.getText().equals(initialText)) {
jTextField1.selectAll();
}
}
});
A JTextArea's tab size can easily be set using setTabSize(int).
Is there a similar way to do it with a JEditorPane?
Right now, text with tabs in my pane looks like:
if (stuff){
more stuff;
}
And, I'd prefer a much smaller tab stop:
if (stuff){
more stuff;
}
As JEditorPane is designed to support different kinds of content types, it does not provide a way to specify a "tab size" directly, because the meaning of that should be defined by the content model.
However when you use a model that's a PlainDocument or one of its descendants, there is a "tabSizeAttribute" that provides what you are looking for.
Example:
JEditorPane pane = new JEditorPane(...);
...
Document doc = pane.getDocument();
if (doc instanceof PlainDocument) {
doc.putProperty(PlainDocument.tabSizeAttribute, 8);
}
...
From the Javadoc:
/**
* Name of the attribute that specifies the tab
* size for tabs contained in the content. The
* type for the value is Integer.
*/
public static final String tabSizeAttribute = "tabSize";
In case anyone's using a StyledDocument (The link on the other answer died)
You create a TabSet which is an array of TabStops. In my case I only cared about the 1st tab, and I wanted it 20px from the left, so this code worked for me:
StyleContext sc = StyleContext.getDefaultStyleContext();
TabSet tabs = new TabSet(new TabStop[] { new TabStop(20) });
AttributeSet paraSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabs);
pane.setParagraphAttributes(paraSet, false);
Took me a while to figure this out.
And decided to use TabStop's in a TabSet that have calculated width based on the font size.
This has to be reset when ever the font size changes (in the paint() method of the JEditPane).
Complicated stuff! :(