Recover the getSelectedValue from addMouseListener [duplicate] - java

This question already has answers here:
JList selected item to String - Weird result: Donnees.Marques#3d5bac58
(4 answers)
Closed 7 years ago.
In listMarques.addMouseListener, I would like to get the String in selectedCategories. I have tried this in my class,
Private selectedCategories = null
but it's not working.
listCategories.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
String selectedCategories = listMarques.getSelectedValue().toString();
System.out.println(selectedCategories);
}
});
listMarques.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
String selectedMarques = listMarques.getSelectedValue().toString();
if(selectedMarques != null && selectedCategories != null)
{
}
}
});

You are hiding the member variable with your local variable.
Replace
String selectedCategories = listMarques.getSelectedValue().toString();
with
YourClassName.this.selectedCategories = listMarques.getSelectedValue().toString();
where YourClassName would be the name of the class in which you are holding the member selectedCategories as well as the above code.
Good luck.

Related

How to randomly get item from string array?

I am trying to generate random questions from my String array called Questions. There 10 items inside. I am trying to set the text of JLabel where once the button is click one of the questions from the array will randomly be selected and displayed. However these 2 sections of code doesn't return anyting.
public String getNextQuestion() {
int NextQues = (int)(Math.random()*10);
return Questions[NextQues];}
public void actionPerformed (ActionEvent e) {
if(e.getSource() == Button) {
Hello.setText(Questions[NextQues]);
Don't hardcode the magic number 10 in getNextQuestion(). I would prefer
ThreadLocalRandom over Math.random(). Like,
public String getNextQuestion() {
return Questions[ThreadLocalRandom.current().nextInt(Questions.length)];
}
Then invoke that method in actionPerformed like,
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Button) {
Hello.setText(getNextQuestion());
}
}
You should be calling your method getNextQuestion
OK, you need an actionlistener on your button in order for something to happen. Something like
public String getNextQuestion() {
int NextQues = (int)(Math.random()*10);
return Questions[NextQues];}
// inside main method
...
Button.addActionListener (
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Hello.setText(getNextQuestion());
}
});
...

Is it Possible to undo a typed character into a JText area? [duplicate]

This question already has answers here:
How to limit a JTextArea to only accept a legal set of characters?
(4 answers)
Closed 8 years ago.
Is it possible to remove the character typed into a JTextArea in Java Swing? Or block certain characters from being added? I am not talking about a replace, I specifically want to remove / block the character added by a key event. Here's some example code to illustrate what I want to do:
input.addKeyListener(new KeyListener(){
#Override
public void keyTyped(KeyEvent e){
//Nothing to do here
}
#Override
public void keyPressed(KeyEvent e){
if(condition == true){
e.undo();
//I want to remove the key that character that was inserted with this action
}
}
#Override
public void keyReleased(KeyEvent e){
//Nothing to do here
}
});
Thanks in advance!
You can store the content of the textfield at the end of the keyPressed method.
If you then encounter a key, that you don't want, you can set the content of the textfield to the stored value and return.
private String oldValue;
#Override
public void keyPressed(KeyEvent e){
if(condition == true){
setText(oldValue);
return;
}
oldvalue = getText();//Replace getText() with correct getter for current value
}

Multiple Jtextfields to be filled before Jbutton enable

