How to change a String in a JTextArea - Java - 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.

Related

Writing with bold in Java using Swing

I'm writing a text editor in Java, using Swing. My main component that I use to enter the text is JTextPane. I know how to bold selected text, but I'd also like just to press bold and have new text formatted. Here's my code:
static void boldSelection(JTextPane editor, JButton button){
StyledDocument doc = (StyledDocument) editor.getDocument();
int selectionEnd = editor.getSelectionEnd();
int selectionStart = editor.getSelectionStart();
if (selectionStart == selectionEnd) {
return;
}
Element element = doc.getCharacterElement(selectionStart);
AttributeSet as = element.getAttributes();
MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
doc.setCharacterAttributes(selectionStart, editor.getSelectedText().length(), asNew, true);
}
It works, but I have no idea how to change it, since I have to pass the length to setCharacterAttributes.
To be clear:
that's what I have:
Bolding selected text
and that's what I want to do:
Entering bolded text
The EditorKit used by the JTextPane supports a Bold Action along with other common actions the might be used by an editor. So you don't need to write any special code, only create a Swing component to use the Action.
Check out the section from the Swing tutorial on Text Component Features for a working example.
The tutorial example only use menu items but you can also use the Action to create a JButton to add to a JToolBar.

Get Text from Text Area and Set it BOLD on Label

I'm basically just trying to get text from a text area and then display it on a Label in Bold format. Any suggestions? This is what the code looks like, but obviously it's not correct.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String sInput = TF_INPUT.getText();
TA_OUTPUT.setText(Font.Bold,sInput);
}
Don't guess at what methods to call or how and what parameters to pass in -- that's what the Java API is for -- to tell exactly what's available. If you did this and looked up JLabel, you'll see that it has a setFont(...) method that it gains from its JComponent parent and which you can and should use to set the font. Then look up Font to see what constructors are available (I often use the String, int, int constructor). So it could be something like:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String sInput = tfInput.getText();
taOutput.setText(sInput);
taOutput.setFont(new Font(Font.DIALOG, Font.BOLD, 24));
}
Also you can re-use a component's font by calling getFont() on it and then deriveFont(...) on the Font to make it bold or change its size.
Actually, JLabel supports HTML. So everything you need to do is wrap your text in <b> tags.

How do I add text to a JTextArea?

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");

JOptionPane using one window for input and output

So I'm working on a little project and I'm looking for the base code for how to do this in JOptionPane. I'm still really new to this side of Java. I'm not looking for a whole lot, I just didn't know where to start.
The program should populate the screen with a JOptionPane window. I need it to be modeled like the picture below. The bottom row is a text input from the user and when they hit the enter key, the text should "refresh/clear" and then the middle string area should populate with both the user input and then just below it the result of an if statement according the the code.
for example: The user enters in: "Hello".
Then the text input should refresh and the grey box should do this: "User: Hello."
"Computer: Hello user".
I would really appreciate any and all help on this.
You don't System.out.println() into a gui component. Doesn't work like this. You can write a console program and use JOptionPanes to get user input, but the output would be used in the console program. You would need to create a gui program mimic a console.
Here's a basic layout to start you off
public class Game extends JFrame {
JTextArea jta = new JTextArea(10, 30);
JTextField jtf = new JTextField(30);
public Game(){
add(jtf, BorderLayout.SOUTH);
add(jta, BorderLayour.CENTER);
jta.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
JFrame frame = new Game();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
}
What I would suggest is since this is a very basic program, I would use an array of String commands and iterate through them.
For example:
String[] question = {"Do you want to go to school?",
"Do you want to drive or walk?"};
jta.setText(questions[0]);
Then in your actionPerformed get the answer from the text field. Use an if statement like
if (jtf.getText().equals("yes") {
jta.append(questions[1]);
}
And so on. If you have no idea what I'm talking about, I would really consider using the Swing tutorials I mentioned. There's a lot of info in those tutorials.

Simple way to have a hybrid JTextField / JPasswordField?

I am developing a simple applet that has a simpe sign-in interface.
And to be concise in space, I have two JTextFields for username and password, which I also use as labels. i.e. to start with, the username JTextField will be pre-filled with grey text saying "username" and the password JTextField pre-filled with "simple password".
Then as soon as the JTextField gets focus, i clear the prefill text and set the text color to black. Similar to stackoverflow's search box, but in swing.
Now for security, I would like to mask the password field when the password JTextField gets focus (but of course still have the pre-filled text legible to start with). JPasswordField doesn't allow the toggling of mask/unmask.
Any ideas for a simple way to obtain this functionality in my simple applet?
You can disable the masking echo character with setEchoChar((char)0); as stated in the JavaDoc.
An example
final JPasswordField pass = new JPasswordField("Password");
Font passFont = user.getFont();
pass.setFont(passFont.deriveFont(Font.ITALIC));
pass.setForeground(Color.GRAY);
pass.setPreferredSize(new Dimension(150, 20));
pass.setEchoChar((char)0);
pass.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
pass.setEchoChar('*');
if (pass.getText().equals("Password")) {
pass.setText("");
}
}
public void focusLost(FocusEvent e) {
if ("".equalsIgnoreCase(pass.getText().trim())) {
pass.setEchoChar((char)0);
pass.setText("Password");
}
}});
Greetz,
GHad
The Text Prompt class will support a password field.

Categories

Resources