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.
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 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;
}
I am very new to this site and a novice programmer so I'm hoping someone here can help me with the problem I'm facing. I am making a simple program that uses a card layout to select/enter several user-specific options that will be stored in string variables and then after the last question, used to give a unique answer. Right now the program advances slide's successfully and displays the proper question, however it does not clear the JRadioButton from the first card and keeps using this radio button instead of the desired component for the duration of the program. For example, The second and third card should have JTextField's while the 4th card should have a JComboBox. I have two main class files, one that is the actual frame and the other that is displayed below which does the work behind the scenes. For future reference, I plan to modify this into an applet once it is working properly so any advice on that would be great. Any help will be greatly appreciated, thanks.
I believe the problem may stem from the creation of multiple card objects here, the ScreenPanel objects each take the same parameters but depending on the different card, a different Component needs to be produced.
// set up questions
String question1 = "Sex: ";
String[] responses1 = {"Female", "Male"};
ask[0] = new ScreenPanel(question1, responses1);
String question2 = "Height in inches: ";
String[] responses2 = new String[1];
ask[1] = new ScreenPanel(question2, responses2);
String question3 = "Weight in pounds: ";
String[] responses3 = new String[1];
ask[2] = new ScreenPanel(question3, responses3);
String question4 = "Event: ";
String[] responses4 = {"Shot Put", "Discus Throw", "Long Jump", "Triple Jump", "High Jump", "Pole Vault", "4 x 800 Relay", "100 Meter Hurdles", "100 Meter Dash", "4 x 200 Relay",
"1600 Meter Run", "4 x 100 Relay", "400 Meter Dash", "300 Meter Hurdles", "800 Meter Run", "200 Meter Dash", "3200 Meter Run", "4 x 400 Relay"};
ask[3] = new ScreenPanel(question4, responses4);
String question5 = "Distance(inches) or Time(seconds)";
ask[4] = new ScreenPanel(question5, new String[1]);
ask[4].setFinalQuestion(true);
addListeners();
}
The Screen Panel class here creates each card, could be a problem with the conditionals but not sure.
class ScreenPanel extends JPanel{
JLabel question;
JRadioButton[] response1;
JTextField response2;
JTextField response3;
JComboBox response4;
JTextField response5;
JButton nextButton = new JButton("Next");
JButton finalButton = new JButton("Finish");
String textResponse1, textResponse2, textResponse3, textResponse4, textResponse5;
ScreenPanel(String ques, String[] resp){
super();
setSize(320, 260);
question = new JLabel(ques);
JPanel sub1 = new JPanel();
JPanel sub2 = new JPanel();
sub1.add(question);
if (TrackAndField.currentScreen == 0){
response1 = new JRadioButton[resp.length];
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < resp.length; i++){
response1[i] = new JRadioButton(resp[i], false);
group.add(response1[i]);
sub2.add(response1[i]);
}
// textResponse1 = group.getSelection().toString();
}
if (TrackAndField.currentScreen == 1){
sub2.remove(response1[0]);
sub2.remove(response1[1]);
response2 = new JTextField(4);
KeyAdapter monitor = new KeyAdapter() {
public void keyTyped(KeyEvent event){
textResponse2 = response2.getText();
}
};
sub2.add(response2);
}
if (TrackAndField.currentScreen == 2){
sub2.remove(response2);
response3 = new JTextField(10);
KeyAdapter monitor = new KeyAdapter() {
public void keyTyped(KeyEvent event){
textResponse3 = response3.getText();
}
};
sub2.add(response3);
}
if (TrackAndField.currentScreen == 3){
sub2.remove(response3);
response4 = new JComboBox(resp);
sub2.add(response4);
textResponse4 = response4.getSelectedItem().toString();
}
Solved by adding an extra string parameter as an ID for the component and used that for the conditionals instead of currentScreen
I was wondering if it is possible to put multiple inputs in JOptionPane.showInputDialog and then get the user input and if the user has given a wrong input for one of the questions then provide them with a error, asking them to re-enter that specific data again.
For example, in the input I want questions like;
How many times have to been out? between 1-10.
Do you like number 1 or 2 or 3?
Please state for how many hours your have between 1-10 you have stop in a restaurant?
and I will need to add some more at a later stage.
So instead of have a JOptionPane.showInputDialog for each question like this:
int timeout;
do {
String timeoutinputbyuser = JOptionPane.showInputDialog("How many times have to been out? between 1-10.");
timeout = Integer.parseInt(timeoutinputbyuser);
} while (timeout < 1 || timeout > 10);
I want to have all the questions in one and provide a suitable error if the user gets any question wrong.
No, the input dialog only accepts a single input area.
Put the components in a JPanel and display it in a JOptionPane.showMessageDialog(..). Note that you can then have better components:
A JSpinner for selecting a number.
JRadioButton objects in a ButtonGroup for the choice of 3..
Try this
JTextField field1 = new JTextField();
JTextField field2 = new JTextField();
JTextField field3 = new JTextField();
JTextField field4 = new JTextField();
JTextField field5 = new JTextField();
Object[] message = {
"Input value 1:", field1,
"Input value 2:", field2,
"Input value 3:", field3,
"Input value 4:", field4,
"Input value 5:", field5,
};
int option = JOptionPane.showConfirmDialog(parent, message, "Enter all your values", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION)
{
String value1 = field1.getText();
String value2 = field2.getText();
String value3 = field3.getText();
String value4 = field4.getText();
String value5 = field5.getText();
}
Backgorund info:
I have a buddy of mine in the Navy, and he wanted to know if I could whip him up a small app that would calcualte when he has his guard duty, because apparently counting on a calendar is hard. I used JOptionPane.showMessageDialog to give him the output of the dates. Here's how I'm doing that.
GregorianCalendar knownDate = new GregorianCalendar(year,month,day);
GregorianCalendar[] futureDates = new GregorianCalendar[10];
for(int i = 0; i < 10; i++) {
futureDates[i] = new GregorianCalendar(year,month,day);
futureDates[i].add(Calendar.DAY_OF_MONTH,10*(i+1)); // duty every 10 days
}
String newline = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder("Jakes duty dates:").append(newline);
for(GregorianCalendar d : futureDates) {
sb.append(months[d.get(Calendar.MONTH)]).append(" ");
sb.append(d.get(Calendar.DAY_OF_MONTH)).append(newline);
}
JOptionPane.showMessageDialog(null,sb.toString());
The 'only problem' is you can't select the text that is displayed. He'd like to select it for IM and email, because what's the point in only being half lazy, right? (Only problem is in quotes because I have a feeling he'll scope creep this to death... haha)
My question:
Is there a "one-line solution" to making a selectable showMessageDialog?
I was able to build on trashgod's answer. While he suggested using a JList, I'm instead using a JTextArea (which gives the kind of selection I need.)
Here's what I'm doing:
JTextArea text = new JTextArea(sb.toString());
JOptionPane.showMessageDialog(null,text);
And it's working like a charm!
================================================
After a little experimentation I did this:
DefaultListModel model = new DefaultListModel();
for(GregorianCalendar g : futureDates) {
String m = months[g.get(Calendar.MONTH)];
String d = String.valueOf(g.get(Calendar.DAY_OF_MONTH));
model.addElement(m + " " + d);
}
JList jlist = new JList(model);
JOptionPane.showMessageDialog(null,jlist);
JOptionPane.showMessageDialog(null,jlist.getSelectedValue());
And the second box displayed what I had selected on the first one. I was really impressed with that. Now granted, this isn't the functionality I was going for (the top section is) but that doesn't make it any less awesome! :-)
Add the dates to a DefaultListModel, create a JList, and pass the list to showMessageDialog(). It's more than one line, but the selection copies to the clipboard using the platform's copy keystroke.
private static final DateFormat df = new SimpleDateFormat("dd-MMM");
private static void createAndShowGUI() {
DefaultListModel dlm = new DefaultListModel();
for (int i = 0; i < 10; i++) {
GregorianCalendar knownDate = new GregorianCalendar();
knownDate.add(Calendar.DAY_OF_MONTH, 10 * i);
dlm.add(i, df.format(knownDate.getTime()));
}
JList list = new JList(dlm);
JOptionPane.showMessageDialog(null, list);
}