Showing combo box when a specific selection occurs - java

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

Related

How to listen on save button or assign an event after it was clicked in Vaadin 7

When I am editing grid inline I can save or cancel my grid row changes. I want to update my database entries after button 'save' will be pushed(Data base mechanism has already done) How can I implement it?
My container:
BeanItemContainer<CategoryOfService> beansContainer;
Editing view:
All what I need it know which listeners I have to use. I found some CommitHandler which I can add by EditorFieldGroup class but I can't implement it properly maybe there is have to be another way to resolve problem.
There's kind of a way to capture inline Save click on the grid.
grid.getEditorFieldGroup().addCommitHandler(new FieldGroup.CommitHandler() {
#Override
public void preCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {
//...
}
#Override
public void postCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {
//...
}
});
After clicking Save both methods preCommit and postCommit get called.
Hope it helps :)
Grid does not currently give you any direct way of adding listeners to the save and cancel buttons for the inline editor, although that is something that might change in Vaadin 7.6.
As a workaround before that happens, the CommitHandler approach that you already mentioned is still supposed to work. You can find a basic example here. The contents of your BeanItemContainer should be fully updated in the postCommit phase.
grid.getEditor().addSaveListener((EditorSaveListener<Product>) event -> {
//your stuf
HibernateDataSource.updateProduct(event.getBean());
});

Text Missing On Checkbox Component for Swing After Adding Action

I'm writing a simple Swing app. I tried adding a checkbox as listed below. Once I added the actionHandler loadPickers the name Foo disappeared from where it was sitting next to the right of chckbxNewCheckBox. I tried adding a call to setHideActionText(), but now nothing displays.
JCheckBox chckbxNewCheckBox = new JCheckBox("Foo");
chckbxNewCheckBox.setToolTipText("");
chckbxNewCheckBox.setName("");
chckbxNewCheckBox.setHideActionText(true);
chckbxNewCheckBox.setAction(loadPickers);
mainPanel.add(chckbxNewCheckBox, "flowy,cell 0 1");
If I change it to this it works properly. I see the text "Foo".
JCheckBox chckbxNewCheckBox = new JCheckBox("Foo");
chckbxNewCheckBox.setToolTipText("");
chckbxNewCheckBox.setName("");
chckbxNewCheckBox.setHideActionText(true);
chckbxNewCheckBox.setAction(loadPickers);
chckbxNewCheckBox.setText("Foo"); //THIS DOES NOT WORK IF IT COMES BEFORE SET ACTION
mainPanel.add(chckbxNewCheckBox, "flowy,cell 0 1");
I've included the action here for completeness. Why does it work this way? Am I missing something here? Currently I'm using the WindowBuilder plugin for Eclipse with the Mig layout system (which I really like). Unfortunately I haven't figure out if there's a way to make WindowBuilder use the .setText() method instead of using the constructor. Any help on what I'm doing wrong, any insight on why this behavior exists like this, or a good workaround for WindowBuilder would be great.
private class LoadPickers extends AbstractAction {
public LoadPickers() {
//putValue(NAME, "SwingAction_2");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
}
}
As explained in the JavaDoc of AbstractButton.setAction:
Setting the Action results in immediately changing all the properties described in Swing Components Supporting Action. Subsequently, the button's properties are automatically updated as the Action's properties change.
So all the following properties can be impacted by setting an action:
enabled
toolTipText
actionCommand
mnemonic
text
displayedMnemonicIndex
icon (NA for JCheckBox)
accelerator (NA for JCheckBox)
selected

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!

eclipse listener for main menu bar selections

i am trying to capture user selections from the menu bar , for example if the user pressed File in the menu, my plug-in gonna print "File pressed".
i figured out how to listen to view selections by IselectionService , but still has no clue how to do it with the main menu bars(or toolbars).
thanx for help
More details :
I gonna explain my problem a little bit more precisely :
I would like capture top-level menus actions and toolbar, the problem is I really don't know how to create and attach the listener.
Here is the ISelectionListener of the plugin.
My purpose is to listen to the workbench top-level menu selections and toolbar.
Thanx for help
// the listener we register with the selection service
private ISelectionListener listener = new ISelectionListener() {
public void selectionChanged(IWorkbenchPart sourcepart, ISelection selection) {
// we ignore our own selections
if (sourcepart != SelectionView.this) {
showSelection(sourcepart, selection);
}
}
};
...
...
public void createPartControl(Composite parent) {
...
getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(listener);
P.S : Most what I found about menu listener were SWT stuff for some view or windows I had created, thats not what I meant, I need listener to the main top level menu and toolbars in eclipse workbench.
If you know the location uri (which you can check with a PluginSpy), you can add an handler in order to react to that menu event.
Note: The Menu Contribution article mentions the locationURI for:
main menu is "org.eclipse.ui.main.menu"
main toolbor is "org.eclipse.ui.main.toolbar"
Yuo could try to use the ICommandService:
with this service you can register an IExecutionListener.
This way you can track all the commands wich are executed but I'm afraid that this way you can't track the menu item that activated the command itself.
Hope it helps
i just wanna tell you i got some help from guys who made Smarttutor plugin, which excatly what i need. captures all the actions on the menus. – amir farah 31 secs ago edit i just wanna tell you i got some help from guys who made Smarttutor plugin, which excatly what i need. captures all the actions on the menus.
here is the website:code.google.com/p/smarttutor

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