How do I add text to a JTextArea? - java

I'm making a java Text Editior and I can't seems to know how to insert a line of text that is "[code][/code]" Here is what I'm trying to program. The method for the inserting is called "insert". So it has to be something that is insert,(something that inserts strings of text in JTextArea)
/////////////////// CODE //////////////////////////////////////////////////////////////////////////////////////////////////
this.insert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
/////////////// END OF CODE ///////////////////////////////////////////////////////////////////

Simple example to set/assign text to JTextArea .. this is not the solution but it will help you...
JTextArea textArea = new JTextArea(
"This is an editable JTextArea. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
Although to set the text .. use this method
void insert(String str, int pos)
Inserts the specified text at the specified position.
public void setText(String t)
Sets the text of JTextArea
For refrerence and help please follow jtextareaguide
Link to video tutorial
Guide for Simple Editor in Java

Java already provides a method for inserting text in the JTextArea class. Try this...
JTextArea t = new JTextArea();
t.setText("specified string");
t.append("+ added string");

use:
JTextArea text=new JTextArea();
text.setText("Message..");
Here is a doc.
public class JTextArea extends JTextComponent
A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java.awt.TextArea class where it can reasonably do so. You can find information and examples of using all the text components in Using Text Components, a section in The Java Tutorial.

Try this:
JTextArea textj1 = new JTextArea();
textj1.setText(textj1.getText().trim() + "a string or even an arraylist");

Better using:
textArea.setText(textArea.getText()+" Message");

Related

Space under JTextPane text when using .setText method

I am using MigLayout 3.5.5, as the newer updates are not compatible with my older code.
Problem
When setting text to a JTextPane in a MigLayout, the JTextPane will take double the space (according to font size) IF the text I am setting the JTextPane contains space characters. It does not happen all the time, but in the specific program I am making, it happens frequently.
The program's goal is to present information in a letter-by-letter basis, so there is a button that updates the text to the next letter. However, the text bounces around, because the JTextPane is sometimes occupying more space than usual. I identified a certain pattern to the height differences.
Pattern
A new line indicates that I added a letter.
"|" represents a space character in the text.
"Space" means JTextPane is taking double the space.
Full String: "The quick brown fox jumps over the lazy dog."
T
Th
The
The|
The|q (Space)
The|qu
The|qui (Space)
The|quic
The|quick (Space)
The|quick|
Note: I stopped the pattern here, because from this point on (starting with The|quick|b), every single letter addition resulted in the JTextPane occupying double its height.
I've already tried printing out the letter-by-letter text to the console to see if there were any new line characters within the text being added, but to no avail. I also thought it might be a problem with the automatic wrapping of the JTextPane, but the text I inserted isn't quite long enough to wrap in the JFrame's size.
Here is a short example to reproduce the behavior:
public class MainFrame extends JFrame {
int currentLetter = 1;
final String FULL_TEXT = "The quick brown fox jumps over the lazy dog.";
JTextPane text;
JButton addLetter;
MainFrame() {
setSize(500, 500);
setLayout(new MigLayout("align center, ins 0, gap 0"));
addElements();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MainFrame application = new MainFrame();
}
});
}
private void addElements() {
text = new JTextPane();
text.setEditable(false);
text.setFont(new Font("Times New Roman", Font.BOLD, 19));
text.setForeground(Color.WHITE);
text.setBackground(Color.BLACK);
add(text, "alignx center, wmax 80%, gapbottom 5%");
addLetter = new JButton("Add Letter");
addLetter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (currentLetter != FULL_TEXT.length()) {
currentLetter++;
updateText();
}
}
});
add(addLetter, "newline, alignx center");
updateText();
}
private void updateText() {
String partialText = new String();
for (int letter = 0; letter < currentLetter; letter++) {
partialText += FULL_TEXT.toCharArray()[letter];
}
text.setText(partialText);
}
}
Why am I using JTextPane?
I tried using JLabel for this task, and it worked well... until the text was long enough to wrap. Then, when I used HTML within the JLabel text to wrap it, every time I updated the text, it would take time for the HTML to render and result in some pretty nasty visual effects.
Next, I tried JTextArea to disguise it as a JLabel, since it not only has line wrapping, but word wrapping as well. It was a great solution, until I found out that I couldn't use a center paragraph alignment in a JTextArea.
So I settled for a JTextPane, which will work well if only I got rid of the extra space at the bottom of it.
Thanks in advance for your help!
The solution is to append text by using the insertString() method on the StyledDocument of the JTextPane instead of using setText() on the JTextPane itself.
For example, instead doing this every time:
JTextPane panel = new JTextPane();
panel.setText(panel.getText() + "test");
You should do this:
JTextPane panel = new JTextPane();
StyledDocument document = panel.getStyledDocument();
document.insertString(document.getLength(), "test", null);
And of course you need to catch the BadLocationException.
Then the space disappears. Here's the question where I found my answer to the rendering problem: JTextPane appending a new string
The answers to those questions don't address the problem with the space, but they do show the correct way to edit text in the JTextPane.

