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
Related
I am trying to set the default close operation in NetBeans 8.0.2 (in Ubuntu 14.04 on an older Asus gaming laptop.) My program is very large but uses no JFrame or java.swing components.
I merely need to save some values when the "x" in the lower right corner is clicked (this is one usual way to stop execution of a java program in NetBeans.)
I found suggestions that involved swing & JFrame, but it wasn't clear just where to insert the code:
DefaultApplicationView view = new DefaultApplicationView(this);
javax.swing.JFrame frame = view.getFrame();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter(){
public void WindowClosing(WindowEvent e){
System.out.println("CLOSING");
}
}
show(view);
I also found a set of instructions that I think I would prefer to use, but the post is old enough that my NetBeans doesn't have the tabs/menu-items referred to:
Set Window to Design Mode by clicking the 'Design' Tab
In the Navigator: Right click the 'JFrame' -> 'Properties'
In the Properties Tab: Set 'defaultCloseOperation' (top of the list) to 'DO_NOTHING'
Select 'Events' Tab
Scroll down to 'windowClosing'
Click on the "..." button on the right of the event to bring up the custom editor
Click 'Add...' and name the handler (i.e. custom function that you want to have execute on click of the 'X', or window close event).
Click 'Ok'
Netbeans now automatically creates the function and takes to you the function body in the source view
Now simply add what you want to do here: eg. dispose(), or system.exit or pintln(), or whatever your heart desires, as long as its JAVA and makes sense to the app.
Then there are a few other possibly relevant posts, but they all explicitly involve JFrame and/or swing. (Am I ignorant of some fact such as "All NetBeans java applications use JFrame", or some such?)
A pared down example of code for what I'm trying to do would be:
public class MyApp{
public static void main(String[] args){
loadMyVariables();
// do some work that changes variables' values
// during this work user clicks the 'x' box to halt execution
// I need then automatically to save the variables' new values
}
// needs to be called by the OS or GUI when execution is halted by user
public static void saveMyVariables{
// here the usual printStream stuff saves some values to a file
System.exit(0);
}
public static void loadMyVariables{
// here the usual Scanner stuff reads some values from a file
}
}
(I need help setting the tags for this, so I'm doing as instructed and asking the community.)
THANKS
I am a newcomer to Eclipse PreferencePages and am currently creating a new FieldEditorPreferencePage for my project. However, having FileFieldEditors() or DirectoryFieldEditors() greys-out the "Apply" and "OK" buttons in my custom preference page. On the other hand, the other FieldEditors (Boolean- and Combo-) do not disable the "Apply" and "OK" buttons.
Furthermore, changing everything to Xtext's LanguageRootPreferencePage seems to work as well (though I'd prefer not to use it as I want the custom preference page to show up in it's own tab).
For example:
//Simplified example of code
public class XPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage, IWorkbenchPropertyPage {
public XPreferencePage() {
super(FieldEditorPreferencePage.GRID);
setDescription("something");
}
protected void initialize() {
super.initalize();
//IPropertyChangeListeners go here
}
protected void createFieldEditors() {
//"Apply" and "OK" works here
g = new BooleanFieldEditor(SConstants.GENERATOR, "Generate Bindings", getFieldEditorParent());
addField(g);
//"Apply" and "OK" is greyed-out starting here
gp = new FileFieldEditor(SConstants.GENERATOR_PATH, "Generator Path:", false, 0, getFieldEditorParent());
gp.setEmptyStringAllowed(true);
addField(gp);
...
}
...
}
Is there anyway to fix this? I followed the tutorial from Eclipse Article-Field-Editors but it doesn't seem to work for me. Reading online says it can be due to negative IntegerField (which I don't have) or that I'm trying to change the default settings (which I don't have either).
I am using Eclipse Mars 4.5.0.
UPDATE: The code above (partially) worked for FileFieldEditors. However, for some reason I need to click FileFieldEditor field and check and uncheck the checkbox directly above the FileFieldEditor for each FileFieldEditor in the preference page before the "Apply" and "OK" buttons are available again.
Furthermore, I have also implemented a IPropertyChangeListener which deactivates certain fields when certain checkboxes are unchecked which means this "check and uncheck" workaround would not work for me. I have also tried setting the default focus to one of my checkboxes but that didn't work
FileFieldEditor(String name, String labelText, Composite parent) defalult validates the path when the text widget loose the focus that is what you are giving invalid as default value.
For e.g. if you give C:\\User\\XXX then this path should physically exist then and only it will not grey out ok and apply button.
You can also use below constructor by setting your validation stratergy.
FileFieldEditor(String name, String labelText,boolean enforceAbsolute, int validationStrategy, Composite parent)
value of validationStrategy
1 for the editor performs validation only when the text widget
loses focus.
0 for the editor performs validation after every key
stroke.
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);
}
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!
I need some help. Is it possible to simulate a drag & drop without registering a component?
E.g. I click the mousekey anywhere on the window and hold the mousekey down, at this moment, I want to create or simulate a DragSourceEvent programmatically with Java.
Is this possible?
Update:
Regarding Bob's reply, at least I got it, I can create a listener for the drag & drop:
DragSource dragSource = new DragSource();
DragGestureListener listener = new DragGestureListener() {
public void dragGestureRecognized(DragGestureEvent event) {
event.startDrag (null, strSel) ;
...
}
}
listener.dragGestureRecognized(new DragGestureEvent(
new DragGestureRecognizer(dragSource, component) {
}, DnDConstants.ACTION_COPY, new Point(0,0), events ));
but unfortunately i get this exception:
java.lang.IllegalArgumentException:
source actions at
java.awt.dnd.DragSourceContext.(DragSourceContext.java:169)
at
java.awt.dnd.DragSource.createDragSourceContext(DragSource.java:454)
at
java.awt.dnd.DragSource.startDrag(DragSource.java:293)
at
java.awt.dnd.DragSource.startDrag(DragSource.java:403)
at
java.awt.dnd.DragGestureEvent.startDrag(DragGestureEvent.java:203)
any suggestions?
The question you asked:
I haven't tried it, but in theory you should be able to create the Event object and get a handle on the Swing Event Queue from one of the system classes. However without having a valid component, there may be problems when methods try to work with the event.
What you probably meant:
Registering events for a standard window -- you should be able to set up drag and drop support for an empty JPanel or JFrame, but it'll take some hacking. Drag & Drop is a pain to work with at this level when not built in -- I suggest using something like an invisible component or something instead.