jpopupmenu where to add listener - swing

I have a jTextField with a button along side to call a popupmenu. The popupmenu contains a list of standard text for the jTextField. This list is held in a list array of variable length, since it can be added too elsewhere in the program.
I'm using the following to generate the popupmenu.
for(i=0;i<=menuArray1.size()-1;i++){
JMenuItem item = new JMenuItem((String) menujlArray1.get(i));
jPopupMenu1.add(item);
}
My question is how do I include the listener that captures which item on the popup menu is selected so I can then put the value into the jTextField.

You need to add a ItemListener interface. If your JMenuItem implements ItemSelectable interface. You can change your code to be like below:
ItemListener il =
e -> {JMenuItem source = (JMenuItem)(e.getSource());
String s = "Item event detected on '" + source.getText() +",New state: "
+ ((e.getStateChange() == ItemEvent.SELECTED) ?
"selected":"unselected");
jTextField.setText(s);
};
for(i=0;i<=menuArray1.size()-1;i++){
JMenuItem item = new JMenuItem((String) menujlArray1.get(i));
jPopupMenu1.add(item);
item.addItemListener(il);
}
More examples here and here

Related

How to Get Selected Item From LibGDX List?

I’ve tried a few different methods to get a selected item from a list (see code below), but everything I’ve tried only returns the first item in the list no matter which item was actually selected. Visually it appears to work because the correct item gets highlighted when it is clicked on.
As a general overview of what I’m trying to do, I have a folder that contains all of the saved preset files (json files), then I read the names of all the files into a list of strings, from this list a specific preset can be selected, and then I have a separate “load” textbutton that loads the item that was selected from the list. But as mentioned above, the correct item is not loaded from the list when the load button is clicked.
Here is my code:
public class PresetLoadMenu extends Menu {
private GUI gui;
private SaveManager saveManager;
private Table scrollPaneContainerTable;
private ScrollPane scrollPane;
private Table scrollTable;
private List<String> presetList;
private TextButton loadButton;
private FileHandle rootFolderHandle = Gdx.files.external(“presets/”);
public PresetLoadMenu(GUI gui){
this.gui = gui;
refreshList();
scrollTable = new Table();
scrollTable.add(presetList);
scrollPane = new ScrollPane(scrollTable);
scrollPaneContainerTable = new Table();
scrollPaneContainerTable.add(scrollPane).size(this.getWidth(), this.getHeight()*.2f);
add(scrollPaneContainerTable);
row();
loadButton = new TextButton("LOAD", gui.menuStyles.getMenuOkCancelButtonStyle());
loadButton.addCaptureListener(new ChangeListener(){
#Override
public void changed(ChangeEvent event, Actor actor){
// METHOD 1:
// System.out.println("SELECTED PRESET: " + presetList.getSelected());
// METHOD 2:
// System.out.println("SELECTED PRESET: " + presetList.getSelection().getLastSelected());
// METHOD 3:
// for (int i=0; i<presetList.getSelection().size(); i++){
// System.out.println("INDEX: " + i + " SELECTED PRESET: " + presetList.getSelection().toArray().get(i));
// }
}
});
add(loadButton).size(loadButton.getWidth(), loadButton.getHeight());
}
public void refreshList(){
FileHandle[] files = rootFolderHandle.list();
Array<String> namesArray = new Array<String>();
for(FileHandle file: files) {
namesArray.add(file.name());
}
presetList = new List<String>(gui.menuStyles.getListStyle());
presetList.setItems(namesArray);
}
}
The last method I tried using a for loop just to see if it would print out the other items that I clicked on, but it still printed the first item just one time and didn't detect that I had clicked on any of the other items.
On request I'm copying my last comment as an answer in order to close my question.
The problem was actually something else outside of the class that I posted, so presetList.getSelected() may work just fine now that I figured out what the problem was. But before I figured it out, I had swapped out the List for a ButtonGroup, which is actually better for me than using the List anyways so it worked out. The List has a built in listener that selects the item on touch down, so items would get selected when trying to scroll up or down. With a button I can have a listener just for the checked state, which is what I want.
Based on your answer, I solved it by creating a table of TextButton (buttonTable) , every of them initialize with an string:
final TextButton button = new TextButton("my string",skin);
and a listener:
button.addListener(new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
button.getText()));
}
});
This buttonTable initialize a ScrollPane to allow vertical scrolling:
scrollPane = new ScrollPane(buttonsTable);
This scrollPane was added to table used to format my form:
mainTable.add(scrollPane);
This table was the actor added to the stage:
stage.addActor(mainTable);

