I need to check if a JList / DefaultListModel contains an item. The item I am checking is a String that changes after a "$" sign.
Here is a pseudo version of the code I'm working with.
String theItem = "Bananas";
BigDecimal theQuantity = new BigDecimal(quantity.getText());
BigDecimal thePrice = new BigDecimal(0.00); //This changes depending on quanitity
thePrice = thePrice.setScale(2, BigDecimal.ROUND_HALF_UP);
if (!dlm.contains(whatGoesHere)) {
dlm.addElement(theItem + " $" + thePrice.toString());
jList.setModel(dlm);
//More code
} else {
JOptionPane.showMessageDialog(mainPanel, "You already selected that item", "Error Dialog", JOptionPane.ERROR_MESSAGE);
return;
}
I solved the problem by making a separate DefaultListModel which contains only the selected item. This is used in the validation IF Statement.
Here is the working code:
DefaultListModel validatorDLM = new DefaultListModel(); //Specifically for validation
DefaultListModel orderDLM = new DefaultListModel();
String theItem = "Bananas"; //This changes with combo box
BigDecimal theQuantity = new BigDecimal(quantity.getText());
BigDecimal thePrice = new BigDecimal(0.00); //This changes depending on quanitity
thePrice = thePrice.setScale(2, BigDecimal.ROUND_HALF_UP);
if (!validatorDLM.contains(theItem)) {
validatorDLM.addElement(theItem);
orderDLM.addElement(theItem + " $" + thePrice.toString());
jList.setModel(orderDLM);
//More code
} else {
JOptionPane.showMessageDialog(mainPanel, "You already selected that item", "Error Dialog", JOptionPane.ERROR_MESSAGE);
return;
}
Related
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.
I'm try to print some data in this order:
Herder
Date(Jtextfield)
Invoice no(Jtextfield)
Jtable
Amount (Jtextfield)
Footer
MessageFormat header = new MessageFormat("Building Materials Coperation Ltd");
MessageFormat footer = new MessageFormat("Thank you! Come again..");
MessageFormat Date = new MessageFormat("Date " + txt_date.getText());
MessageFormat Inoice_no = new MessageFormat("Invoice No " + txt_invoice_no.getText());
MessageFormat Amount = new MessageFormat("Total Amount:- Rs" + txt_Total_amount.getText());
try {
PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
jTable2.print(JTable.PrintMode.FIT_WIDTH, header, Date, false, set, false);
jTable2.print(JTable.PrintMode.FIT_WIDTH, Inoice_no, Amount, false, set, false);
jTable2.print(JTable.PrintMode.FIT_WIDTH, Inoice_no, footer, false, set, false);
} catch (java.awt.print.PrinterException e) {
JOptionPane.showMessageDialog(null, "\n" + "Error from Printer Job "
+ "\n" + e);
}
So i have got print but,it gets 3 pop ups window to print it
How can i print in order
I hope,you will help me to find that
(Can you give me and examples,Its big help)
Thanks
Im really not sure as how to word this question. But im gonna try my best here. Bear with me if you could :)
I have a database with 3 tables (that i am dealing with right now). Fortunately they all have the same amount of columns. Im trying to input values into them using a "popup" form. (Not sure how to do that, but im using this link here as a guideline, and hoping it works)
Here is the code i have written for that method so far..
public form(int option, String val1, String val2, String val3, String val4, String val5)
{
val1 = null;
val2 = null;
val3 = null;
val4 = null;
val5 = null;
JTextField val1Field = new JTextField(20);
JTextField val2Field = new JTextField(20);
JTextField val3Field = new JTextField(20);
JTextField val4Field = new JTextField(20);
JTextField val5Field = new JTextField(20);
String name;
String lbl1 = null;
String lbl2 = null;
String lbl3 = null;
String lbl4 = null;
String lbl5 = null;
switch(option)
{
case 1: //if customer
name = "Customer Information";
lbl1 = "Customer No:";
lbl2 = "Customer Name:";
lbl3 = "Company Name:";
lbl4 = "Contact Number: ";
lbl5 = "Discount Rate:";
case 2: //if item
name = "Item Information";
lbl1 = "Item No:";
lbl2 = "Item Name:";
lbl3 = "Cost Price:";
lbl4 = "Selling Price: ";
lbl5 = "Stock:";
case 3: //if user
name = "Staff Information";
lbl1 = "Staff ID:";
lbl2 = "Full Name:";
lbl3 = "Username:";
lbl4 = "Password: ";
lbl5 = "adminusercheck:";
default:
JOptionPane.showMessageDialog(alphaPOS,
"Something went wrong! Try again!",
"ERROR",
JOptionPane.ERROR_MESSAGE);
}
JPanel formPanel = new JPanel();
formPanel.add(new JLabel(lbl1));
formPanel.add(val1Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl2));
formPanel.add(val2Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl3));
formPanel.add(val3Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl4));
formPanel.add(val4Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl5));
formPanel.add(val5Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
int result = JOptionPane.showConfirmDialog(null, formPanel,
name, JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
val1 = val1Field.getText();
val2 = val2Field.getText();
val3 = val3Field.getText();
val4 = val4Field.getText();
val5 = val5Field.getText();
}
return(option, val1, val2, val3, val4, val5);
}
Now.. it took me a while to realize that i cannot return values like that, and that i could instead return the object instead. I have a class made for each of these "tables" (Item, Customer and Staff).
But.. the thing is in the method above i need to use a switch so that i can have the labels made according to the type of Table.
So my question is, is there a way to pass the object and its name into the method? Or do i have it all wrong?
Any help is much appreciated.
It looks to me like you don't really need to return option since you never change it. Also, it looks like you were trying to have the caller pass variables into the method and let the method fill in the values of those variables. But Java doesn't have "output" or "reference" parameters the way C++ and PHP do, so this doesn't work. (You can pass in a reference to a mutable object and have a method set a field in that object, but you can't do that with String since it's immutable.)
If that's the case, then since the 5 things you want to return are all the same type, you could just make your method return a String[]:
public String[] form(int option)
{
String[] values = new String[] (5);
//values[0] = null; // not necessary since the array elements will already be null
//values[1] = null; ...
...
if (result == JOptionPane.OK_OPTION)
{
values[0] = val1Field.getText();
values[1] = val2Field.getText();
values[2] = val3Field.getText();
values[3] = val4Field.getText();
values[4] = val5Field.getText();
}
return values;
}
P.S. I recommend using arrays or ArrayList instead of separate variables like val1Field, val2Field, etc., so that you don't have to repeat code like this.
While there is a way to kind of do this, I would like to point out that this is not a good design! Don't generalize methods! I think that you need to try to redesign your code instead. If one of your classes changes, you will end up breaking them up anyway. Create a handler for each form type. You can do this using Factory pattern and then get the appropriate form, based on that. Might be a bit more work, but you will thank me later :)
If you need help on design, then that is something that we can definitely discuss.
So I tried finding a tutorial on how to do this but nothing gets this complicated. This is the first I am learning of HAshMaps so I am sure my solution should be easy, but I don't know how to do it.
I am trying to use an Array to populate a HashMap, and when I run the program my print out shows up null, which indicates that it isn't populating for me. Been working on this for two days, and am really lost and confused.
I am trying to get my key "expenses" to be valued with a "type".
Edit: I would like my case two to be a printout of
1: groceries
2: Entertainment
3: Etc.....
public static void main(String[] args) throws FileNotFoundException, IOException
{
// TODO code application logic here
// HashMap<String, String> map = new HashMap<String, String>();
HashMap<String, List<Expenses>> map = new HashMap<>();
List <Expenses> expenseType = new ArrayList();
double amount, totalAmount;
int cmd, year, month, date;
String type, resp;
totalAmount = 0;
String fname = JOptionPane.showInputDialog("Enter the name of the budget file, none if no file");
if (fname.compareTo("none") !=0)
{
FileInputStream ist = new FileInputStream(fname);
ObjectInputStream ifile = new ObjectInputStream(ist);
}
boolean done = false;
while(!done)
{
resp = JOptionPane.showInputDialog("Enter a command from: \n"
+ "\t1:Add a new deduction\n" //think its done
+ "\t2:Add a new expense\n" //this is done, but could be made better wit
+ "\t3:Add a deposit\n" //This is done
+ "\t4:Deduction options\n"
+ "\t5:Expense Options\n"
+ "\t6:Total balances in bank\n"
+ "\t7:quit");
cmd = Integer.parseInt(resp);
switch(cmd)
{
case 1:
break;
case 2:
//Give the option to add new spending occurence.
//Give option to choose from array of spending types.
resp = JOptionPane.showInputDialog("Enter a command from: \n"
+ "\t1: Create a new expense\n" //done
+ "\t2: Choose from expense list\n"
+ "\t3:quit");
int cmd2 = Integer.parseInt(resp);
switch (cmd2)
{
case 1:
type = JOptionPane.showInputDialog("Enter the type of the expense:");
resp = JOptionPane.showInputDialog("Enter the amount of the expense:");
amount = Double.parseDouble(resp);
resp = JOptionPane.showInputDialog("Enter the year of the expense:");
year = Integer.parseInt(resp);
resp = JOptionPane.showInputDialog("Enter the month of the expense:");
month = Integer.parseInt(resp);
resp = JOptionPane.showInputDialog("Enter the date of the expense:");
date = Integer.parseInt(resp);
// List<Expenses> expenses = map.get(type);
// Does the map have a List for type?
if (expenseType == null) {
// No. Add one.
expenseType = new ArrayList<>();
map.put(type, expenseType);
}
Expenses e = new Expenses(type, amount, year, month, date);
expenseType.add(e);
// map.put(type, new ArrayList(expenses));
map.put(type, expenseType);
break;
case 2:
//Use a hashmap to search through the ArrayLIst and print out options.
//How do I populate the HashMap?
type = null;
List<Expenses> typelist = map.get(type); //reads from map
System.out.println(typelist);
break;
}
}
}
}
}
Please don't use raw types. And, if I understand you, then you want something like
Map<String, List<Expenses>> map = new HashMap<>();
Then, to add to the List in the Map - use something like
List<Expenses> expenses = map.get(type);
// Does the map have a List for type?
if (expenses == null) {
// No. Add one.
expenses = new ArrayList<>();
map.put(type, expenses);
}
Expenses e = new Expenses(type, amount, year, month, date);
expenses.add(e);
1) You should have this line
map.put(new String(type),expenses);
instead of
map.put(expenses, new String(type));
to get value from hashmap using key i.e. type.
2) Also remove double quotes from
List<Expenses> typelist = map.get("type");
to pass variable type.
I have a SimpleComboBox in GUI which contains some duplicate items also. Assume there are 3 items which is same as "domain". When i select second "domain" or third "domain", the selected item and selected index is always pointing to first occurance of "domain". How can i correct, so that the selected index/item is right one, instead of first occurance of item?
ComboBox with duplicate values:
When i select "domain" at fourth occurence it will always pointing the first occurance of "domain".
Output:
When i select the "192.168.1.30" at last occurenece, it will point the first occurance of "192.168.1.30".
Please any one help me.
private SimpleComboBox<String> domainName = new SimpleComboBox<String>();
domainName = WidgetUtil.getStringCombo("Domain Name", 12, true, domainNameList, null);
domainName.addSelectionChangedListener(getReportSelectionListener());
domainName.setForceSelection(true);
domainName.setTriggerAction(TriggerAction.ALL);
private Button New, add, remove;
New = WidgetUtil.getButton("New", "new", "");
New.addSelectionListener(buttonAction());
thirdLayoutContainer.add(New);
add = WidgetUtil.getButton("Add", "add", "");
add.addSelectionListener(buttonAction());
add.setStyleAttribute("paddingTop", "10px");
thirdLayoutContainer.add(add, formData);
remove = WidgetUtil.getButton("Remove", "remove", "");
remove.addSelectionListener(buttonAction());
public void componentSelected(ButtonEvent ce){
String domain_name = null;
if (ce.getComponent().getId().equals("remove")){
System.err.println("Clicked remove button...");
domain_name = domainName.getRawValue();
domainNameList.remove(domain_name);
systemDetailsMap.remove(domain_name);
systemDetailsMap.remove(domain_name + "_USER_NAME");
systemDetailsMap.remove(domain_name + "_HOST_NAME");
systemDetailsMap.remove(domain_name + "_PASSWORD");
domainName.removeAll();
domainName.add(domainNameList);
userName.clear();
hostName.clear();
password.clear();
System.err.println("After remove domain name list ---> " + domainNameList);
System.err.println("After remove map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("add")) {
System.err.println("Clicked add button...");
domain_name = domainName.getRawValue();
domainNameList.add(domain_name);
systemDetailsMap.put(domain_name, domain_name);
systemDetailsMap.put(domain_name + "_HOST_NAME", hostName.getValue());
systemDetailsMap.put(domain_name + "_USER_NAME", userName.getValue());
systemDetailsMap.put(domain_name + "_PASSWORD", password.getValue());
// domainName.clear();
domainName.add(domainNameList);
// domainName.reset();
System.err.println("After add domain name list ---> " + domainNameList);
System.err.println("After add map ---> " + systemDetailsMap);
} else if (ce.getComponent().getId().equals("new")) {
System.err.println("Clicked new button...");
userName.clear();
hostName.clear();
password.clear();
domainName.removeAllListeners();
domainName.removeAll();
domainName.clear();
domainName.setEmptyText("Add a new domain");
userName.setEmptyText("Add a new username");
hostName.setEmptyText("Add a new hostname");
password.setEmptyText("Add a new password");
domainName.addSelectionChangedListener(getReportSelectionListener());
}
}
};
private SelectionChangedListener<SimpleComboValue<String>> getReportSelectionListener(){
SelectionChangedListener<SimpleComboValue<String>> ReportListener = new SelectionChangedListener<SimpleComboValue<String>>() {
#Override
public void selectionChanged(SelectionChangedEvent<SimpleComboValue<String>> se) {
SimpleComboValue<String> selectedValue = se.getSelectedItem();
String value = selectedValue.getValue();
System.err.println("Selected Value ---> " + selectedValue.getValue());
if (value != null && !value.equals("---New---") ){
userName.clear();
hostName.clear();
password.clear();
userName.setValue(systemDetailsMap.get(value + "_USER_NAME").toString());
hostName.setValue(systemDetailsMap.get(value + "_HOST_NAME").toString());
password.setValue(systemDetailsMap.get(value + "_PASSWORD").toString());
}
}
};
return ReportListener;
}
Please help me. Thanks in advance.
I am not using Ext-gwt just the standard ext-js, but I think I know what you need! You should define a display and value field.
Ext.create('Ext.form.ComboBox', {
store: xyz,
queryMode: 'local',
displayField: 'name',
valueField: 'id',
renderTo: Ext.getBody()
});
You just have to make sure, that the duplicated items are getting unique id. I think that if this is possible in ext-js it should also be possible in ext-gwt!