i put text on a JTextfield and i try to use that text in another class
... i have no error but no result
btnEntrez.addActionListener(new AuthentificationListner());
public class AuthentificationListner implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
Authentification aut = new Authentification();
String login = aut.txtnom.getText();
System.out.println("Login :"+login);
}
result :
Login : (But no textfield text :/ )
If Authentification is a JFrame, then aut.txtnom.getText() isn't going to return anything (other than what it was initialized with) as the user won't have time to enter anything before you try and grab the value, this is what JDialog is for. See How to make dialogs for more details.
Swing, like most UI frameworks is event driven, something happens, you respond to it, rather the procedural or linear (which your code seems to be trying to do)
Another approach is to use an observer pattern on Authentification, which will notify interested parties that something (they might be interested in) has changed.
Related
I need to create a JDialog, or a JFrame class (it doesn't particularly matter so long as it's a graphical interface) - that can be used in a static command that is called from the within the actionPerformed(ActionEvent) handler and will stall that process until the user provides their selections from the user interface.
Obviously it is possible to do, because this is exactly what the dialogs JOptionPane creates does. But when I try to stall the thread until the user has completed the selection process, the interface doesn't display properly.
Here is the part of my code that I'm having trouble with:
public static Results queryForResults(String message, int propertyOne,
int propertyTwo){
MyCustomDialog mcd = new MyCustomDialog(message, propertyOne,propertyTwo);
mcd.show();
// complete() is a boolean property of my MyCustomDialog class that turns
// true when the interface has been completed.
while(!mcd.complete()){
synchronized(mcd){
try{
mcd.wait(10000L);
} catch(InterruptedException e) {
e.printStackTrace();
return null;
}
}
}
mcd.dispose();
// My MyCustomDialog class has a getResults() property which returns
// a Results object (i.e. another custom class I've made to contain
// the selections made by the user.)
return mcd.getResults();
}
The dialog outer frame appears, but it's insides don't. They just seem to be a screen capture of whatever was on the screen beneath the dialog when it appeared. I get the impression that this isn't working because I'm not supposed to be stalling the Swing Event thread with the wait command. So how do you do it?
There is no need for a while loop. A modal JDialog will cause execution to stop in your ActionLIstener until the dialog is closed.
Also, don't use the show() method to display a dialog. You should be using the setVisible(true) method.
I am coding a bookshop in Java and have a problem with when a new book is ordered I want the user to select whether it is a ebook or paper book. If it is an ebook I want another combo box to show on the page with called cboFormat. I have some code but it doesn't seem to work.
This is in the constructor.
if("Ebook".equals(cboBookType.getSelectedItem()))
{
cboFormat.enable();
}
else
{
cboFormat.disable();
}
Why doesn't this work? I have also previously set the format input to disabled.
This could be that you do not have a actionlistener on your combo box ? As Andrew suggested, there could be more reasons why your block does not work. If you pasted more code it would be easier to determine what the problem is. If however you are missing action listener on your combo box, code below.
public void actionPerformed(ActionEvent e) {
JComboBox cboBookType = (JComboBox)e.getSource();
String bookType= (String)cboBookType.getSelectedItem();
//and paste your ifs here
if("Ebook".equals.....){
...
}
... rest of code
}
And if you don't know what action listener is, its basically interface used by other classes to listen for an action event. i.e. user clicking button, or user selecting checkbox etc.
Dont use enable and disable try this and dont put it in the constructor because then it wont get updated you have to make a new event like itemchanged or itemstatechanged i dont know it exactly
if("Ebook".equals(cboBookType.getSelectedItem()))
{
cboFormat.setvisible(true);
}
else
{
cboFormat.setvisible(false);
}
When a user clicks a JButton in my Java-Swing application, a string is returned from a method and the user then needs to be able to read the string (somehow). The JButton is within a JPanel. My first thought was to create an 'alert' dialogue (thinking this would be easy), I tried to follow this example that looked easy: http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/DialogExample.htm
I have not yet been able to confirm if this works because I do not know how to import the libraries into eclipse. For example import org.eclipse.swt.SWT; gives the error "... cannot be resolved".
So one possible solution is how to import in Eclipse. Another possible solution is to dynamically change the text within the JPanel somehow.
As Ben mentioned in his comment. I would set a jLabel with a blank text to start. Then, when you click your button that triggers the method, simply tack on:
label.setText(value);
Alternatively you could use another pane to popup and display the message.
If you're talking about Swing, an easy solution is to pop a message box with the string:
button.addActionListener(new ActionListener {
public void actionPerformed(ActionEvent e) {
String message = methodThatReturnsYourString();
JOptionPane.showMessageDialog(null, message);
}
}
In this link you will find the information u require in order to add the library and import it:
http://www.eclipsepluginsite.com/swt.html
as well I would not mix SWT with swing and I would stick to swing you can set the label on the event of your button
button.addActionListener(new ActionListener {
public void actionPerformed(ActionEvent e) {
String message = "Test String";
labelMessage.setText(message );
}
}
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!
Using Swing in Java I wrote a form containing radio buttons, text fields and so on. In the very end I have a "Submit" button.
Now I want to "send" the information given by the user to the program. How do I do that? Is there a good tutorial about that?
Is it kind of similar to PHP? (I am asking just because I know how to do it in PHP. To avoid confusions I probably need to mention that I do NOT program a web application).
Processing data in Swing is way different from the typical web REQUEST/RESPONSE paradigm.
To Take something you may know, it's more in the fashion of Javascript actions in an HTML page : each time user performs an operation, one or more events are sent, and the application developper can update application content according to it.
In your case, if you register an ActionListener to the button, it will be called each time button is clicked. You'll then have the possibility to perform any operation you want.
But that's not all !
Each time a component is keyboard focused, or receives the mouse, events are sent, as well as when a key is stroked or when widget's model is updated.
I would really suggest you to read documents such as Swing tutorial (which dives in greater details than I could do in 1 month).
Not completely sure what you mean by "send to the program". You are in the program so I assume that you have a dialog that renders this form? Just pass the dialog the object that you want to use to store the data. For example, your dialog's constructor can take an argument.
public class MyDialog extends JPanel {
private UserInfo userInfo;
private JTextField name;
/**
* The main area of the dialog.
*/
protected JPanel panel;
public MyDialog(UserInfo userInfo) {
this.userInfo = userInfo;
}
public showDialog() {
// Some code to create the form which it looks like you already know how to do
// Create a name field
JLabel nameLabel = new JLabel("Name:");
panel.add( nameLabel );
JButton submit = new JButton("Submit");
submit.addActionListener( new ActionListener() {
public void actionPerformed (ActionEvent event)
{
this.userInfo.setName(name.getText().trim());
} } );
panel.add( submit );
}
}