Adding new JTextFields at the click of a JButton - java

I am working on an Invoice System and I want to create new fields each time the add new button is clicked.
It needs to add the fields in the code below each time.
The fields need to appear under its respective columns.
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 256, 990, 303);
panel.add(panel_2);
panel_2.setLayout(null);
code = new JTextField();
code.setBounds(10, 11, 86, 20);
panel_2.add(code);
code.setColumns(10);
code.setEditable(false);
desc = new JTextField();
desc.setBounds(106, 11, 345, 20);
panel_2.add(desc);
desc.setColumns(10);
desc.setEditable(false);
quantity = new JTextField("0");
quantity.setBounds(461, 11, 86, 20);
panel_2.add(quantity);
quantity.setColumns(10);
quantity.setEditable(false);
price = new JTextField("0");
price.setBounds(557, 11, 106, 20);
panel_2.add(price);
price.setColumns(10);
price.setEditable(false);
individualTotal = new JTextField();
individualTotal.setBounds(673, 11, 106, 20);
panel_2.add(individualTotal);
individualTotal.setColumns(10);
individualTotal.setEditable(false);
Below is my buttons that I have set up:
JButton newEntry = new JButton("+");
newEntry.setBackground(Color.PINK);
newEntry.setForeground(Color.BLUE);
newEntry.setFont(new Font("Tahoma", Font.BOLD, 15));
newEntry.setBounds(10, 204, 57, 20);
panel.add(newEntry);
newEntry.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
code.setEditable(true);
desc.setEditable(true);
quantity.setEditable(true);
price.setEditable(true);
individualTotal.setEditable(true);
}
});
newEntry.setEnabled(false);
JButton minusEntry = new JButton("-");
minusEntry.setBackground(Color.PINK);
minusEntry.setForeground(Color.RED);
minusEntry.setFont(new Font("Wide Latin", Font.BOLD, 16));
minusEntry.setBounds(77, 205, 57, 20);
panel.add(minusEntry);
minusEntry.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
code.setEditable(false);
desc.setEditable(false);
quantity.setEditable(false);
price.setEditable(false);
individualTotal.setEditable(false);
}
});
minusEntry.setEnabled(false);
I know there must be an answer somewhere on this site but I cannot seem to find it.
Please also note that I am new at Java development

Create your own subclass of a JPanel which represents one "datasheet" or tablecell or what ever
public DataPanel extends JPanel{
private JTextField field1 = new JTextField();
private JTextField field2 = new JTextField();
// ..... and so on
public DataPanel(YourDataObject data){
field1.setText(data.getValue1());
field2.setText(data.getValue2());
// ... and so on
// then add all of your text fields to the panel
add(field1);
add(field2);
// .... and so on
}
}
Then on button click you add the panel to the component you want to show it on
onClick(SomeEvent event){
yourComponent.add(new DataPanel(yourDataObject));
}

Related

How to get value from a text field?