How to change a String in a JTextArea - Java

I'm about to make a program where if you click a button it will show some text... But i don't know how to change the string after i have set the string. Here is the code i have right now.
//Text Area to "Copy"
String output = "";
JTextArea TArea = new JTextArea(output);
TArea.setBounds(200, 72, 177, 296);
panel.add(TArea);
//When press the button "Generate"
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
String output = "Hello World";
TArea.setBounds(200, 72, 177, 296);
}
});
Hope you can help me :)
But i don't know how to change the string after i have set the string
textArea.setText(...);
will reset the text
textArea.append(...);
will add text to the end of the text area.
Other thoughts:
I suggest you read the Swing Tutorial for the basics of using Swing.
Don't use setBounds(..). Swing was designed to be used with layout managers. The tutorial has plenty of examples of using the layout managers.
Variable names should NOT start with an upper case character. Follow Java conventions and don't make up your own. Any tutorial or text book will follow the conventions.

Adding text next to a textfield to describe what data the user is expected to enter into it

I am trying to create a simple GUI that simulates a record store. I am still in the beginning stages.
I am running into trouble when I try to add text to describe what the user is expected to enter in the text field.
In addition, I am also having trouble positioning every textfield on its own line. In other words if there is space for two textfields in one line, then it displays in one line, and I am trying to display every text field on its own line.
This is what I tried so far:
item2 = new JTextField("sample text");
However the code above just adds default text within the text field, which is not what I need :/
I appreciate all the help in advance.
public class MyClass extends JFrame{
private JTextField item1;
private JTextField item2;
public MyClass(){
super("Matt's World of Music");
setLayout(new FlowLayout());
item1 = new JTextField();
item2 = new JTextField();
add(item1);
add(item2);
thehandler handler = new thehandler();
item1.addActionListener(handler);
item2.addActionListener(handler);
}
}
For your first problem, you need to use a JLabel to display your text. The constructor is like this:
JLabel label = new JLabel("Your text here");
Works really well in GUI.
As for getting things on their own lines, I recommend a GridLayout. Easy to use.
In your constructor, before adding anything, you do:
setLayout(new GridLayout(rows,columns,x_spacing,y_spacing));
x_spacing and y_spacing are both integers that determine the space between elements horizontally and vertically.
Then add like you have done. Fiddle around with it and you'll get it worked out.
So your final would look like:
setLayout(new GridLayout(2,2,10,10));
add(new JLabel("Text 1"));
add(text1);
add(new JLabel("text 2"));
add(text2);
You could just use a JLabel to label your textfields.
JLabel label1 = new JLabel("Item 1: ");
add(label1);
add(item1);
If you really want text inside the fields, you could set the text in the field with the constructor, and then add a MouseListener to clear the text on click:
item1 = new JTextField("Text");
item1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (item1.getText().equals("Text")) // User has not entered text yet
item1.setText("");
}
});
Or, (probably better) use a FocusListener:
item1 = new JTextField("Text");
item1.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
if (item1.getText().equals("Text")) // User has not entered text yet
item1.setText("");
}
public void focusLost(FocusEvent e) {
if (item1.getText().equals("")) // User did not enter text
item1.setText("Text");
}
});
As for layout, to force a separate line, you use use a Box.
Box itemBox = Box.createVerticalBox();
itemBox.add(item1);
itemBox.add(item2);
add(itemBox);
Make:
item1 = new JTextField(10);
item2 = new JTextField(10);
that should solve problem with width of JTextField.
For beginning use GridLayout to display JTextField in one line. After that I strongly recomend using of MIG Layout http://www.migcalendar.com/miglayout/whitepaper.html.
put JLabel next to JTextField to describe what the user is expected to enter in the text field.
JLabel lbl = new JLabel("Description");
or you could also consider using of toolTipText:
item1.setToolTipText("This is description");
For making a form in Java Swing, I always recommend the FormLayout of JGoodies, which is designed to ... create forms. The links contains an example code snippet, which I just copy-pasted here to illustrate how easy it is:
public JComponent buildContent() {
FormLayout layout = new FormLayout(
"$label, $label-component-gap, [100dlu, pref]",
"p, $lg, p, $lg, p");
PanelBuilder builder = new PanelBuilder(layout);
builder.addLabel("&Title:", CC.xy(1, 1));
builder.add(titleField, CC.xy(3, 1));
builder.addLabel("&Author:", CC.xy(1, 3));
builder.add(auhtorField, CC.xy(3, 3));
builder.addLabel("&Price:", CC.xy(1, 5));
builder.add(priceField, CC.xy(3, 5));
return builder.getPanel();
}
Now for the description:
Use a label in front of the textfield to give a very short description
You can put a longer description in the textfield as suggested by #Alden. However, if the textfield is for short input, nobody will be able to read the description
You can use a tooltip (JComponent#setTooltipText) to put a longer description. Those tooltips also accept basic html which allows some formatting. Drawback of the tooltips is that the user of your application has to 'discover' that feature as there is no clear indication those are available
You can put a "help-icon" (like e.g. a question mark) after each text field (use a JButton with only an icon) where on click you show a dialog with a description (e.g. by using the JOptionPane class)
You can put one "help-icon" on each form which shows a dialog with a description for all fields.
Note for the dialog suggestion: I wouldn't make it a model one, allowing users to open the dialog and leave it open until they are finished filling in the form

JTextArea won't update java

I'm trying to update a JTextArea using the .append. I'm sending in a string to the method from another class and I know the textBox method gets the string as I can use .println to test it. The only thing is it does not update the JTextArea which is strange as when I first start the program and the gui is being created i'm able to update it.
public void textBox (String text){
textArea.append(text);
}
Does anyone have any ideas? Many thanks in advance.
Try using textArea.append(text + "\n");
I too had the same problem . I solved it by adding a "\n" at the end
JTextArea textArea = new JTextArea(text);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
String appendText = "jumps over the lazy dog.";
textArea.append(appendText);

Java swing: Multiline labels? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Multiline text in JLabel
I want to do this:
JLabel myLabel = new JLabel();
myLabel.setText("This is\na multi-line string");
Currently this results in a label that displays
This isa multi-line string
I want it to do this instead:
This is
a multi-line string
Any suggestions?
Thank you
EDIT: Implemented solution
In body of method:
myLabel.setText(convertToMultiline("This is\na multi-line string"));
Helper method:
public static String convertToMultiline(String orig)
{
return "<html>" + orig.replaceAll("\n", "<br>");
}
You can use HTML in JLabels. To use it, your text has to start with <html>.
Set your text to "<html>This is<br>a multi-line string" and it should work.
See Swing Tutorial: JLabel and Multiline label (HTML) for more information.
public class JMultilineLabel extends JTextArea{
private static final long serialVersionUID = 1L;
public JMultilineLabel(String text){
super(text); // According to Mr. Polywhirl, this might improve it -> text + System.lineSeparator()
setEditable(false);
setCursor(null);
setOpaque(false);
setFocusable(false);
setFont(UIManager.getFont("Label.font"));
setWrapStyleWord(true);
setLineWrap(true);
//According to Mariana this might improve it
setBorder(new EmptyBorder(5, 5, 5, 5));
setAlignmentY(JLabel.CENTER_ALIGNMENT);
}
}
It totally looks the same for me, but its ugly
Another easy way (but changes the text style a bit) is to use a <pre></pre> html block.
This will persist any formatting the user entered if the string you are using came from a user input box.
Example:
JLabel label = new JLabel("<html><pre>First Line\nSecond Line</pre></html>");
The direct procedure of writing a multi-line text in a jlabel is:
JLabel label = new JLabel("<html>First Line<br>Second Line</html>");
The problem with using html in JLabel or any Swing component is that you then have to style it as html, not with the usual setFont, setForeground, etc. If you're ok with that, fine.
Otherwise you can use something like MultilineLabel from JIDE, which extends JTextArea. It's part of their open source Commom Layer.
JLabel can accept html code. Maybe you can try to use the <br> tag.
Example:
JLabel myLabel = new JLabel();
myLabel.setText("<html> This is a <br> multi-line string </html>");
http://java.sun.com/docs/books/tutorial/uiswing/components/html.html

Categories

Resources