get values of Jtextfields when click OK in Dialog - java

My need is to display a tab in a JDialog (confirmDialog or inputDialog). The tab contains 2 JTextField per row. The display works fine :
but I don't know how to get the values of the JTextFields.
Here is the display code :
int size = model.getCheckedApplications().size();
// une ligne par application sélectionnée
layout = new GridLayout(size + 1, 3, 5, 5);
myPanel = new JPanel(layout);
myPanel.add(new JLabel("Application"));
myPanel.add(new JLabel("Version cadre"));
myPanel.add(new JLabel("Nouvelles natures"));
for (Application app : model.getCheckedApplications()) {
myPanel.add(new JLabel(app.getCode88()));
JTextField versionActuelleField = new JTextField(30);
versionActuelleField.setName("versionActuelle"
+ app.getCode88());
versionActuelleField.setText(app
.getVersionCadreActuelle());
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
myPanel.add(versionActuelleField);
myPanel.add(nouvellesNaturesField);
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then I don't know how to get the values when the user clicks on the OK Button :
if (result == 0) { // The user clicks on the ok button

You need to add them to some list that you store, so you can get at them again. Since you are adding them in reference to an application, I would suggest a Map
private Map<Application, JTextField> nouvellesNaturesFields = new ArrayListMultimap<Application, JTextField>(); //Or Hashmap, if the key is unique
private Map<Application, JTextField> versionActuelleFields = new ArrayListMultiMap<Application, JTextField>();
public List<JTextField> getNouvellesNaturesFields() {
return nouvellesNaturesFields ;
}
public List<JTextField> getVersionActuelleFields () {
return versionActuelleFields ;
}
//class code
for (Application app : model.getCheckedApplications()) {
//Other code
JTextField nouvellesNaturesField = new JTextField(
30);
nouvellesNaturesField.setName("nouvellesNatures"
+ app.getCode88());
nouvellesNaturesFields.put(app, nouvellesNaturesField);
//Other code and same for your new nature fields
}
result = JOptionPane.showConfirmDialog(null, myPanel,
"Valeurs de cette version",
JOptionPane.OK_CANCEL_OPTION);
Then when the user clicks the confirm button, using the property accessor getNouvellesNaturesFields()or getVersionActuelleFields() you can iterate all the fields created, like so:
for (Map.Entry<Application, JTextField> entry: myMap.entries()) {
//Do something here
}
Or you could also get them via:
for (Application app : model.getCheckedApplications()) {
List<JTextField> data = myMap.get(app);
for(JTextField field : data) {
field.getText();
}
}
Since the key value probably won't be unique, I used an ArrayListMultiMap, but if it would be unique, then a HashMap should suffice

You assign the Jtextfield value to a string using the getText() method e.g below
String texfield = JTextField.getText();
Subsequently you use the String textfield wherever you want. And to get the right jtextfield you have to get text from the textfield you want for example you have four Jtexfield. Assuming they are JTextField1, JTextField2, JTextField3 and JTextField4. To get the value of JTextField3 you have
String texfield = JTextField3.getText();

The values should be in the JTextFields you created:
versionActuelleField
nouvellesNaturesField
Also, you might want to look at ParamDialog, which I implemented to be a generic solution to this question.
EDIT
Yes I see now that you are creating these JTextFields in a loop. So you need to create a Collection, I'd suggest a Map<String, JTextField> where you could map all of your application names to the matching JTextField, as well as iterate over the collection to get all application names / JTextFields.

Related

how to combine joptionpane with combobox

i want my joptionpane can combine with combobox,and the combobox data is in database, how i managed that.
i've tried change but the red code always show
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String wel = sdf.format(cal1.getDate());
String NamaFile = "/report/harianMasuk.jasper";
HashMap hash = new HashMap();
String tak = JOptionPane.showOptionDialog(null,id.getSelectedIndex()-1,"Laporan Supplier",JOptionPane.QUESTION_MESSAGE);
try {
hash.put("til", wel);
hash.put("rul", tak);
runReportDefault(NamaFile, hash);
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
Read the section from the Swing tutorial on Getting User Input From a Dialog.
It demonstrates how to display a combo box in a JOptionPane.
Not exactly sure what you are trying to accomplish but it appears to be that you want to utilize a JComboBox within a JOptionPane dialog window. This ComboBox would be filled with specific data from your database. The User is to select from this ComboBox and your application continues processing based on that selection. If this is the case then you might want to try something like this:
String selectedItem = "";
int selectedItemIndex = -1;
/* Ensure dialog never hides behind anything (use if
the keyword 'this' can not be used or there is no
object to reference as parent for the dialog). */
JFrame iframe = new JFrame();
iframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iframe.setAlwaysOnTop(true);
// ---------------------------------------------------
int btns = JOptionPane.OK_CANCEL_OPTION;
String dialogMessage = "<html>Select the desired item from the Drop-Down "
+ "list<br>you want to work with:<br><br></html>";
String dialogTitle = "Your Fav Items";
/* Up to you to gather what you want placed into the
JComboBox that will be displayed within the JOptionPane. */
String[] comboBoxItems = {"Your", "DB", "Items", "You", "Want", "To",
"Add", "To", "ComboBox"};
BorderLayout layout = new BorderLayout();
JPanel topPanel = new JPanel(layout);
JLabel label = new JLabel(dialogMessage);
topPanel.add(label, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
JComboBox cb = new JComboBox();
cb.setModel(new DefaultComboBoxModel<>(comboBoxItems));
cb.setSelectedIndex(-1);
centerPanel.add(cb, BorderLayout.CENTER);
topPanel.add(centerPanel);
// Ensure a selection or Cancel (or dialog close)
while (selectedItemIndex < 0) {
int res = JOptionPane.showConfirmDialog(iframe, topPanel, dialogTitle, btns);
if (res == 2) {
selectedItem = "Selection Option Was Canceled!";
break;
}
selectedItemIndex = cb.getSelectedIndex();
if (res == JOptionPane.OK_OPTION) {
if (selectedItemIndex == -1) {
JOptionPane.showMessageDialog(iframe, "<html>You <b>must</b> "
+ "select something or select <font color=red><b>Cancel</b></font>.",
"Invalid Selection...", JOptionPane.WARNING_MESSAGE);
}
else {
selectedItem = cb.getSelectedItem().toString();
}
}
iframe.dispose();
}
JOptionPane.showMessageDialog(iframe, "<html>You selected the ComboBox item:"
+ "<br><br><b><font color=blue><center>" + selectedItem + "</center>"
+ "</font></b><br></html>", "Selected Item", JOptionPane.INFORMATION_MESSAGE);
iframe.dispose();
With the above code, the Input dialog that will be displayed would look something like this:
It is up to you to find the means to fill the comboBoxItems String Array used within the code above.

How to make a jtextarea respond to another jtextarea change

JComboBox cBox = new JComboBox();
cBox.addItem("Food"); String x = "Food";
cBox.addItem("Shirt");
cBox.addItem("Computer");
cBox.setSelectedItem(null);
cBox.setBounds(56, 127, 336, 27);
contentPane.add(cBox);
tPName = new JTextArea();
tPName.setBounds(38, 227, 130, 26);
contentPane.add(tPName);
tPName.setColumns(10);
tSName = new JTextArea();
tSName.setBounds(262, 227, 130, 26);
contentPane.add(tSName);
tSName.setColumns(10);
JButton btn = new JButton("Further Details");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = (String) cBox.getSelectedItem(); //gets value of combo box
tPName.setText(name); //text area displays value
String x = (String) tPName.getText();
name = "Food"; tSName.setText(F);
name = "Shirt"; tSName.setText(S);
name ="Computer"; tSName.setText(C);
}
});
btn.setBounds(162, 166, 117, 29);
contentPane.add(btn);
how would I make tSName display a text corresponding to a specific value of tPName which is copied from a combobox where F, S and C strings stand for those corresponding values I want to use.
I'm not sure if I understand you correctly. You try to make one textarea display something, when the text of another textarea changes, am I right? If yes, you should look for an Event of the first Textbox (something like tPNameKeyTyped) in this Event you can check the tPName.getText() simply with
if(tPName.getText().equals("whatever")){
tSName.setText("whatever u want");
}
Is that what you are looking for?
I right now dont have pc so I cant check errors but.
this should work
tPName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tSName.setText(tPName.getText()); // put the value of tPName to tSName.
// i think this is all you want. i actually cant get your question.
// you can put a switch case to put coreesponding values in tSName. like:
switch(tPName.getText()){
case "a" : tSName.setText("1");
break;
//..... so on
default:
tSName.setText("stack overflow is great");
break;
}
}
});
EDIT:- Onece you do this try to refresh and validate the textareas.
tPName.validate();
tSName.validate();
tPName.repaint(); // refresh still not sure as i dont have pc if this not works try <your jframe>.repaint(); this should work

