how to set nextline in textfield - java

so im creating a chat with a Gui that contains pictures of some men who has a textfield above them that will contain the text that the person chat.
This is by far the hardest project ive created and im quite proud of my accomplisments ive already created a multithreaded server and protocol for my chat client :) ive gotten a guy from Stackoverflow to help me resize my textfield if the text going into it is larger than the size of the textfield :) but now i have another problem when the textfield resizes it resizes only widght because my textfield doesnt change line
ive created the following code to try and make it change lines but it doesnt seem to work could anyone help me?
Send.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
String x = textField_chat.getText();
if (x.length() > 10) {
String oldLine = x.substring(0,5);
String newLineString = x.substring(5,x.length());
txt_ChatPerson1.setText(oldLine+"\n"+newLineString);
}else {
textField_chat.setText("");
txt_ChatPerson1.setVisible(true);
txt_ChatPerson1.setText(x);
}

Use a TextArea instead.
TextArea description from it's javadoc:
Text input component that allows a user to enter multiple lines of plain text. Unlike in previous releases of JavaFX, support for single line input is not available as part of the TextArea control, however this is the sole-purpose of the TextField control. Additionally, if you want a form of rich-text editing, there is also the HTMLEditor control.

I'm taking a shot in the dark here but if you are running this on Windows the new line character is "\r\n".
Try this:
txt_ChatPerson1.setText(oldLine+"\r\n"+newLineString);

Related

Prevent User Input but Allow Highlighting in TextArea

I have a text area that replicates a console output in my GUI. Id like for the user to select highlight and copy the output but not allow them to insert. Is there a way this could be done?
Right now I have a simple textArea editor and Ive tried terminalText.setDisable(true);. While this disables userinput it completely disables users from highlighting text as well.
I set my terminal text doing the following:
public void printToConsole(String s){
consoleBuilder.append(s);
terminalText.setText(consoleBuilder.toString());
}
I found that this disables input; however I am now unable to enter text using setText() method above and I cannot highlight:
terminalText.setTextFormatter(new TextFormatter<String>((Change c) -> {
return null ;
}));

javafx save layout after adding some nodes

simply i made little application .. and i attach button in gridpane so when im click the button generate text field .
#FXML
private void msgBtn(ActionEvent e) {
TextField newField = new TextField();
gp.getChildren().add(newField);
}
the question how i could save the text field generated for later open ?!
any way to save the generated node into xml file or some thing so i can recall it in the next start ?
i read a little about serialized but i didn't get how i approach to my goal through it
can any body help or give me some example ?

jComboBox editor returns empty String

I wrote a autocomplete combobox program in which I search for the words entered by the user inside a file. The program works fine, however, the combobox editor doesn't return anything when something is typed in it. I don't know why is that.. Here is the chunk of code that deals with the problem.
// in GUI class constructor
InstantSearchBox = new JComboBox();
InstantSearchBox.setEditable(true);
/*****/
KeyHandler handle = new KeyHandler();
InstantSearchBox.getEditor().getEditorComponent().addKeyListener(handle);
// Keylistener class (KeyPressed method)
try
{
dataTobeSearched = InstantSearchBox.getEditor ().getItem ().toString ();
// the string variable is empty for some reason
System.out.println ("Data to be searched " + dataTobeSearched);
}
catch (NullPointerException e)
{
e.printStackTrace ();
}
Regards
Don't use a KeyListener. The text typed has not beeen added to the text field when at the time a keyPressed event is generated.
The better way to check for changes to the text field is to add a DocumentListener to the Document of the text field. See the section from the Swing tutorial on How to Write a Document Listener for more information.
You should use dataTobeSearched = (String) InstantSearchBox.getSelectedItem();
Despite its name, for editable comboboxes, this method just returns what text is entered.
The editor is only used internally by JComboBox to temporarily capture the input as they are typing. Once they have typed, the editor is cleared down and the text transferred back to the combobox model.
This allows editors to be shared amongst multiple comboboxes all at once - they just jump in when they are needed, capture input, jump back out again and clear down when editing is finished.
Use InstantSearchBox.getSelectedItem() instead of InstantSearchBox.getEditor().getItem().

How do I change the value of a JOptionPane from a PropertyChangeListener without triggering the listener?

