Is there any way to tell during the execution of the valueChanged method of a ListSelectionListener whether the user clicked the JList or whether setSelectedIndex was called by some other code?
AFAIK, no. But if the goal is to only execute something if the selection comes from the user, you may set a flag before selecting an index in the code to signal that the selection doesn't come from the user, or remove the listener and add it afterwards:
private void selectIndexInList(int index) {
this.selectionComesFromTheCode = true;
try {
list.setSelectedIndex(index);
}
finally {
this.selectionComesFromTheCode = false;
}
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (!this.selectionComesFromTheCode) {
...
}
}
Related
I currently have an actionListener set up to detect whether or not the checkBox I have created is checked, and depending on this; set the value of taskType to either 'oneOff' (unchecked) or 'Routine (checked). The problem is that when the user submits the form by clicking the button, the received value is 'null' if the box is left unchecked, the only way to make the received value 'oneOff' is by checking the box and unchecking it again. How can I make the default unchecked value of the checkbox 'oneOff' - and is this even possible?
checkBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
if(freqComboBox.getSelectedIndex() == -1 && checkBox.isSelected())
{
freqLabel.setEnabled(true);
freqComboBox.setEnabled(true);
createTask.setEnabled(false);
}
else if(checkBox.isSelected())
{
freqLabel.setEnabled(true);
freqComboBox.setEnabled(true);
taskType = "Routine";
}
else
{
freqLabel.setEnabled(false);
freqComboBox.setEnabled(false);
freqComboBox.setSelectedIndex(-1);
taskType = "oneOff";
}
}
});
I'm having a problem with my Java code.
I need to execute my doSomething() method, which includes code that manage also global variables. The problem is that the method is invoked twice (both mouseEvent and focusEvent of my JTable are fired at the same time).
How can I execute the doSomething() method only once at a time, in a sort of mutual exclusion ?
Thanks.
addMouseListener (new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
doSomething();
}
});
addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e){
doSomething();
}
});
JTable cells contains String with length 1 or 2.
I need to apply a setValue method (or delete the String), in the exact moment the user stops the cell editing or he writes a 2 character String.
With those listeners I know the exact time to do the setValue or to inform the user that the first character he wrote doesn't exist. So in that way I wanted to block the user's action.
In other words, I need to control the user input in order to do a setValue or delete it. FocusLost tells me when the user clicks outside the JTable Component.
MouseClicked tells me when the user clicks in the JTable Component.
When mouseClicked is invoked and the JOptionPane appears, the cell automatically lose the focus, and so also the focusLost is invoked.
public void doSomething () {
// inEdit and tableCellEdited are the global variables
if ( inEdit && tableCellEdited != null ) {
String temp = "" + tableCellEdited.getDay();
String s = tableCellEdited.getValRenderer().trim();
if (s.length() > 2) s = s.substring(4);
if ( !s.trim().isEmpty() ) {
JOptionPane.showMessageDialog(getParent(),
"Code doesn't exist" , "Error: Code doesn't exist",JOptionPane.WARNING_MESSAGE);
tableCellEdited.setRendererValue(getUltimaGG(), false);
}
else {
tableCellEdited.setRendererValue(s, false);
setValueAt(tableCellEdited, getRowFromMat(tableCellEdited.getMat()), Integer.parseInt(temp.substring(6, 8)) );
}
clearProgrammazioneDueCaratteri();
}
}
repaint();
}
I have two JComboBoxes; one removes all items in the other if it's already populated and then adds a new set of items, and the second fires an event that gets information from a database using the selected item. The problem occurs after the first combo box does its thing removing the items and adding new ones; when I select any of the items in the second JComboBox, the event that fires doesn't happen anymore.
Below I have provided snippets of my code:
The first combo box
cmbIDs.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
selection = (String)cmbIDs.getSelectedItem();
if (!(selection.equals("Select an username")))//current selection in combobox is stored as string
{
comboActivate(selection);
if (!unitC.getText().equals("")){
unitC.setText("");
}
if (!lecturer.getText().equals("")){
lecturer.setText("");
}
if (!(courseD.getText().equals("Not Enrolled"))){
populateUnits(selection);
}
}
else{
JOptionPane.showMessageDialog(null,"Please select a Surname.");
}
}
});
Removing the items inside populateUnits(String selectionID):
try
{
units.removeAllItems();
units.addItem("Select a Unit");
}
catch (NullPointerException npe)
{
units.addItem("Select a Unit");
}
After this instructions are sent through a client to a server where a db is queried and the server replies with information which is then added to the second JComboBox. I assure you also that the items are added to the JComboBox after removeAllItems() is used.
The second jComboBox:
units.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ue)
{
uSelect = (String)units.getSelectedItem();
if (!(uSelect.equals("Select a Unit")))//current selection in combobox is stored as string
{
System.out.println(uSelect);
unitActivate(uSelect);
}
else
{
JOptionPane.showMessageDialog(null,"Please select a Unit.");
}
}
});
It looks like your code never gets a fresh set of items from the database, so the user can never select anything other than "Select an Unit", which your second code block ignores.
it work for me
try {
boxListMaterial.removeActionListener(controller);
boxListMaterial.removeAllItems();
}catch (Exception e){}
boxListMaterial.addActionListener(controller);
Controller - ActionListener*
I have this combo box that I would like to enable or disable depending on a selection of "SDO/OD", (coded as 10 in database) in a previous combo box. When I use the following code it gives me the drop down listing, but for every choice. I want the drop down for only when "SDO/OD" is chosen. Otherwise, disable the combo box but allow the data to pass the null for the record. I don't think it is reading the Listener. My question is why is this happening? How to I handle the Listerner to accommodate such a task?
fcbRole.addSelectionChangedListener(new SelectionChangedListener<ModelData>()
{
#Override
public void selectionChanged(SelectionChangedEvent<ModelData> se)
{
fcbOfficeRegion.clearSelections();
fcbOfficeRegion.getStore().clearFilters();
if(fcbRole.getValue().equals("SDO/OD") && se.getSelectedItem() != null)
{
fcbOfficeRegion.enable();
fcbOfficeRegion.setValueField(se.getSelectedItem().get("strValue").toString());
StoreFilter<ModelData> sfRole = new StoreFilter<ModelData>()
{
#Override
public boolean select(Store<ModelData> store,
ModelData parent, ModelData item,
String property) {
String name = item.get("filterDepts");
name = getScc().cleanString(name.toLowerCase());
if (name.contains("(" + fcbRole.getValue().get("strValue") + ")"))
{
return true;
}
return false;
}
};
fcbOfficeRegion.getStore().addFilter(sfRole);
fcbOfficeRegion.getStore().applyFilters("fcbOfficeRegion");
}
else
Best of Listeners for JComboBox is ItemListener, this Listener fired events SELECTED/DESELECTED, always twice
Is there a way to disable the Back button in a browser (basically clearing the History token stack) in GWT? Once I browse to a certain page in my application I want to make sure that the user can't use the back button to go back, but only be able to use links on the page to navigate the site.
You cannot disable a button just intercept it and change its return to something the browser does not understand.
This removes the history:
Window.addWindowClosingHandler(new ClosingHandler() {
#Override
public void onWindowClosing(ClosingEvent event) {
event.setMessage("My program");
}
});
To understand it see: http://groups.google.com/group/google-web-toolkit/browse_thread/thread/8b2a7ddad5a47af8/154ec7934eb6be42?lnk=gst&q=disable+back+button#154ec7934eb6be42
However, I would recommend not doing this because your it goes against good UI practices. Instead you should figure out a way that the back button does not cause a problem with your code.
Call the method below in the onModuleLoad().
private void setupHistory() {
final String initToken = History.getToken();
if (initToken.length() == 0) {
History.newItem("main");
}
// Add history listener
HandlerRegistration historyHandlerRegistration = History.addValueChangeHandler(new ValueChangeHandler() {
#Override
public void onValueChange(ValueChangeEvent event) {
String token = event.getValue();
if (initToken.equals(token)) {
History.newItem(initToken);
}
}
});
// Now that we've setup our listener, fire the initial history state.
History.fireCurrentHistoryState();
Window.addWindowClosingHandler(new ClosingHandler() {
boolean reloading = false;
#Override
public void onWindowClosing(ClosingEvent event) {
if (!reloading) {
String userAgent = Window.Navigator.getUserAgent();
if (userAgent.contains("MSIE")) {
if (!Window.confirm("Do you really want to exit?")) {
reloading = true;
Window.Location.reload(); // For IE
}
}
else {
event.setMessage("My App"); // For other browser
}
}
}
});
}
I found a way to make GWT ignore the back-button: Just add historyitem x if no historyitem was set and do nothing on x.
set a historyitem on startup
History.newItem("x")
in the ValueChangeHandler of History add the following:
String historyToken = event.getValue();
if (!historyToken.equals("x"))
History.newItem("x");
Window.addWindowClosingHandler(new ClosingHandler() {
#Override
public void onWindowClosing(ClosingEvent event) {
event.setMessage("My program");
}
});
That is not a fool proof solution. In fire fox I can press the back button and the onWindowClosing method is never invoked. The reason is that I have used History.newItem() and since history exists the back button or backspace buttons simply navigate through the browser history.
So....fix that :)
Put this in your index.html file:
window.open('html page(For example trial.html)', 'Name of the desired site', width='whatever you want',height='whatever you want', centerscreen=yes, menubar=no,toolbar=no,location=no,
personalbar=no, directories=no,status=no, resizable=yes, dependent=no, titlebar=no,dialog=no');