JTextArea displaying weird error message

I have checked all over internet looking for what may be causing this error... but I haven't been lucky. My code basically gets the text from a JTextField and a JComboBox and passes it to a JTextArea when the user presses a button. That's the code...
final JTextField quant = new JTextField(3);
final JTextArea list = new JTextArea(10,30);
list.setEditable(false);
JPanel entry = new JPanel();
entry.add(quant);
entry.add(optionProds);
JButton adiciona = new JButton("Adicionar");
entry.add(adiciona);
entry.add(list);
adiciona.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
list.setText(optionProds.getSelectedItem().toString() + "-" + quant);
System.out.print(list.getText());
}
});
finalAction.add(entry);
The problem is that when I press the button, the JTextArea won't display the name of the product and its amount, but the text below instead:
Gato-javax.swing.JTextField[,134,8,37x20,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#2034094f,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=3,columnWidth=11,command=,horizontalAlignment=LEADING]
What could be causing this?
use
list.setText(optionProds.getSelectedItem().toString() + "-" + quant.getText());
instead of
list.setText(optionProds.getSelectedItem().toString() + "-" + quant);
why do you print quant? quant is a jtextfiled .that's not a error .this is what you get when you print a jcomponent .when you print a jcomponent you get properties and values such as location,border,margin...etc. so you should print the text using getText() method

Display selected Item in JComboBox when item is clicked

I currently have 2 JComboBoxes. When an item in the first JComboBox is selected, relevant items are displayed in JComboBox2. However when I try to select the items in the second JComboBox it keeps returning to default. However it is registering the value of the item that is selected, just not displaying the selected item in the JComboBox.
Here is a snippet of my code:
mainComboBox = new JComboBox( treeItems);
mainComboBox.addActionListener( this );
getContentPane().add( mainComboBox, BorderLayout.WEST );
// Create sub combo box with multiple models
subComboBox = new JComboBox();
subComboBox.addActionListener(this);
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
getContentPane().add( subComboBox, BorderLayout.EAST );
String [] chromalveolataItems = chromalveolataTreeSet.toArray(new String[chromalveolataTreeSet.size()]);
subItems.put(treeItems[1], chromalveolataItems);
String [] mycetozoaItems = mycetozoaTreeSet.toArray(new String[mycetozoaTreeSet.size()]);
subItems.put(treeItems[2], mycetozoaItems);
String [] metazoaItems = metazoaTreeSet.toArray(new String[metazoaTreeSet.size()]);
subItems.put(treeItems[3], metazoaItems);
String [] viridiplantaeItems = viridiplantaeTreeSet.toArray(new String[viridiplantaeTreeSet.size()]);
subItems.put(treeItems[4], viridiplantaeItems);
String [] virusesItems = virusesTreeSet.toArray(new String[virusesTreeSet.size()]);
subItems.put(treeItems[5], virusesItems);
.
#Override
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
String organismComboItem = (String)subComboBox.getSelectedItem();
if(treeArray.contains(organismComboItem)){
//System.out.println(treeArray.indexOf(organismComboItem));
String selectedId = idArray.get(treeArray.indexOf(organismComboItem));
System.out.println(selectedId);
}
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
There is probably a relatively simple solution to this however I am new to Java so please forgive me.
Any help whatsoever would be much appreciated! :)
Looks to me like you based your code on the example found in this posting: Binding comboboxes in swing (or one like it).
When you use examples don't add extra code.
subComboBox.addActionListener(this);
The example does not do this. By adding the same listener to the subComboBox you are telling it to reset itself every time you select an item from it. Only the mainComboBox needs the ActionListener.