Hi I badly need some help I already search about Jtextfield to be filled before jbutton enables, DocumentListener most people use to determined if Jtextfield is being populated. I tried DocumentListener and it works but all I want is all Jtextfield must be not empty before the Jbutton enables here is my code.
Ftext.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
change();
}
#Override
public void removeUpdate(DocumentEvent e) {
change();
}
#Override
public void changedUpdate(DocumentEvent e) {
change();
}
private void change(){
if (Ftext.getText().equals("") && Mtext.getText().equals("") && Ltext.getText().equals("") && Addtext.getText().equals("")) {
SaveButton.setEnabled(false);
} else {
SaveButton.setEnabled(true);
}
}
});
if (Ftext.getText().equals("") && Mtext.getText().equals("") && Ltext.getText().equals("") && Addtext.getText().equals(""))
Means that all the fields must be empty. Some times you need to read this logic aloud...
"if field is empty AND field is empty AND field is empty..."
If you used || (or) instead, it would mean that if any one of the fields was empty the statement would be true for example...
if (Ftext.getText().equals("") ||
Mtext.getText().equals("") ||
Ltext.getText().equals("") ||
Addtext.getText().equals("")) {...
You should also consider using .getText().isEmpty() or .getText().trim().isEmpty() if the fields shouldn't contain just spaces.
You might also consider writing a single DocumentListener implementation instead of creating a new anonymous class for each field
public class FieldValidationHandler implements DocumentListener() {
private List<JTextField> monitorFields;
public FieldValidationHandler(JTextField... fields) {
monitorFields = Arrays.asList(fields);
for (JTextField field : monitorFields) {
field.getDocument().addDocumentListener(this);
}
}
#Override
public void insertUpdate(DocumentEvent e) {
change();
}
#Override
public void removeUpdate(DocumentEvent e) {
change();
}
#Override
public void changedUpdate(DocumentEvent e) {
change();
}
private void change(){
boolean enabled = true;
for (JTextField field : monitorFields) {
if (field.getText().trim().isEmpty()) {
enabled = false;
break;
}
}
SaveButton.setEnabled(enabled);
}
}
Then you'd just create a single instance...
FieldValidationHandler handler = new FieldValidationHandler(Ftext, Mtext, Ltext, Addtext);
Now, this approach is a little sneaky, in that it adds the DocumentListener to the fields you specify via the constructor automatically.
Another approach might be to have some kind "Validation" controller, that you would pass to this handler and it would call some kind of "validate" method when change was called.
This would separate the listener from the fields, but this is all a matter of context at the time.
I would personally have a "register" and "unregister" process which would allow you to add or remove fields as you need to

DocumentListener Validation Error in MVC Application

I am making a swing MVC application , to know the intricacies of GUI design using the Swing Framework . My JDK Version is 7 and I have a simple application that contains a dialog having a textfield for storing the path to a file , a browse button , 2 textfields for user id and password and 2 buttons for Update and Cancel functionalities.
Clicking on these buttons simply shows a dialog with either Update or Cancel message on it.
I planned to use DocumentListener to validate the textfield components.
In the UI i have the following code to create the 2 textfields :
public JPasswordField getMyPasswordField() {
if(myPasswordField == null)
{
myPasswordField = new JPasswordField();
myPasswordField.setBounds(133, 93, 163, 21);
myPasswordField.getDocument().putProperty("Owner", "myPasswordField");
}
return myPasswordField;
}
public JTextField getMyUserNameField() {
if(myUserNameField== null)
{
myUserNameField = new JTextField();
myUserNameField.setBounds(133, 66, 163, 21);
myUserNameField.getDocument().putProperty("Owner", "myUserNameField");
}
return myUserNameField;
}
In the controller I used the following code :
myReferenceUI.getMyUserNameField().getDocument().addDocumentListener(this);
myReferenceUI.getMyPasswordField().getDocument().addDocumentListener(this);
And in the method implementation I wrote the following :
public void insertUpdate(DocumentEvent e) {
Object owner = e.getDocument().getProperty("Owner");
changed(owner);
}
#Override
public void removeUpdate(DocumentEvent e) {
Object owner =e.getDocument().getProperty("Owner");
changed(owner);
}
#Override
public void changedUpdate(DocumentEvent e) {
Object owner =e.getDocument().getProperty("Owner");
changed(owner);
}
public void changed(Object e)
{
System.out.println(e.toString());
if( e.toString().equals("myUserNameField"))
{
if(myReferenceUI.getMyUserNameField().getText().equals("") )
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
return ;
}
}
if( e.toString().equals("myPasswordField"))
{
if(myReferenceUI.getMyPasswordField().getText().equals("") )
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
return ;
}
}
myReferenceUI.getMyUpdateButton().setEnabled(true);
}
My intent was to enable the update button only if the 2 textboxes for username and password have non null values.
The listener events fire properly and the update button is disabled in case of null entry in the username / password fields.
But after entering any value in these fields , if i press backspace and erase the text , the update button remains disabled.
What can i do to get rid of this condition ?
Use a DocumentListener that is aware of both the documents that you want to follow. For example:
private static class PasswordValidator implements DocumentListener {
private final Document[] documents;
private final JComponent component;
PasswordValidator(JComponent component, Document... docs) {
this.component = component;
documents = docs;
for (Document doc : docs) {
doc.addDocumentListener(this);
}
validate();
}
#Override
public void insertUpdate(DocumentEvent e) {
validate();
}
#Override
public void removeUpdate(DocumentEvent e) {
if (e.getDocument().getLength() == 0) {
component.setEnabled(false);
}
}
#Override
public void changedUpdate(DocumentEvent e) {
// Attribute change - ignore
}
private void validate() {
for (Document doc : documents) {
if (doc.getLength() == 0) {
component.setEnabled(false);
return;
}
}
component.setEnabled(true);
}
}
That particular implementation would then be used something like:
new PasswordValidator(myReferenceUI.getMyUpdateButton(), myReferenceUI.getMyUserNameField().getDocument(), myReferenceUI.getMyPasswordField().getDocument());
I got around my troubles by attaching PropertyChangedListeners to both my username and password fields and the following bit of code :
public void setUpdateButtonState()
{
if((myReferenceUI.getMyUserNameField().getText().equalsIgnoreCase("")
|| String.valueOf(myReferenceUI.getMyPasswordField().getPassword())
.equalsIgnoreCase("") ))
{
myReferenceUI.getMyUpdateButton().setEnabled(false);
}
else
{
myReferenceUI.getMyUpdateButton().setEnabled(true);
}

Why is cancelCellEditing() not called when pressing escape while editing a JTable cell?

I have an editable JTable and have set a DefaultCellEditor like so:
colModel.getColumn( 1 ).setCellEditor( new DefaultCellEditor( txtEditBox ) {
// ...
#Override
public void cancelCellEditing() {
super.cancelCellEditing();
// handling the event
}
// ...
}
However, when pressing escape while editing a cell in this column, though the editing mode is finished, this method is not called. Any ideas why? Am I doing something wrong? Is there a way to handle this (other than manually adding a KeyListener that is)?
The official way: You can register a CellEditorListener: AbstractCellEditor.addCellEditorListener(...). If the editing is canceled, editingCanceled(ChangeEvent e) should be called. Due to a SUN bug http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6788481, editingCanceled is not called :(
As workaround you can register your own action for the ESCAPE key and handle it yourself. But it will not work for resize events.
Another solution (quick and dirty;-)): Overwrite the methode JTable.removeEditor() and insert your code after the super call.
I had this problem too. I wrote another workaround that involves ActionListener and FocusListener. This is it:
public class TableEditorListenerHelper {
// dealing with events
private final EventListenerList listeners = new EventListenerList();
private ChangeEvent changeEvent;
// cell editor that we're helping
private CellEditor editor;
// transient state
private boolean editing = false;
private JTable table;
public TableEditorListenerHelper(CellEditor editor, JTextField field) {
this.editor = editor;
field.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
field.addFocusListener(new FocusListener() {
#Override public void focusGained(FocusEvent e) {
editing = true;
}
#Override public void focusLost(FocusEvent e) {
JTable table = TableEditorListenerHelper.this.table;
if (editing && isEditing(table)) {
fireEditingCanceled();
}
}
private boolean isEditing(JTable table) { // a hack necessary to deal with focuslist vs table repaint
return table != null && table.isEditing();
}
});
}
public void setTable(JTable table) {
this.table = table;
}
public void addCellEditorListener(CellEditorListener l) {
listeners.add(CellEditorListener.class, l);
}
public void removeCellEditorListener(CellEditorListener l) {
listeners.remove(CellEditorListener.class, l);
}
public CellEditorListener[] getCellEditorListeners() {
return listeners.getListeners(CellEditorListener.class);
}
protected void fireEditingCanceled() {
for (CellEditorListener l : getCellEditorListeners()) {
l.editingCanceled(getOrCreateEvent());
}
resetEditingState();
}
protected void fireEditingStopped() {
for (CellEditorListener l : getCellEditorListeners()) {
l.editingStopped(getOrCreateEvent());
}
resetEditingState();
}
private void resetEditingState() {
table = null;
editing = false;
}
private ChangeEvent getOrCreateEvent() {
return changeEvent = changeEvent == null ? new ChangeEvent(editor) : changeEvent;
}
Here you can find a little more complete solution.
Another way fix this bug:
jTable.addPropertyChangeListener("tableCellEditor", e -> {
Object o = e.getOldValue();
if (o instanceof DefaultCellEditor) {
((DefaultCellEditor) o).cancelCellEditing();
}
});

Categories

Resources