Flex - Clearing DateField value on tab change in TabNavigator

I have the following tab navigator, which has a Project tab, containing a Combobox next to Release label as follows(AdditionalDetails.mxml):
Same tab navigator is having a Gate2 tab, which contains a DateField next to the label CERT load date, which can be seen below(Gate2.mxml):
Now, when I select Release as TBD on Project tab, an alert box appears as follows:
On clicking YES, I want to clear the DateField on Gate2 tab. How can I do so?
Code for Combobox(AdditionalDetails.mxml):
<mx:ComboBox id="General_Release_Dates"
selectedItem="{modelProxy.General_Release_Dates}"
valueCommit="{model.General_Release_Dates = event.currentTarget.selectedItem;updateReleaseDate(event)}"
change="{model.General_Release_Dates = event.currentTarget.selectedItem;updateReleaseDate(event)}" close="closeHandler(event);" includeInLayout="true" visible="true">
</mx:ComboBox
Code for handling YES click on Alert box:
private function alertClickHandler(evt:CloseEvent):void {
if (evt.detail == Alert.YES) { //Code to clear DateField}
DateField code on Gate2 tab(Gate2.mxml):
DateField code:<mx:DateField id="G2_CRTLoadDate" width="150" selectedDate="{modelProxy.G2_CRTLoadDate}" change="{modelProxy.G2_CRTLoadDate = event.currentTarget.selectedDate;changeManagerStatus()}"/>
Updated: Aug 31 23:27(JST)
If you're using singleton
Flex - Problems in accessing static variable on another mxml page
1) Create variable at your MySingleton class like below.
private var _gate2:Object;
public function set gate2(value:Object):void
{
_gate2 = value;
}
public function get gate2():Object
{
return _gate2;
}
2) Gate2.mxml (write at creationComplete event)
singleton.gate2 = this;
3) Control Gate2 from external class.
private function alertClickHandler(evt:CloseEvent):void {
if (evt.detail == Alert.YES) {
//Code to clear DateField
singleton.gate2.G2_CRTLoadDate.selectedDate = null;
}
}

"Events type" in java

My program contain two classes, one represent the main program and the other one is a gui implemented using swing,
I'm trying to create an "event type", meaning I want my main program to wait until the UserInterface (GUI) will indicate some event, like pressing a button, and I would like to sends some information when my button is pressed.
General Code for the main program (this is the relevant section)
// Open window GUI with the requested BID and wait for confirmation or denial
HumanIFWindow nextWindowGUI = new HumanIFWindow();
nextWindowGUI.setVisible(true);
// ----------------- //
// - Wait on event - //
// ----------------- //
// Here is where I want to wait for the gui Indication
return returnedBid;
Code for the GUI (Again only relevant part)
JButton btnAprove = new JButton("Aprove");
btnAprove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// ----------------- //
// - Trigger event - //
// ----------------- //
// Here is where I want to trigger the event
}});
Preferably I would like to use some library, is there's one that match my needs?
(Maybe BusEvent?)
Edit to specify the question (Thanks Kishan Sarsecha Gajjar)
I want the first class (the general one) to enter a wait statement, I know how to wait using:
while( someBoolean...)
Thread.sleep(...)
and I can change someBoolean with a handle in the GUI class, Like:
FisrtClass.someBoolean == False
But I want something nicer and neater, like a library that Implements the sleep statement. and there's no additional code needed. Is there something like that?
I've looked at Google-BusEvent library but I'm not sure if that's compatible
EDIT, adding JDialog
updated code: Main program:
Bid returnedBid = requestBid;
// Open window GUI with the requested BID and wait for confirmation
DialogHumanConfirmManual nextWindowGUI = new DialogHumanConfirmManual(requestBid);
// Wait on event
if ( (returnedBid = nextWindowGUI.getAnswer()) != null ){
System.out.println("Got Bid " + returnedBid.print());
}
GUI - Dialog:
public DialogHumanConfirmManual(Bid requestedBid){
currentBid = requestedBid;
currentBid.approvedHuman = false;
Dialog mainFrame = new Dialog(new Frame());
myPanel = new JPanel();
getContentPane().add(myPanel);
myPanel.add(new JLabel("Confirmation Dialog"));
yesButton = new JButton("Confirm");
yesButton.addActionListener(this);
myPanel.add(yesButton);
noButton = new JButton("No");
noButton.addActionListener(this);
myPanel.add(noButton);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (yesButton == e.getSource()) {
currentBid.approvedHuman = true;
answeredBid = currentBid;
}
}
After opening the Dialog the if ( returnBid ) is called, which result in Null Pointer Exception later on in the code, So How can I delay the main program until the user can Confirm the request??
the other one is a gui implemented using swing,
Use a modal JDialog not a JFrame.
Once the dialog is made visible, the code after the setVisible(true) statement will NOT execute until the dialog is closed.
Read the section from the Swing tutorial on How to Make Dialogs for more information. The tutorial covers the JOptionPane class, but you can just use a JDialog, which is created exactly the same way a JFrame is. You can choose whether to use a JOptionPane or JDialog depending on your exact requirement.