I am creating a program where I can add and delete items. When added, I want the TOTAL panel to get values from itemprice_textfield when the button ADD is clicked.
private JFrame frame;
private JTextField itemname_textfield;
private JTextField itemprice_textfield;
private JButton add_button;
private JComboBox comboBox;
private JButton del_button;
private JLabel itemprice_label;
private JLabel itemname_label;
private JLabel lblNewLabel_3;
private JLabel totalamount_label;
private JTextField textField_2;
private double amount;
private JLabel bigger_itemname_label;
private JLabel bigger_itemprice_label;
private ArrayList <String> itemnames = new ArrayList();
private ArrayList <Double> itemprices = new ArrayList();
private JTable table;
//DefaultTableModel dtm;
//String header [] = new String [] {itemname_textfield, itemprice_textfield};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EntapaCCE103LabExam1_Frame1 window = new EntapaCCE103LabExam1_Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class lists{ // user defined method lists class
public String itemname;
public double price;
public lists(String itemname, double price)
{
this.itemname = itemname;
this.price = price;
}
public lists(JTextField textField) {
// TODO Auto-generated constructor stub
}
public lists(JTextField textField, JTextField textField_1) {
// TODO Auto-generated constructor stub
}
} // end
public EntapaCCE103LabExam1_Frame1() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.getContentPane().setLayout(null);
JLabel big_title = new JLabel("MY ORDERS");
big_title.setFont(new Font("Times New Roman", Font.PLAIN, 18));
big_title.setBounds(245, 11, 116, 52);
frame.getContentPane().add(big_title);
itemname_textfield = new JTextField(10); // name text
itemname_textfield.setBounds(412, 268, 109, 20);
frame.getContentPane().add(itemname_textfield);
itemname_textfield.setColumns(10);
itemprice_textfield = new JTextField(); // price text
itemprice_textfield.setBounds(412, 330, 109, 20);
frame.getContentPane().add(itemprice_textfield);
itemprice_textfield.setColumns(10);
add_button = new JButton("ADD ITEM");
add_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String getname = itemname_textfield.getText(); // used to get the input string from user to transfer to the combo box
comboBox.addItem(getname); // used to display the received string inputs
}
});
add_button.setFont(new Font("Serif", Font.PLAIN, 13));
add_button.setBounds(412, 361, 109, 23);
frame.getContentPane().add(add_button);
comboBox = new JComboBox();
comboBox.setBounds(412, 479, 109, 22);
frame.getContentPane().add(comboBox);
del_button = new JButton("DELETE ITEM");
del_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
comboBox.removeItem(comboBox.getSelectedItem()); // used to delete the selected index in combo box.
}
});
del_button.setFont(new Font("Serif", Font.PLAIN, 11));
del_button.setBounds(412, 512, 109, 23);
frame.getContentPane().add(del_button);
itemprice_label = new JLabel("Enter Item Price:"); // label for item price
itemprice_label.setBounds(412, 311, 109, 14);
frame.getContentPane().add(itemprice_label); // used to display the text from label
itemname_label = new JLabel("Enter Item Name:"); // label for item name
itemname_label.setBounds(412, 249, 102, 14);
frame.getContentPane().add(itemname_label); // used to display the text from label
lblNewLabel_3 = new JLabel("OPERATION");
lblNewLabel_3.setFont(new Font("Sitka Subheading", Font.PLAIN, 17));
lblNewLabel_3.setBounds(419, 185, 102, 32);
frame.getContentPane().add(lblNewLabel_3);
String getname = itemname_textfield.getText();
totalamount_label = new JLabel("TOTAL: " + amount); // amount here
totalamount_label.setFont(new Font("Serif", Font.PLAIN, 13));
totalamount_label.setBounds(412, 130, 136, 20);
frame.getContentPane().add(totalamount_label);
bigger_itemname_label = new JLabel("ITEM NAME");
bigger_itemname_label.setFont(new Font("Serif", Font.PLAIN, 14));
bigger_itemname_label.setBounds(84, 190, 96, 14);
frame.getContentPane().add(bigger_itemname_label);
bigger_itemprice_label = new JLabel("PRICE");
bigger_itemprice_label.setFont(new Font("Serif", Font.PLAIN, 14));
bigger_itemprice_label.setBounds(245, 192, 46, 14);
frame.getContentPane().add(bigger_itemprice_label);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(39, 225, 322, 285);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
table.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
}
}
But I don't know how or what to do since I am new to Java GUI.
Also, please tell me if there's something weird in my code so that I can make improvement.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
having problems with the code mentioned below. the eclipse error code is as follows ::
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at gui.PassengerGui$2.actionPerformed(PassengerGui.java:139)
Any recommendations would be very much appreciated? I have have been pulling my hair out for almost one hour trying to figure out what the problem is..
private JPanel contentPane;
private JFileChooser fileChooser;
private PassengerController controller;
private PassengerTabelPanel tabelPanel;
private JTextField nameField;
private JTextField cityField;
private JTable passengerTable;
private JRadioButton standardRadio;
private JRadioButton businessRadio;
private ButtonGroup classGroup;
private PassengerFormListener formListener;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassengerGui frame = new PassengerGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public PassengerGui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 584, 368);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenuItem importDataItem = new JMenuItem("Import Data");
menuBar.add(importDataItem);
JMenuItem exportDataItem = new JMenuItem("Export Data");
menuBar.add(exportDataItem);
fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new PassengerFileFilter());
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
classGroup = new ButtonGroup();
//set up class radio
classGroup.add(standardRadio);
classGroup.add(businessRadio);
JLabel nameLabel = new JLabel("Name: ");
nameLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
nameLabel.setBounds(12, 11, 69, 31);
contentPane.add(nameLabel);
JLabel cityLabel = new JLabel("City: ");
cityLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
cityLabel.setBounds(12, 47, 69, 31);
contentPane.add(cityLabel);
JLabel lblNewLabel_2 = new JLabel("Class: ");
lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblNewLabel_2.setBounds(12, 89, 69, 31);
contentPane.add(lblNewLabel_2);
nameField = new JTextField();
nameField.setBounds(60, 18, 129, 20);
contentPane.add(nameField);
nameField.setColumns(10);
cityField = new JTextField();
cityField.setColumns(10);
cityField.setBounds(60, 53, 129, 20);
contentPane.add(cityField);
JRadioButton businessRadio = new JRadioButton("Business");
businessRadio.setBounds(58, 95, 109, 23);
contentPane.add(businessRadio);
JRadioButton standardRadio = new JRadioButton("Standard");
standardRadio.setBounds(60, 127, 109, 23);
contentPane.add(standardRadio);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
String city = cityField.getText();
String passengerClass = classGroup.getSelection().getActionCommand();
PassengerFormEvent ev = new PassengerFormEvent(this, name, passengerClass, city);
You aren't instantiating ButtonGroup variable classGroup. You are using dot (.) operator on a null reference.
Do this:
ButtonGroup classGroup = new ButtonGroup();
and Somewhere in your code after this instantiation, do this:
String passengerClass = classGroup.getSelection().getActionCommand();
You are not instantiating classGroup. You need code such as:-
classGroup = new ButtonGroup();
before you can call methods on classGroup.
EDIT: In answer to the second problem, it's because the buttons you've added to the buttonGroup are also null. You need to create them before you add them.

Issue in Radio Button Action Listener

