Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
First of all, I'm new in java.
I would like to generate forms dynamically based on Arrays, I was able to generate the fields, but I do not know how to read them, I couldn't find something like text field index or something.
So basically i'm asking how to read values from a TextField component that has no reference.
JTextField myText = new JTextField() vs new JTextField(), added to a panel
Below is a simple code example, any idea is welcomed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame{
private JPanel p1 = new JPanel();
private JButton btn = new JButton("Read Data");
public Test(){
super("Dynamic Form");
setLayout(new GridLayout(4,2));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// Declare the Array with fields
String[] fList = new String[3];
fList[0] = "id";
fList[1] = "firstName";
fList[2] = "lastName";
//Iterate fields array and add elements
for(int i = 0; i<fList.length; i++){
add(new JLabel(fList[i]));
add(new JTextField("field: "+fList[i]));
}
add(p1);
add(btn);
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev){
String id = "id field value is: "; // + some code to get actual text field value
String firstName = "firstName field value is: "; // + some code to get actual text field value
String lastName = "lastName field value is: "; // + some code to get actual text field value
System.out.println(id+ " " + firstName + " " + lastName);
}
}
);
pack();
setLocationRelativeTo(null);
setResizable(true);
setVisible(true);
}
public static void main(String [] args){
new Test();
}
}
You need to store references to those text fields somewhere.
List<JTextField> fields = new ArrayList<>();
...
for(int i = 0; i<fList.length; i++){
JTextField field= new JTextField("field: "+fList[i]);
add(new JLabel(fList[i]));
add(field);
fields.add(field);
}
Now you can access them from your fields list:
public void actionPerformed(ActionEvent ev){
String id = "id field value is: " + fields.get(0).getText();
String firstName = "firstName field value is: " + fields.get(1).getText();
String lastName = "lastName field value is: " + fields.get(2).getText();
System.out.println(id+ " " + firstName + " " + lastName);
}
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm using JCreator Pro. I'm trying to get information entered in the textfields to display and calculate the selling price of used cars. The window looks like this:
When I click display, I want the information to appear on the bottom half of the window (car make and model, year of manufacturing, sale price)
But when I do click it, all I get are these lines of text in the General output window and I can't make out what's wrong. My code compiles without any errors.
Here's my main class for reference:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MIT141674CarDetailsTest extends JFrame implements ActionListener {
MIT141674Car car;
JTextField jtfMakeModel, jtfYear, jtfPurchPrice;
JButton jbtnDisplay, jbtnClear;
JLabel jlblMakeModel, jlblYear, jlblSellPrice;
public MIT141674CarDetailsTest() {
setSize(500, 210);
setLocationRelativeTo(null);
setTitle("Purchased car details");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new GridLayout(7, 2));
// input
add(new JLabel(" Enter car make and model: "));
jtfMakeModel = new JTextField();
add(jtfMakeModel);
add(new JLabel(" Enter year of manufacturing: "));
jtfYear = new JTextField();
add(jtfYear);
add(new JLabel(" Enter purchase price: "));
jtfPurchPrice = new JTextField();
add(jtfPurchPrice);
// buttons
jbtnDisplay = new JButton("Display");
add(jbtnDisplay);
jbtnDisplay.addActionListener(this);
jbtnClear = new JButton("Clear all");
add(jbtnClear);
jbtnClear.addActionListener(this);
// display car
add(new JLabel(" Car make and model: "));
jlblMakeModel = new JLabel("");
add(jlblMakeModel);
add(new JLabel(" Year of manufacturing: "));
jlblYear = new JLabel("0000");
add(jlblYear);
add(new JLabel(" Sale price: "));
jlblSellPrice = new JLabel("$0.00");
add(jlblSellPrice);
}
public static void main(String[] args) {
MIT141674CarDetailsTest carWin = new MIT141674CarDetailsTest();
carWin.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("Display")) {
int carYear = Integer.parseInt(jtfYear.getText());
if (carYear >= 2009) {
double pPrice = Double.parseDouble(jtfPurchPrice.getText());
if (pPrice > 0) {
car = new MIT141674Car(jtfMakeModel.getText(),
carYear, pPrice);
jlblMakeModel.setText(car.getMakeModel());
jlblYear.setText(Integer.toString(car.getYear()));
jlblSellPrice
.setText(Double.toString(car.getSellingPrice()));
} else
// pPrice <=0 - invalid
JOptionPane.showMessageDialog(null,
"Invalid purchase price, please re-enter");
} // carYear <=2009
else
// invalid carYear
JOptionPane.showMessageDialog(null,
"Invalid year of manufacturing, please re-enter");
} // if display
else
// not Display button, then check if it's Clear all button
if (str.equals("Clear all")) {
// remove text from all text fields
jtfMakeModel.setText("");
jtfYear.setText("");
jtfPurchPrice.setText("");
// clear labels
jlblMakeModel.setText("");
jlblYear.setText("0000");
jlblSellPrice.setText("$0.00");
}
} // actionPerformed
} // end of class
Can anyone help me and tell me what is wrong?
EDIT: I have partially solved my problem by doing what #Exbury mentioned by changing
car = new MIT141674Car (jtfMakeModel.getText(), car.getYear(), car.getSellingPrice());
to
car = new MIT141674Car (jtfMakeModel.getText(), carYear, pPrice);
But now I've found that the year entered only displays if I enter 2009, any other years entered after 2009 comes up as 0.
Giving one class a getter/accessor method that extracts the desired information of JTextField and giving the other class a setter/mutator method that allows outside objects to inject the desired information, here to set the text of its JLabel
While creating car object you are using same car reference (null) in constructor
Change this to
car = new MIT141674Car (jtfMakeModel.getText(), car.getYear(), car.getSellingPrice());`
to
car = new MIT141674Car (jtfMakeModel.getText(), carYear, pPrice);
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.
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
Below is the code I am working on. Basically I need a box to open and get the user to input their data in the corresponding text fields. All is working great. Everything is outputting correctly when I print it from the actionPerformed method, but when I call gui.displayPersonInfo method from main it shows all of the values as null. It is doing the displayPersonInfo method first before the box has even opened, even though I call the method after. Anyone know what is wrong with my code? (output below)
package userInput;
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Person extends JFrame{
String Name;
String Address;
String PhoneNumHome;
String PhoneNumWork;
String email;
JLabel label, label2;
JTextField tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8;
JButton button;
public Person(){
setLayout(new FlowLayout());
label = new JLabel("Enter your name");
add(label);
tf1 = new JTextField(10);
add(tf1);
label = new JLabel("Enter your Address (street number + street name)");
add(label);
tf2 = new JTextField(10);
add(tf2);
label = new JLabel("Enter your city");
add(label);
tf3 = new JTextField(10);
add(tf3);
label = new JLabel("Enter your province");
add(label);
tf4 = new JTextField(10);
add(tf4);
label = new JLabel("Enter your postal code");
add(label);
tf5 = new JTextField(10);
add(tf5);
label = new JLabel("Enter your home phone number (306-xxx-xxx)");
add(label);
tf6 = new JTextField(10);
add(tf6);
label = new JLabel("Enter your work phone number (306-xxx-xxx)");
add(label);
tf7 = new JTextField(10);
add(tf7);
label = new JLabel("Enter your email (user#emailservice.xxx");
add(label);
tf8 = new JTextField(10);
add(tf8);
button = new JButton("Next");
add(button);
event e = new event();
button.addActionListener(e);
}
public class event implements ActionListener{
public void actionPerformed(ActionEvent e){
String address1, pnum, wnum, a;
try{
String word = tf1.getText();
Name = word;
System.out.println(Name);
Address = tf2.getText();
Address = Address + " " + tf3.getText();
Address = Address + " " + tf4.getText();
Address = Address + " " + tf5.getText();
address1 = Address;
System.out.println(Address);
PhoneNumHome = tf6.getText();
pnum = PhoneNumHome;
PhoneNumWork = tf7.getText();
wnum = PhoneNumWork;
email = tf8.getText();
a = email;
System.out.println(PhoneNumHome);
System.out.println(PhoneNumWork);
System.out.println(email);
saveInfo(word, address1, pnum, wnum, a);
displayPersonInfo();
System.exit(0);
}catch(Exception ex){}
}
}
public void displayPersonInfo(){
System.out.println("Name: " + Name);
System.out.println("Address: " + Address);
System.out.println("Home Phone Number: " + PhoneNumHome);
System.out.println("Work Phone Number: " + PhoneNumWork);
System.out.println("Email: " + email);
}
public void saveInfo(String name, String address, String Hphone, String Wphone, String Email){
Name = name;
Address = address;
PhoneNumHome = Hphone;
PhoneNumWork = Wphone;
email = Email;
}
public static void main(String[] args) {
Person gui = new Person();
gui.displayPersonInfo();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Enter Information");
gui.setSize(350,330);
gui.setLocation(500,250);
gui.setVisible(true);
}
}
here is the output: (it acts as if displayPersonInfo occurs first)
run:
Name: null
Address: null
Home Phone Number: null
Work Phone Number: null
Email: null
A Name (now it prints it from within actionPerformed)
An Adress a City a province a postal code
a number
another number
an email
Name: A Name
Address: An Adress a City a province a postal code
Home Phone Number: a number
Work Phone Number: another number
Email: an email
BUILD SUCCESSFUL (total time: 20 seconds)
It seems your saveInfo function is redundant since you already set every value prior to calling it, but I don't know why saveInfo is nulling the values. Try to call displayPersonInfo before saveInfo and see what happens.
In the main method the "displayPersonInfo()" method is being called right on start. You declared the string name as a field up there uninitialized, so by default its value is null. You initialize this variable inside the actionPerformed() method inside the event class.
The problem is:
public void displayPersonInfo() {
System.out.println("Name: " + Name);
}
public static void main(String[] args) {
Person gui = new Person();
gui.displayPersonInfo();
}
You attribute the value that you want for the variable ONLY when the action is performed, so if you try to access that variable before that you will the get the default value up there, which is null. And that's exactly what you're doing. When the main method starts, it calls the displayPersonInfo(), and inside of that you try to access the variable name and it returns to you null, because the variable only receives the value that you want when the action is performed.
So the solution would be:
public void displayPersonInfo() {
String word = tf1.getText();
Name = word;
System.out.println("Name: " + Name);
}
You must give the value that you want before you call the variable. The same applies to the other ones. If you declare something as "String Name;" and try to call it, you will receive null.