I am trying to make a program to manage a group of sports players. Each player has an enum Sport, and SportManager has convenient factory methods. What I am trying to do is open a dialog that has a JTextField for a name and a combo box to choose a sport. However, I want to stop the user from closing the dialog while the text field is blank, so I wrote a PropertyChangeListener so that when the text field is blank, it would beep to let the user know. However, if the user puts in something in the text after setting off the beep, it doesn't trigger the listener and you can't close the dialog without pressing cancel because the value is already JOptionPane.OK_OPTION, and cancel is the only way to change JOptionPane.VALUE_PROPERTY. So I tried to add
message.setValue(JOptionPane.UNITIALIZED_VALUE);
within the listener. However this just closes the window right away without giving the user a chance to fill in the text field, presumably because it triggers the listener I just registered. How do I make it so that it will beep more than once and give the user a chance to fill in the field?
FYI newPlayer is the component I'm registering the action to.
Code:
newPlayer.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Object[] msg = new Object [4];
msg[0] = new JLabel("Name:");
final JTextField nameField = new JTextField();
msg[1]=nameField;
msg[2] = new JLabel("Sport: ");
JComboBox<Sport> major = new JComboBox<Sport>(SportManager.getAllSports());
msg[3]=major;
final JOptionPane message = new JOptionPane();
message.setMessage(msg);
message.setMessageType(JOptionPane.PLAIN_MESSAGE);
message.setOptionType(JOptionPane.OK_CANCEL_OPTION);
final JDialog query = new JDialog(gui,"Create a new player",true);
query.setContentPane(message);
query.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
message.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
String prop = e.getPropertyName();
if (query.isVisible()&& (e.getSource() == message)&& (prop.equals(JOptionPane.VALUE_PROPERTY))) {
if(nameField.getText().equals("")&&message.getValue().equals(JOptionPane.OK_OPTION)){
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
return;
}
query.dispose();
}
}
});
query.pack();
query.setVisible(true);
if(Integer.parseInt(message.getValue().toString())==JOptionPane.OK_OPTION){
players.add(new Player(nameField.getText(),(Sport)major.getSelectedItem()));
edited=true;
}
gui.show(players);
}
});
I don't think you can do it with JOptionPane but you can using using TaskDialog framework and few others.
You can also create a dialog yourself, attach change listeners to your fields and enable/disable OK button based on content of your fields. This process is usually called "form validation"
However, I want to stop the user from closing the dialog while the
text field is blank
I get where you are going, but Java Swing is not very good at this. There is no way you can prevent the listener from being called. A solution would be to ignore the call, but this is complicated to implement.
The way I solved this issue is to let the pop-up disappear, check the returned value and if it is null/empty, beep and re-open it until user fills something.
JOptionPane does not internally support validation of inputs (Bug Reference). Your best bet is to create your own custom JDialog which supports disabling the OK button when the input data is invalid.
I'd recommend reading the bug report since other people talk about it and give workarounds.
However, I want to stop the user from closing the dialog while the text field is blank
The CustomDialog example from the section in the Swing tutorial on Stopping Automatic Dialog Closing has a working example that does this.
After taking a quick look at your code and the working example I think your code should be something like:
if (query.isVisible()
&& (e.getSource() == message)
&& (prop.equals(JOptionPane.VALUE_PROPERTY)))
{
if (message.getValue() == JOptionPane.UNINITIALIZED_VALUE)
return;
if (nameField.getText().equals("")
&& message.getValue().equals(JOptionPane.OK_OPTION))
{
Toolkit.getDefaultToolkit().beep();
message.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
else
query.dispose();
}
Otherwise, I'll let you compare your code with the working code to see what the difference is.
One way to solve this problem is to add a Cancel and Ok button to your dialog. Then, disable closing the popup via the X in the corner, forcing the user to click either Cancel or Ok to finish/close the dialog. Now, simply add a listener to the text field that will disable the Ok button if the text field is blank.
Judging from your code I assume you can figure out how to implement these steps, but if you have trouble let us know! Good luck!

text in text box

i am pretty new to the gwt framework and i am using it for building the ui of my web site,
i would like to make the text box have a text in it that once the user clicks on it for the first time, the text disappears. and in the rest of the time it behaves like a normal text box
any ideas on how to do it?
When you create the textbox, set the default text and add a keyboard listener:
TextBox box = new TextBox();
box.setText("Default Text");
box.addKeyboardListener(this);
defaultValue = true; // this is a global boolean value
Then have your class implement KeyboardListener leaving them all blank except:
public void onKeyPress(Widget arg0, char arg1, int arg2)
{
if(defaultValue)
{
box.setText = "";
defaultValue = false;
}
}
you can add a clickHandler to the box.
Within the handler you do something as easy as:
if(text==DEFAULT_TEXT)
{
text==""
}
If someone is going to write again the same DEFAULT_TEXT it would get wiped out again.
If you want to avoid that add boolean variable in the check expression.
Can't tell it for GWT, but a general approach could be:
use a variable to flag, whether the text box is 'initialized' or 'in use'
add a listener to the text widget (I'd use a KeyboardListener and make the text disappear when the user starts entering text and not on the first - maybe accidental - mouse click)
When the listener receives the first event for the widget (flag = 'initialized'), clear the flag and replace the text inside the text field with the actual keystroke.
(for a click listener: upon the first click on the widget clear the flag and the text box.)

Categories

Resources