I have written some code when one of the option in radio button is clicked
it should display one jlabel and jtext field. And when other option in the radio button is clicked it should hide the previous shown jlabel and jtext field and display new jlabel and jtext field.
In the output when I click on one of the radio button it is displaying nothing unless and until I maximize my Window. After geting my jlabel and jtextfield If I click on other radio button the jlabel and jtextfield is hidden but Im not able to see new jlabel and jtextfield for that radiobutton.
enter code here
public class Emp4 {
private JFrame frame;
private JTextField jtxtName;
private JTextField jtxtAge;
private JTextField jtxtSal;
private JTextField jtxtHour_Pay;
private JTextField jtxtHour_Worked;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Emp4 window = new Emp4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Emp4() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(30, 11, 414, 36);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblEmployeeDatabase = new JLabel("Employee Database");
lblEmployeeDatabase.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblEmployeeDatabase.setBounds(157, 7, 193, 25);
panel.add(lblEmployeeDatabase);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel_1.setBounds(10, 61, 464, 230);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel jlblEmpName = new JLabel("Employee Name");
jlblEmpName.setBounds(10, 11, 110, 14);
panel_1.add(jlblEmpName);
jtxtName = new JTextField();
jtxtName.setBounds(114, 8, 120, 20);
panel_1.add(jtxtName);
jtxtName.setColumns(10);
JLabel jlblEmpAge = new JLabel("Employee Age");
jlblEmpAge.setBounds(10, 52, 110, 14);
panel_1.add(jlblEmpAge);
jtxtAge = new JTextField();
jtxtAge.setColumns(10);
jtxtAge.setBounds(114, 49, 120, 20);
panel_1.add(jtxtAge);
JLabel jlblEmpType = new JLabel("Employee Type");
jlblEmpType.setBounds(10, 95, 110, 14);
panel_1.add(jlblEmpType);
JRadioButton jrdbuttonFullTime = new JRadioButton("Full Time");
JRadioButton jrdbtnContract = new JRadioButton("Contract ");
JLabel jlblEmpHour = new JLabel("Hourly Rate");
jlblEmpHour.setBounds(5, 121, 66, 14);
ButtonGroup group =new ButtonGroup();
JLabel jlblEmpSal = new JLabel("Salary");
jlblEmpSal.setBounds(114, 121, 66, 14);
JLabel jlblEmpWork = new JLabel("Hours Worked");
jlblEmpWork.setBounds(150, 120, 86, 24);
jtxtSal = new JTextField();
jtxtSal.setColumns(10);
jtxtSal.setBounds(164, 121, 109, 23);
jtxtHour_Pay = new JTextField();
jtxtHour_Pay.setColumns(10);
jtxtHour_Pay.setBounds(75, 121, 59, 23);
jtxtHour_Worked = new JTextField();
jtxtHour_Worked.setColumns(10);
jtxtHour_Worked.setBounds(243, 121, 109, 23);
group.add(jrdbuttonFullTime);
group.add(jrdbtnContract);
jrdbuttonFullTime.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jrdbuttonFullTime.isSelected()){
//jrdbtnContract.setSelected(false);
panel_1.add(jlblEmpSal);
panel_1.add(jtxtSal);
jlblEmpHour.setVisible(false);
jtxtHour_Pay.setVisible(false);
jtxtHour_Worked.setVisible(false);
jlblEmpWork.setVisible(false);
}
}
});
jrdbuttonFullTime.setBounds(113, 91, 109, 23);
panel_1.add(jrdbuttonFullTime);
jrdbtnContract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(jrdbtnContract.isSelected()){
//jrdbuttonFullTime.setSelected(false);
panel_1.add(jlblEmpHour);
panel_1.add(jtxtHour_Pay);
panel_1.add(jlblEmpWork);
panel_1.add(jtxtHour_Worked);
jlblEmpSal.setVisible(false);
jtxtSal.setVisible(false);
}
}
});
jrdbtnContract.setBounds(218, 91, 109, 23);
panel_1.add(jrdbtnContract);
}
}
Insteed of adding and removing components, simply add all and hide/show them on radiobox selection like this:
panel_1.add(jlblEmpSal);
panel_1.add(jtxtSal);
panel_1.add(jlblEmpHour);
panel_1.add(jtxtHour_Pay);
panel_1.add(jlblEmpWork);
panel_1.add(jtxtHour_Worked);
ActionListener myAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jlblEmpHour.setVisible(jrdbtnContract.isSelected());
jtxtHour_Pay.setVisible(jrdbtnContract.isSelected());
jtxtHour_Worked.setVisible(jrdbtnContract.isSelected());
jlblEmpWork.setVisible(jrdbtnContract.isSelected());
jlblEmpSal.setVisible(jrdbuttonFullTime.isSelected());
jtxtSal.setVisible(jrdbuttonFullTime.isSelected());
}
};
myAction.actionPerformed(null); // to initialize labels first
jrdbuttonFullTime.addActionListener(myAction); // add actionlisteners
jrdbtnContract.addActionListener(myAction);// add actionlisteners
As you can see, you dont even need 2 separate action listeners as one but shared instance is just enough.
So the complete app will look like this:
public class Emp4 {
private JFrame frame;
private JTextField jtxtName;
private JTextField jtxtAge;
private JTextField jtxtSal;
private JTextField jtxtHour_Pay;
private JTextField jtxtHour_Worked;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Emp4 window = new Emp4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Emp4() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(0, 0, 1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(30, 11, 414, 36);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblEmployeeDatabase = new JLabel("Employee Database");
lblEmployeeDatabase.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblEmployeeDatabase.setBounds(157, 7, 193, 25);
panel.add(lblEmployeeDatabase);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel_1.setBounds(10, 61, 464, 230);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel jlblEmpName = new JLabel("Employee Name");
jlblEmpName.setBounds(10, 11, 110, 14);
panel_1.add(jlblEmpName);
jtxtName = new JTextField();
jtxtName.setBounds(114, 8, 120, 20);
panel_1.add(jtxtName);
jtxtName.setColumns(10);
JLabel jlblEmpAge = new JLabel("Employee Age");
jlblEmpAge.setBounds(10, 52, 110, 14);
panel_1.add(jlblEmpAge);
jtxtAge = new JTextField();
jtxtAge.setColumns(10);
jtxtAge.setBounds(114, 49, 120, 20);
panel_1.add(jtxtAge);
JLabel jlblEmpType = new JLabel("Employee Type");
jlblEmpType.setBounds(10, 95, 110, 14);
panel_1.add(jlblEmpType);
JRadioButton jrdbuttonFullTime = new JRadioButton("Full Time");
JRadioButton jrdbtnContract = new JRadioButton("Contract ");
JLabel jlblEmpHour = new JLabel("Hourly Rate");
jlblEmpHour.setBounds(5, 121, 66, 14);
ButtonGroup group = new ButtonGroup();
JLabel jlblEmpSal = new JLabel("Salary");
jlblEmpSal.setBounds(114, 121, 66, 14);
JLabel jlblEmpWork = new JLabel("Hours Worked");
jlblEmpWork.setBounds(150, 120, 86, 24);
jtxtSal = new JTextField();
jtxtSal.setColumns(10);
jtxtSal.setBounds(164, 121, 109, 23);
jtxtHour_Pay = new JTextField();
jtxtHour_Pay.setColumns(10);
jtxtHour_Pay.setBounds(75, 121, 59, 23);
jtxtHour_Worked = new JTextField();
jtxtHour_Worked.setColumns(10);
jtxtHour_Worked.setBounds(243, 121, 109, 23);
group.add(jrdbuttonFullTime);
group.add(jrdbtnContract);
panel_1.add(jlblEmpSal);
panel_1.add(jtxtSal);
panel_1.add(jlblEmpHour);
panel_1.add(jtxtHour_Pay);
panel_1.add(jlblEmpWork);
panel_1.add(jtxtHour_Worked);
ActionListener myAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jlblEmpHour.setVisible(jrdbtnContract.isSelected());
jtxtHour_Pay.setVisible(jrdbtnContract.isSelected());
jtxtHour_Worked.setVisible(jrdbtnContract.isSelected());
jlblEmpWork.setVisible(jrdbtnContract.isSelected());
jlblEmpSal.setVisible(jrdbuttonFullTime.isSelected());
jtxtSal.setVisible(jrdbuttonFullTime.isSelected());
}
};
myAction.actionPerformed(null); // to initialize labels first
jrdbuttonFullTime.addActionListener(myAction);
jrdbtnContract.addActionListener(myAction);
jrdbtnContract.setBounds(218, 91, 109, 23);
jrdbuttonFullTime.setBounds(113, 91, 109, 23);
panel_1.add(jrdbuttonFullTime);
panel_1.add(jrdbtnContract);
}
}
I've revised your code a little. This should get you going on the right path:
public class Emp4 {
private JFrame frame;
private JTextField jtxtName;
private JTextField jtxtAge;
private JTextField jtxtSal;
private JTextField jtxtHour_Pay;
private JTextField jtxtHour_Worked;
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
try {
Emp4 window = new Emp4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Emp4()
{
initialize();
}
private void initialize()
{
frame = new JFrame();
frame.setBounds(0, 0, 1000, 800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel.setBounds(30, 11, 414, 36);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblEmployeeDatabase = new JLabel("Employee Database");
lblEmployeeDatabase.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblEmployeeDatabase.setBounds(157, 7, 193, 25);
panel.add(lblEmployeeDatabase);
JPanel panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 3));
panel_1.setBounds(10, 61, 464, 230);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel jlblEmpName = new JLabel("Employee Name");
jlblEmpName.setBounds(10, 11, 110, 14);
panel_1.add(jlblEmpName);
jtxtName = new JTextField();
jtxtName.setBounds(114, 8, 120, 20);
panel_1.add(jtxtName);
jtxtName.setColumns(10);
JLabel jlblEmpAge = new JLabel("Employee Age");
jlblEmpAge.setBounds(10, 52, 110, 14);
panel_1.add(jlblEmpAge);
jtxtAge = new JTextField();
jtxtAge.setColumns(10);
jtxtAge.setBounds(114, 49, 120, 20);
panel_1.add(jtxtAge);
JLabel jlblEmpType = new JLabel("Employee Type");
jlblEmpType.setBounds(10, 95, 110, 14);
panel_1.add(jlblEmpType);
JRadioButton jrdbuttonFullTime = new JRadioButton("Full Time");
JRadioButton jrdbtnContract = new JRadioButton("Contract ");
JLabel jlblEmpHour = new JLabel("Hourly Rate");
jlblEmpHour.setBounds(5, 121, 66, 14);
ButtonGroup group = new ButtonGroup();
JLabel jlblEmpSal = new JLabel("Salary");
jlblEmpSal.setBounds(114, 121, 66, 14);
JLabel jlblEmpWork = new JLabel("Hours Worked");
jlblEmpWork.setBounds(150, 120, 86, 24);
jtxtSal = new JTextField();
jtxtSal.setColumns(10);
jtxtSal.setBounds(164, 121, 109, 23);
jtxtHour_Pay = new JTextField();
jtxtHour_Pay.setColumns(10);
jtxtHour_Pay.setBounds(75, 121, 59, 23);
jtxtHour_Worked = new JTextField();
jtxtHour_Worked.setColumns(10);
jtxtHour_Worked.setBounds(243, 121, 109, 23);
//*******************************************************************
// Add all your salary fields here, not in ActionListeners
// Start them off invisible
//*******************************************************************
jlblEmpSal.setVisible(false);
panel_1.add(jlblEmpSal);
jtxtSal.setVisible(false);
panel_1.add(jtxtSal);
panel_1.add(jlblEmpHour);
jlblEmpHour.setVisible(false);
panel_1.add(jtxtHour_Pay);
jtxtHour_Pay.setVisible(false);
panel_1.add(jlblEmpWork);
jlblEmpWork.setVisible(false);
jtxtHour_Worked.setVisible(false);
panel_1.add(jtxtHour_Worked);
group.add(jrdbuttonFullTime);
group.add(jrdbtnContract);
jrdbuttonFullTime.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (jrdbuttonFullTime.isSelected()) {
//jrdbtnContract.setSelected(false);
// ****************************************************
// In ActionListeners for radiobuttons, hide the fields you
// don't want to see, make visible the ones you do want to see
// ****************************************************
jlblEmpSal.setVisible(true);
jtxtSal.setVisible(true);
jlblEmpHour.setVisible(false);
jtxtHour_Pay.setVisible(false);
jtxtHour_Worked.setVisible(false);
jlblEmpWork.setVisible(false);
}
}
});
jrdbuttonFullTime.setBounds(113, 91, 109, 23);
panel_1.add(jrdbuttonFullTime);
jrdbtnContract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if (jrdbtnContract.isSelected()) {
//jrdbuttonFullTime.setSelected(false);
// ****************************************************
// In ActionListeners for radiobuttons, hide the fields you
// don't want to see, make visible the ones you do want to see
// ****************************************************
jlblEmpHour.setVisible(true);
jtxtHour_Pay.setVisible(true);
jlblEmpWork.setVisible(true);
jtxtHour_Worked.setVisible(true);
jlblEmpSal.setVisible(false);
jtxtSal.setVisible(false);
}
}
});
jrdbtnContract.setBounds(218, 91, 109, 23);
panel_1.add(jrdbtnContract);
}
}
Your radio buttons start off both unchecked, so you see no salary detail initially. When you click one or the other, the corresponding details appear.
In which case(which radiobutton checked ?) you want to show which controls?