Writing actionListner to display form input on console upon confirmation

I am currently constructing a GUI which allows me to add new cruises to the system. I want to write an actionListner which once the user clicks on "ok" then the form input will be displayed as output on the console.
I currently have the following draft to complete this task:
ok = new JButton("Add Cruise");
ok.setToolTipText("To add the Cruise to the system");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
int selected = typeList2.getSelectedIndex();
String tText = typeList2[selected];
Boolean addtheCruise = false;
addtheCruise = fleet.addCruise();
fleet.printCruise();
if (addtheCruise)
{
frame.setVisible(false);
}
else
{ // Report error, and allow form to be re-used
JOptionPane.showMessageDialog(frame,
"That Cruise already exists!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
buttonPanel.add(ok);
Here is the rest of the code to the Form input frame:
contentPane2 = new JPanel (new GridLayout(18, 1)); //row, col
nameInput = new JLabel ("Input Cruise Name:");
nameInput.setForeground(normalText);
contentPane2.add(nameInput);
Frame2.add(contentPane2);
Cruisename = new JTextField("",10);
contentPane2.add(Cruisename);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
confirmPanel = new JPanel ();
confirmPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
confirmPanel.setBorder(BorderFactory.createLineBorder(Color.PINK));
addItinerary = new JButton("Add Itinerary");
confirmPanel.add(Add);
confirmPanel.add(addItinerary );
Frame2.add(confirmPanel, BorderLayout.PAGE_END);
Frame2.setVisible(true);
contentPane2.add(Cruisename);
Frame2.add(contentPane2);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
contentPane2.setBorder(BorderFactory.createLineBorder(Color.black));
//Label for start and end location jcombobox
CruiseMessage = new JLabel ("Enter Start and End Location of new Cruise:");
CruiseMessage.setForeground(normalText);
contentPane2.add(CruiseMessage);
Frame2.add(contentPane2);
/**
* creating start location JComboBox
*/
startL = new JComboBox();
final JComboBox typeList2;
final String[] typeStrings2 = {
"Select Start Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
startL = new JComboBox(typeStrings2);
contentPane2.add(startL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
/**
* creating end location JComboBox
*/
endL = new JComboBox();
final JComboBox typeList3;
final String[] typeStrings3 = {
"Select End Location", "Tobermory","Oban", "Isle of Mull", "Isle of Harris",
"Lewis and Harris", "Stornoway", "Skye", "Portree"};
endL = new JComboBox(typeStrings3);
contentPane2.add(endL);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
// add spacing between comboboxes
contentPane2.add(Box.createRigidArea(new Dimension(5,0)));
//Label for select ship jcombobox
selectShipM = new JLabel ("Select Ship to assign Cruise:");
selectShipM.setForeground(normalText);
contentPane2.add(selectShipM);
Frame2.add(contentPane2);
/**
* creating select ship JCombobox
* select ship to assign cruise
*/
selectShip = new JComboBox();
final JComboBox typeList4;
final String[] typeStrings4 = {
"Select Ship", "Dalton Princess", "Stafford Princess" };
selectShip = new JComboBox(typeStrings4);
contentPane2.add(selectShip);
Frame2.add(contentPane2, BorderLayout.CENTER);
Frame2.setVisible(true);
I need all form inputs from the code above to be displayed on the console upon completion.
Summary:
1. I have two ships in one fleet
2. To add new cruise, all fields (Name, start date, end date, ship) must be selected.
The Problem:
1. I keep coming up with errors when creating " fleet = new Fleet();" in my constructor. Even though I have declared it in my class.
2. In the draft code below, line 5 states "typeList2", however, I have two JComboBox's - two different type Strings for both drop down menu's (Shown in the rest of the code). How do I input both typeLists to the output rather than just one?
Thank you.

Categories

Resources