Update Label text field

I use a Label component to display the length of an ArrayCollection. How do I get it to update when I add new items to the collection?
Here's the text field for the Label:
text="{model.meetingInfo.documentList.length}"
Here's the handler for adding a new item to the collection:
var attachmentProgressVO:AttachmentProgressVO = new AttachmentProgressVO();
attachmentProgressVO.fileReference = file as File;
newAttachmentList.addItem(attachmentProgressVO);
checkIfUpdate(file as File, attachmentProgressVO);
meetingInfo.docsAndAttachmentsList.addItem(attachmentProgressVO);
I tried adding these 2 lines but that didn't work:
meetingInfo.docsAndAttachmentsList.itemUpdated( attachmentProgressVO );
meetingInfo.docsAndAttachmentsList.refresh();
I also tried changing this:
public var docsAndAttachmentsList:ArrayCollection = new ArrayCollection();
to this:
private var _docsAndAttachmentsList:ArrayCollection = new ArrayCollection();
..with a getter and setter but that didn't work.
I'm not using the right approach, am I?
Generically, Binding only looks at a specific object; you can't drill down 4 objects deep to a specific property and expect binding to update values.
Changing the documentList does not change meetingInfo or Model, so binding will never be triggered. itemUpdated() and refresh() should update the list based class which displays the data; but will not affect your label displaying the count.
You need to listen on the collection for a collectionChange event and manually update the label's text in the collectionChange handler.

dropdownlist event

I have been searching all around for a guide on event handling in flash builder 4.5. I have a dropdownlist that I'd like to activate preferably a action script function. similar to asp.net/js.
cheers!
right out of as3 docs with some comments...
import fl.controls.ComboBox;
import fl.controls.Label;
var myComboBox:ComboBox = new ComboBox();
myComboBox.prompt = "Please select an item...";
myComboBox.addItem({label:"Item 1"});
myComboBox.addItem({label:"Item 2"});
myComboBox.addItem({label:"Item 3"});
myComboBox.addItem({label:"Item 4"});
myComboBox.width = 150;
myComboBox.move(10, 10);
myComboBox.addEventListener(Event.CHANGE, changeHandler); // <- ASSIGN EVENT LISTENER
addChild(myComboBox);
var myLabel:Label = new Label();
myLabel.autoSize = TextFieldAutoSize.LEFT;
myLabel.text = "selectedIndex:" + myComboBox.selectedIndex;
myLabel.move(myComboBox.x + myComboBox.width + 10, myComboBox.y);
addChild(myLabel);
function changeHandler(event:Event):void { // <- ASSIGN FUNCTION
myLabel.text = "selectedIndex:" + myComboBox.selectedIndex;
}
Also from the docs, these are the events...
change
Dispatched when the user changes the selection in the ComboBox component or, if the ComboBox component is editable, each time the user enters a keystroke in the text field. ComboBox
close
Dispatched when the drop-down list is dismissed for any reason. ComboBox
enter
Dispatched if the editable property is set to true and the user presses the Enter key while typing in the editable text field. ComboBox
itemRollOut
Defines the value of the type property of an itemRollOut event object. ComboBox
itemRollOver
Defines the value of the type property of an itemRollOver event object. ComboBox
open
Dispatched when the user clicks the drop-down button to display the drop-down list. ComboBox
scroll
Dispatched when the user scrolls the drop-down list of the ComboBox component. ComboBox