Cannot get JLabel to display JTextField Input

I have my ProfileInput class to store a JTextField input from a Dialog box. Then I transfer that to the setter and getter methods. From there I am calling the setter and getter methods in my AppFrame class.
The the problem that I am having is when I want the input to be displayed as a JLabel on the GUI nothing is showing up. I have no errors that are displayed when I run the code either. Any ideas as to what I have done wrong.
Please note that I am new to Java and am trying to learn. Any ideas/help to improve anything is also great.
ProfileInput Class
package GUI;
//Library imports
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ProfileInput extends Dialog {
//array for the active drop down box
String[] activeLabels = {"Select One", "Not Active", "Slightly Active", "Active", "Very Active"};
public String firstNameString;
//intilizing aspects used in the user profile dialog box
JPanel Panel = new JPanel();
JButton saveButton = new JButton("Save");
JLabel firstName = new JLabel("First Name: ");
JLabel lastName = new JLabel("Last Name: ");
JLabel age = new JLabel("Age: ");
JLabel weight = new JLabel("Weight: ");
JLabel height = new JLabel("Height: ");
JLabel weightGoal = new JLabel("Weight Goal: ");
JLabel activeLevel = new JLabel("Active Level: ");
JLabel completion = new JLabel("Completion By: ");
JTextField firstNameInput = new JTextField();
JTextField lastNameInput = new JTextField();
JTextField ageInput = new JTextField();
JTextField weightInput = new JTextField();
JTextField heightInputFeet = new JTextField();
JTextField heightInputInches = new JTextField();
JTextField weightGoalInput = new JTextField();
JComboBox activeCombo = new JComboBox(activeLabels);
JTextField completionInput = new JTextField();
//setup of the dialog panel
public ProfileInput(Frame parent) {
super(parent,true);
userProfileInput();
setSize(315, 380);
setTitle("Profile Creator");
setLocationRelativeTo(null);
}
public void userProfileInput() {
//sets up the main panel for the dialog box (only panel to add to)
Panel.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
Panel.setLayout(null);
//sets the location of the aspects inside the panel
firstName.setBounds(35, 15, 150, 20);
lastName.setBounds(35, 50, 150, 20);
firstNameInput.setBounds(115, 15, 150, 20);
lastNameInput.setBounds(115, 50, 150, 20);
age.setBounds(35, 85, 120, 20);
ageInput.setBounds(115, 85, 150, 20);
weight.setBounds(35, 115, 150, 20 );
weightInput.setBounds(115, 115, 150, 20);
height.setBounds(35, 150, 150, 20);
heightInputFeet.setBounds(115, 150, 72, 20);
heightInputInches.setBounds(193, 150, 72, 20);
weightGoal.setBounds(35, 185, 150, 20);
weightGoalInput.setBounds(115, 185, 150, 20);
activeLevel.setBounds(35, 220, 150, 20);
activeCombo.setBounds(115,220, 150, 20);
completion.setBounds(35, 255, 150, 20);
completionInput.setBounds(130, 255, 120, 20);
saveButton.setBounds(135, 310, 65, 20);
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//converts the inputs to a string
firstNameString = firstNameInput.getText();
System.out.println(firstNameString);
}
});
//adds the items to the main panel on the dialog box
Panel.add(firstName, null);
Panel.add(lastName, null);
Panel.add(firstNameInput, null);
Panel.add(lastNameInput, null);
Panel.add(age, null);
Panel.add(ageInput, null);
Panel.add(weight, null);
Panel.add(weightInput, null);
Panel.add(height, null);
Panel.add(heightInputFeet, null);
Panel.add(heightInputInches, null);
Panel.add(weightGoal, null);
Panel.add(weightGoalInput, null);
Panel.add(activeLevel, null);
Panel.add(activeCombo, null);
Panel.add(completion, null);
Panel.add(completionInput, null);
Panel.add(saveButton, null);
//adds the panel to the dialog frame
add(Panel);
}//end of userProfileInput method
public String getFirstName() {
return this.firstNameString;
}
public void setFirstName(String firstNameString) {
this.firstNameString = firstNameString;
}
}
AppFrame Class
public class AppFrame extends JFrame {
private static final long serialVersionUID = 1L;
ProfileInput profileInput = new ProfileInput(null);
String firstNameTest = profileInput.getFirstName();
/**
* Starts the frame from AppFrame method below.
*
* #param args
*/
public static void main(String[] args) {
new AppFrame().setVisible(true);
}//end of main Method
/**
*
*
*/
private AppFrame() {
//Initialization of panels and bars used in the main app
JMenuBar menuBar = new JMenuBar();
JPanel contentPane = new JPanel(new BorderLayout());
JPanel rightPanel = new JPanel();
JPanel profileInfo = new JPanel();
//aspects used in the left toolbar panel
JToolBar toolBarPanel = new JToolBar();
JButton bloodPressureTool = new JButton();
JButton heartRateTool = new JButton();
JButton weightTool = new JButton();
JButton bmiTool = new JButton();
JButton medicationTool = new JButton();
JButton appointmentTool = new JButton();
JButton noteTool = new JButton();
JButton profileTool = new JButton();
Border etched = BorderFactory.createEtchedBorder();
Icon bloodPIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BloodPressure.png");
Icon heartRateIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/HeartRate.png");
Icon weightIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Weight.png");
Icon bmiIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BMI.png");
Icon medicationIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Medications.png");
Icon appointmentIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/DoctorAppointment.png");
Icon noteIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Notes.png");
Icon profileIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Profile.png");
//aspects of the user profile panel
JLabel firstName = new JLabel("First Name: ");
JLabel lastName = new JLabel("Last Name: ");
JLabel height = new JLabel("Height: ");
JLabel weight = new JLabel("Weight: ");
JLabel age = new JLabel("Age: ");
JLabel weightGoal = new JLabel("Weight Goal: ");
JLabel activeLevel = new JLabel("Active Level: ");
JLabel completion = new JLabel("Completion Date: ");
//Menu Bar Headers
JMenu file = new JMenu("File");
JMenu go = new JMenu("Go");
JMenu help = new JMenu("Help");
//file drop down
JMenuItem newEntry = new JMenuItem("Profile Creator");
JMenuItem exportReport = new JMenuItem("Export Report");
JMenuItem exportNotes = new JMenuItem("Export Notes");
JMenuItem preferences = new JMenuItem("Preferences");
JMenuItem exit = new JMenuItem("Exit");
file.add(newEntry);
file.addSeparator();
file.add(exportReport);
file.addSeparator();
file.add(exportNotes);
file.addSeparator();
file.add(preferences);
file.addSeparator();
file.add(exit);
//action used when the user presses the enter profile input button
newEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
profileInput.setVisible(true);
}
});
//allows for the program to exit when exit is clicked
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
exitDialog();
}
});
//go drop down
JMenuItem bloodPressure = new JMenuItem("Blood Pressure");
JMenuItem heartRate = new JMenuItem("Heart Rate");
JMenuItem medication = new JMenuItem("Medication");
JMenuItem weightDisplay = new JMenuItem("Weight");
JMenuItem bmi = new JMenuItem("BMI");
JMenuItem docAppoints = new JMenuItem("Doctor's Appointments");
JMenuItem notes = new JMenuItem("Notes");
JMenuItem resources = new JMenuItem("Profile");
go.add(bloodPressure);
go.addSeparator();
go.add(heartRate);
go.addSeparator();
go.add(medication);
go.addSeparator();
go.add(weight);
go.addSeparator();
go.add(bmi);
go.addSeparator();
go.add(docAppoints);
go.addSeparator();
go.add(notes);
go.addSeparator();
go.add(resources);
//help drop down
JMenuItem usersGuide = new JMenuItem("Users Guide");
JMenuItem about = new JMenuItem("About Personal Health Application");
help.add(usersGuide);
help.addSeparator();
help.add(about);
//adds Items to Frame
menuBar.add(file);
menuBar.add(go);
menuBar.add(help);
setJMenuBar(menuBar);
//Panel that allows for all GUI to be ad added here
contentPane.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
contentPane.setBackground(Color.WHITE);
contentPane.add(toolBarPanel, BorderLayout.WEST);
contentPane.add(rightPanel);
//stores the buttons for application (left)
toolBarPanel.setOrientation(JToolBar.VERTICAL);
toolBarPanel.setBackground(Color.white);
toolBarPanel.setFloatable(false);;
toolBarPanel.setBorder(etched);
//sets the large panel on the right side of the frame.
rightPanel.setBackground(Color.WHITE);
rightPanel.setBorder(etched);
rightPanel.setLayout(null);
rightPanel.add(profileInfo, null);
//adds the user profile info to the main screen
profileInfo.setBounds(0, 0, 1104, 100);
profileInfo.setBackground(Color.WHITE);
profileInfo.setLayout(null);
profileInfo.setBorder(etched);
firstName.setBounds(80, 10, 80, 20);
firstName.setFont(new java.awt.Font("Dialog", 1, 11));
lastName.setBounds(80, 50, 80, 20);
lastName.setFont(new java.awt.Font("Dialog", 1, 11));
weightDisplay.setBounds(310, 10, 80, 20);
weightDisplay.setFont(new java.awt.Font("Dialog", 1, 11));
height.setBounds(330, 50, 80, 20);
height.setFont(new java.awt.Font("Dialog", 1, 11));
age.setBounds(550, 10, 80, 20);
age.setFont(new java.awt.Font("Dialog", 1, 11));
weightGoal.setBounds(550, 50, 80, 20);
weightGoal.setFont(new java.awt.Font("Dialog", 1, 11));
activeLevel.setBounds(780, 10, 80, 20);
activeLevel.setFont(new java.awt.Font("Dialog", 1, 11));
completion.setBounds(780, 50, 120, 20);
completion.setFont(new java.awt.Font("Dialog", 1, 11));
//test to see if first name displays
JLabel firstNameInputTest = new JLabel(firstNameTest);
firstNameInputTest.setBounds(160, 10, 80, 20);
profileInfo.add(firstName);
profileInfo.add(lastName);
profileInfo.add(weightDisplay);
profileInfo.add(height);
profileInfo.add(age);
profileInfo.add(weightGoal);
profileInfo.add(completion);
profileInfo.add(activeLevel);
//part of test to see of first name displays
profileInfo.add(firstNameInputTest);
//blood pressure button
bloodPressureTool.setMaximumSize(new Dimension(90, 80));
bloodPressureTool.setMinimumSize(new Dimension(30, 30));
bloodPressureTool.setFont(new java.awt.Font("Dialog", 1, 10));
bloodPressureTool.setPreferredSize(new Dimension(90, 50));
bloodPressureTool.setBorderPainted(false);
bloodPressureTool.setContentAreaFilled(false);
bloodPressureTool.setVerticalTextPosition(SwingConstants.BOTTOM);
bloodPressureTool.setHorizontalTextPosition(SwingConstants.CENTER);
bloodPressureTool.setText("Blood Pressure");
bloodPressureTool.setOpaque(false);
bloodPressureTool.setMargin(new Insets(0, 0, 0, 0));
bloodPressureTool.setSelected(true);
bloodPressureTool.setIcon(bloodPIcon);
//heart rate button
heartRateTool.setMaximumSize(new Dimension(90, 80));
heartRateTool.setMinimumSize(new Dimension(30, 30));
heartRateTool.setFont(new java.awt.Font("Dialog", 1, 10));
heartRateTool.setPreferredSize(new Dimension(90, 50));
heartRateTool.setBorderPainted(false);
heartRateTool.setContentAreaFilled(false);
heartRateTool.setVerticalTextPosition(SwingConstants.BOTTOM);
heartRateTool.setHorizontalTextPosition(SwingConstants.CENTER);
heartRateTool.setText("Heart Rate");
heartRateTool.setOpaque(false);
heartRateTool.setMargin(new Insets(0, 0, 0, 0));
heartRateTool.setSelected(true);
heartRateTool.setIcon(heartRateIcon);
//weight button
weightTool.setMaximumSize(new Dimension(90, 80));
weightTool.setMinimumSize(new Dimension(30, 30));
weightTool.setFont(new java.awt.Font("Dialog", 1, 10));
weightTool.setPreferredSize(new Dimension(90, 50));
weightTool.setBorderPainted(false);
weightTool.setContentAreaFilled(false);
weightTool.setVerticalTextPosition(SwingConstants.BOTTOM);
weightTool.setHorizontalTextPosition(SwingConstants.CENTER);
weightTool.setText("Weight");
weightTool.setOpaque(false);
weightTool.setMargin(new Insets(0, 0, 0, 0));
weightTool.setSelected(true);
weightTool.setIcon(weightIcon);
//BMI button
bmiTool.setMaximumSize(new Dimension(90, 80));
bmiTool.setMinimumSize(new Dimension(30, 30));
bmiTool.setFont(new java.awt.Font("Dialog", 1, 10));
bmiTool.setPreferredSize(new Dimension(90, 50));
bmiTool.setBorderPainted(false);
bmiTool.setContentAreaFilled(false);
bmiTool.setVerticalTextPosition(SwingConstants.BOTTOM);
bmiTool.setHorizontalTextPosition(SwingConstants.CENTER);
bmiTool.setText("BMI");
bmiTool.setOpaque(false);
bmiTool.setMargin(new Insets(0, 0, 0, 0));
bmiTool.setSelected(true);
bmiTool.setIcon(bmiIcon);
//medication button
medicationTool.setMaximumSize(new Dimension(90, 80));
medicationTool.setMinimumSize(new Dimension(30, 30));
medicationTool.setFont(new java.awt.Font("Dialog", 1, 10));
medicationTool.setPreferredSize(new Dimension(90, 50));
medicationTool.setBorderPainted(false);
medicationTool.setContentAreaFilled(false);
medicationTool.setVerticalTextPosition(SwingConstants.BOTTOM);
medicationTool.setHorizontalTextPosition(SwingConstants.CENTER);
medicationTool.setText("Medication");
medicationTool.setOpaque(false);
medicationTool.setMargin(new Insets(0, 0, 0, 0));
medicationTool.setSelected(true);
medicationTool.setIcon(medicationIcon);
//appointment button
appointmentTool.setMaximumSize(new Dimension(90, 80));
appointmentTool.setMinimumSize(new Dimension(30, 30));
appointmentTool.setFont(new java.awt.Font("Dialog", 1, 10));
appointmentTool.setPreferredSize(new Dimension(90, 50));
appointmentTool.setBorderPainted(false);
appointmentTool.setContentAreaFilled(false);
appointmentTool.setVerticalTextPosition(SwingConstants.BOTTOM);
appointmentTool.setHorizontalTextPosition(SwingConstants.CENTER);
appointmentTool.setText("Appointments");
appointmentTool.setOpaque(false);
appointmentTool.setMargin(new Insets(0, 0, 0, 0));
appointmentTool.setSelected(true);
appointmentTool.setIcon(appointmentIcon);
//note button
noteTool.setMaximumSize(new Dimension(90, 80));
noteTool.setMinimumSize(new Dimension(30, 30));
noteTool.setFont(new java.awt.Font("Dialog", 1, 10));
noteTool.setPreferredSize(new Dimension(90, 50));
noteTool.setBorderPainted(false);
noteTool.setContentAreaFilled(false);
noteTool.setVerticalTextPosition(SwingConstants.BOTTOM);
noteTool.setHorizontalTextPosition(SwingConstants.CENTER);
noteTool.setText("Notes");
noteTool.setOpaque(false);
noteTool.setMargin(new Insets(0, 0, 0, 0));
noteTool.setSelected(true);
noteTool.setIcon(noteIcon);
//profile button
profileTool.setMaximumSize(new Dimension(90, 80));
profileTool.setMinimumSize(new Dimension(30, 30));
profileTool.setFont(new java.awt.Font("Dialog", 1, 10));
profileTool.setPreferredSize(new Dimension(90, 50));
profileTool.setBorderPainted(false);
profileTool.setContentAreaFilled(false);
profileTool.setVerticalTextPosition(SwingConstants.BOTTOM);
profileTool.setHorizontalTextPosition(SwingConstants.CENTER);
profileTool.setText("Profile");
profileTool.setOpaque(false);
profileTool.setMargin(new Insets(0, 0, 0, 0));
profileTool.setSelected(true);
profileTool.setIcon(profileIcon);
//adding buttons to toolBarPanel
toolBarPanel.add(bloodPressureTool);
toolBarPanel.add(heartRateTool);
toolBarPanel.add(weightTool);
toolBarPanel.add(bmiTool);
toolBarPanel.add(medicationTool);
toolBarPanel.add(appointmentTool);
toolBarPanel.add(noteTool);
toolBarPanel.add(profileTool);
//sets up the actual frame
setSize(1200,800);
setResizable(false);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
add(contentPane);
//allows for the program to shut down by using x and then using the dialog
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitDialog();
}
});
}//end of appFrame Method
You've got several problems with the above code, but most important, you're using a modeless dialog when you absolutely need to use a modal one. Since it is modeless, program flow in the calling code does not halt when the dialog is made visible, and so you're calling getFirstName() on the dialog immediately after it is opened, before it has been closed, and well before the user has had a chance to input any information whatsoever. A modal dialog on the other hand will freeze program flow in the calling code, and program flow will not resume until the dialog is no longer visible.
Problems and suggestions:
First and foremost, make sure the dialog window is a modal dialog.
But even before this, don't use Dialog, Panel and other AWT component classes, but rather use Swing classes -- JDialog, JPanel, etc.
You can set the JDialog to be modal with either the proper constructor, passing in ModalityType.APPLICATION_MODAL as a parameter within the appropriate constructor (see the API), or you can set it via a method.
Either way, make sure that it's set before setting the dialog visible.
Do this, and when you query the state of the dialog, you can be assured that the user has at least had a chance to interact with the dialog before you try to extract information from it.
Be sure to query the dialog and assign the results after setting it visible.
Edit, I see now that you're calling String firstNameTest = profileInput.getFirstName(); even before setting the dialog visible, as if the firstNameTest String, which is obviously null at this stage, will magically update once the dialog has been visualized and dealt with, but sorry, there's no magic in Java, and fields will not update by themselves. Again, do not set the firstNameTest field at that point, but rather only after the dialog has been displayed and then dealt with.
Next we'll need to talk about null layouts and setBounds. You really don't want to go this route, trust me.
For example:
public class AppFrame extends JFrame {
private static final long serialVersionUID = 1L;
// !! the JLabel needs to be a field so it can be set in the ActionListener
private JLabel firstNameInputTest = new JLabel("");
private ProfileInput profileInput = null; //!! let this start out as null
// !! worthless code, get rid of
// String firstNameTest = profileInput.getFirstName();
public static void main(String[] args) {
// .... etc
And the ActionListener where we create/display the dialog:
newEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//!! create JDialog in a lazy fashion
if (profileInput == null) {
// create dialog, passing in the JFrame
profileInput = new ProfileInput(AppFrame.this);
}
profileInput.setVisible(true); // display the *modal* dialog
// program flow is frozen here until JDialog is no longer visible
// query dialog for its contents
String firstNameTxt = profileInput.getFirstName();
// and use in GUI
firstNameInputTest.setText(firstNameTxt);
}
});
We don't want to declare the JLabel within a method or constructor since in doing so, it will not be visible throughout the class. So...
private AppFrame() { // ??? private ???
// .....
// test to see if first name displays
// !! JLabel firstNameInputTest = new JLabel(firstNameTest); // No!!!
Finally, a very simple example JDialog to demonstrate what I'm discussing:
#SuppressWarnings("serial")
public class ProfileInput extends JDialog {
private JTextField firstNameField = new JTextField(10);
public ProfileInput(JFrame frame) {
// make it modal!
super(frame, "Profile Input", ModalityType.APPLICATION_MODAL);
JPanel panel = new JPanel();
panel.add(new JLabel("Enter First Name:"));
panel.add(firstNameField);
panel.add(new JButton(new SubmitAction("Submit", KeyEvent.VK_S)));
add(panel);
pack();
setLocationRelativeTo(frame);
}
public String getFirstName() {
return firstNameField.getText();
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
ProfileInput.this.dispose();
}
}
}

Using the file location to show the file in 'windows explorer'

Good Morning, I want to show the file location when the button "Locate" is pressed. Also I have full file path in JTextField, when I tried, I get an 'NullPointerException' exception, please give me directions, thanks
So far have tried:
public class locateExp {
private JFrame frame;
private JTextField txtCusersmyFirstPdf;
private Desktop desktop;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
locateExp window = new locateExp();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public locateExp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 489, 329);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton button = new JButton("Locate");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//full file path
File pdfFilepath = new File(txtCusersmyFirstPdf.getText());
if (pdfFilepath.exists()){
try {
//desktop.open(pdfFilepath.getParentFile());
desktop.open(pdfFilepath);
} catch(IOException ex) {
}
}
}
});
button.setMnemonic('t');
button.setFont(new Font("Calibri", Font.BOLD, 12));
button.setBorder(null);
button.setBackground(SystemColor.menu);
button.setBounds(126, 112, 44, 19);
frame.getContentPane().add(button);
JButton button_1 = new JButton("Open");
button_1.setMnemonic('o');
button_1.setFont(new Font("Calibri", Font.BOLD, 12));
button_1.setBorder(null);
button_1.setBackground(SystemColor.menu);
button_1.setBounds(180, 112, 44, 19);
frame.getContentPane().add(button_1);
JButton button_2 = new JButton("Print");
button_2.setMnemonic('p');
button_2.setFont(new Font("Calibri", Font.BOLD, 12));
button_2.setBorder(null);
button_2.setBackground(SystemColor.menu);
button_2.setBounds(228, 112, 44, 19);
frame.getContentPane().add(button_2);
JLabel label = new JLabel("File:");
label.setFont(new Font("Calibri", Font.BOLD, 12));
label.setBounds(114, 142, 44, 14);
frame.getContentPane().add(label);
JLabel lblMyFirstPdf = new JLabel("My First PDF Doc.pdf");
lblMyFirstPdf.setBounds(162, 141, 269, 14);
frame.getContentPane().add(lblMyFirstPdf);
JLabel label_2 = new JLabel("Path/name:");
label_2.setFont(new Font("Calibri", Font.BOLD, 12));
label_2.setBounds(89, 173, 63, 14);
frame.getContentPane().add(label_2);
txtCusersmyFirstPdf = new JTextField();
txtCusersmyFirstPdf.setText("C:\\Users\\My First PDF Doc.pdf");
txtCusersmyFirstPdf.setColumns(10);
txtCusersmyFirstPdf.setBounds(162, 168, 269, 23);
frame.getContentPane().add(txtCusersmyFirstPdf);
JLabel label_3 = new JLabel("File Size:");
label_3.setFont(new Font("Calibri", Font.BOLD, 12));
label_3.setBounds(106, 205, 325, 14);
frame.getContentPane().add(label_3);
JLabel label_4 = new JLabel("513 k bytes");
label_4.setBounds(162, 204, 269, 14);
frame.getContentPane().add(label_4);
}
}
If you get NullPointerException at desktop.open(pdfFilePath), have you checked whether the object desktop itself has been properly initialized? Assuming it is java.awt.Desktop you are using, verify if you have checked both
1. whether Desktop is supported on your platform and
2. whether OPEN Action is supported
You can do this as follows, before the call to desktop.open(...).
if(!Desktop.isDesktopSupported()){
System.out.println("Desktop is not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.OPEN) && pdfFilepath.exists()) {
try {
//desktop.open(pdfFilepath.getParentFile());
desktop.open(pdfFilepath);
} catch(IOException ex) {
...
}
}
If you have initialized it properly as above and still get NullPointerException, the the file is null (as per docs). But since pdfFilepath.exists() returns true in your case, check the desktop initialization as shown above.

Categories

Resources