How to get value from a text field? - java

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.

Related

Adding new JTextFields at the click of a JButton

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));
}

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?

clear jbutton - not clearing my text fields

I have a program to calculate the amount of paint needed to cover certain area. I have a button that that I have coded which is supposed to clear the text field but it is not working. I have used the exact same format in other programs and it has worked before but for some reason it is not working in this particular program. The error says cannot find symbol on the clearjbuttonactionperformed. Please help.
/*
FileName: PaintCalculator
Name: Bhattarai
Date: October.2014
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
public class PaintCalculator extends JFrame
{
// declarations
Color black = new Color(0, 0, 0);
Color white = new Color(255, 255, 255);
Color light_gray = new Color(192, 192, 192);
DecimalFormat currency;
JTextField currencyJTextField;
JLabel roomWidthJLabel;
JTextField roomWidthJTextField;
JLabel roomLengthJLabel;
JTextField roomLengthJTextField;
JLabel numberofGallonsJLabel;
JTextField numberofGallonsJTextField;
JLabel subTotalJLabel;
JTextField subTotalJTextField;
JLabel salesTaxJLabel;
JTextField salesTaxJTextField;
JLabel totalAmountJLabel;
JTextField totalAmountJTextField;
JButton enterJButton;
JButton clearJButton;
double roomWidth;
double roomLength;
double numberofGallons;
double subTotal;
double salesTax;
double totalAmount;
public PaintCalculator()
{
createUserInterface();
}
public void createUserInterface()
{
Container contentPane = getContentPane();
contentPane.setBackground(white);
contentPane.setLayout(null);
// initialize components
// input
roomWidthJLabel = new JLabel ();
roomWidthJLabel.setBounds (50, 20, 150, 20);
roomWidthJLabel.setFont(new Font("Default", Font.PLAIN, 12));
roomWidthJLabel.setText ("Enter Width of Room (Ft):");
roomWidthJLabel.setForeground(black);
roomWidthJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(roomWidthJLabel);
roomWidthJTextField = new JTextField();
roomWidthJTextField.setBounds(230, 20, 100, 20);
roomWidthJTextField.setFont(new Font("Default", Font.PLAIN, 12));
roomWidthJTextField.setHorizontalAlignment(JTextField.CENTER);
roomWidthJTextField.setForeground(black);
roomWidthJTextField.setBackground(white);
roomWidthJTextField.setEditable(true);
contentPane.add(roomWidthJTextField);
roomLengthJLabel = new JLabel();
roomLengthJLabel.setBounds(50, 70, 150, 20);
roomLengthJLabel.setFont(new Font("Default", Font.PLAIN, 12));
roomLengthJLabel.setText("Enter Length of Room (Ft):");
roomLengthJLabel.setForeground(black);
roomLengthJLabel.setHorizontalAlignment(JLabel.CENTER);
contentPane.add(roomLengthJLabel);
roomLengthJTextField = new JTextField();
roomLengthJTextField.setBounds(230, 70, 100, 20);
roomLengthJTextField.setFont(new Font("Default", Font.PLAIN, 12));
roomLengthJTextField.setHorizontalAlignment(JTextField.CENTER);
roomLengthJTextField.setForeground(black);
roomLengthJTextField.setBackground(white);
roomLengthJTextField.setEditable(true);
contentPane.add(roomLengthJTextField);
// outputs
numberofGallonsJLabel = new JLabel();
numberofGallonsJLabel.setBounds(50, 120, 150, 20);
numberofGallonsJLabel.setFont(new Font("Default", Font.PLAIN, 12));
numberofGallonsJLabel.setText("Number of Gallons:");
numberofGallonsJLabel.setForeground(black);
numberofGallonsJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(numberofGallonsJLabel);
numberofGallonsJTextField = new JTextField();
numberofGallonsJTextField.setBounds(230, 120, 100, 20);
numberofGallonsJTextField.setFont(new Font("Default", Font.PLAIN, 12));
numberofGallonsJTextField.setHorizontalAlignment(JTextField.CENTER);
numberofGallonsJTextField.setForeground(black);
numberofGallonsJTextField.setBackground(white);
numberofGallonsJTextField.setEditable(false);
contentPane.add(numberofGallonsJTextField);
subTotalJLabel = new JLabel();
subTotalJLabel.setBounds(50, 170, 150, 20);
subTotalJLabel.setFont(new Font("Default", Font.PLAIN, 12));
subTotalJLabel.setText("Sub Total:");
subTotalJLabel.setForeground(black);
subTotalJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(subTotalJLabel);
subTotalJTextField = new JTextField();
subTotalJTextField.setBounds(230, 170, 100, 20);
subTotalJTextField.setFont(new Font("Default", Font.PLAIN, 12));
subTotalJTextField.setHorizontalAlignment(JTextField.CENTER);
subTotalJTextField.setForeground(black);
subTotalJTextField.setBackground(white);
subTotalJTextField.setEditable(false);
contentPane.add(subTotalJTextField);
salesTaxJLabel = new JLabel();
salesTaxJLabel.setBounds(50, 220, 150, 20);
salesTaxJLabel.setFont(new Font("Default", Font.PLAIN, 12));
salesTaxJLabel.setText("Sales Tax (6%):");
salesTaxJLabel.setForeground(black);
salesTaxJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(salesTaxJLabel);
salesTaxJTextField = new JTextField();
salesTaxJTextField.setBounds(230, 220, 100, 20);
salesTaxJTextField.setFont(new Font("Default", Font.PLAIN, 12));
salesTaxJTextField.setHorizontalAlignment(JTextField.CENTER);
salesTaxJTextField.setForeground(black);
salesTaxJTextField.setBackground(white);
salesTaxJTextField.setEditable(false);
contentPane.add(salesTaxJTextField);
totalAmountJLabel = new JLabel();
totalAmountJLabel.setBounds(50, 270, 150, 20);
totalAmountJLabel.setFont(new Font("Default", Font.PLAIN, 12));
totalAmountJLabel.setText("Total Sales:");
totalAmountJLabel.setForeground(black);
totalAmountJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(totalAmountJLabel);
totalAmountJTextField = new JTextField();
totalAmountJTextField.setBounds(230, 270, 100, 20);
totalAmountJTextField.setFont(new Font("Default", Font.PLAIN, 12));
totalAmountJTextField.setHorizontalAlignment(JTextField.CENTER);
totalAmountJTextField.setForeground(black);
totalAmountJTextField.setBackground(white);
totalAmountJTextField.setEditable(false);
contentPane.add(totalAmountJTextField);
// control
enterJButton = new JButton();
enterJButton.setBounds(50, 320, 100, 30);
enterJButton.setFont(new Font("Default", Font.BOLD, 12));
enterJButton.setText("Enter");
enterJButton.setForeground(black);
enterJButton.setBackground(white);
contentPane.add(enterJButton);
enterJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
enterJButtonActionPerformed(event);
}
}
);
clearJButton = new JButton();
clearJButton.setBounds(230, 320, 100, 30);
clearJButton.setFont(new Font("Default", Font.BOLD, 12));
clearJButton.setText("Clear");
clearJButton.setForeground(black);
clearJButton.setBackground(white);
contentPane.add(clearJButton);
clearJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clearJButtonActionPerformed(event);
}
}
);
// set properties of application’s window
setTitle("Paint Calculator"); // set title
setSize( 400, 400 ); // set window size
setVisible(true); // display window
}
// main method
public static void main(String[] args)
{
PaintCalculator application = new PaintCalculator();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void enterJButtonActionPerformed(ActionEvent event)
{
getRoomWidthInput();
}
/* Try-Catch Method */
public void getRoomWidthInput()
{
try
{
roomWidth = Double.parseDouble(roomWidthJTextField.getText());
getRoomLengthInput();
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog(this,
"Please enter Room Width!",
"Number Format Error", JOptionPane.ERROR_MESSAGE );
roomWidthJTextField.setText("");
roomWidthJTextField.requestFocusInWindow();
}
}
public void getRoomLengthInput()
{
try
{
roomLength = Double.parseDouble(roomLengthJTextField.getText());
calculateNumberofGallons();
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog(this,
"Please enter Room Length!",
"Number Format Error", JOptionPane.ERROR_MESSAGE );
roomLengthJTextField.setText("");
roomLengthJTextField.requestFocusInWindow();
}
}
public void calculateNumberofGallons()
{ //process data
final double Tax_Rate = .07;
final double priceperGallon = 24.95;
numberofGallons = (roomWidth * roomLength)/ 400;
subTotal = numberofGallons * priceperGallon;
salesTax = subTotal * Tax_Rate;
totalAmount = subTotal + salesTax;
//display results
currency = new DecimalFormat("$0.00");
numberofGallonsJTextField.setText("" + numberofGallons);
subTotalJTextField.setText("" + currency.format(subTotal));
salesTaxJTextField.setText("" + currency.format(salesTax));
totalAmountJTextField.setText("" + currency.format(totalAmount));
}
}

Refresh JTable using Vectors strings

I'm trying to refresh my table but it won't refresh. I tried using the fireTableDataChanged() as well as creating a new model but my Table will not budge. I can get the initial values in but I can't figure out how to refresh it.
HS = new Vector(Arrays.asList(finalHSArr));
SF = new Vector(Arrays.asList(finalFlagsArr));
I have two separate JTables that I am trying to refresh and these are the new values above. I've been trying for 6 hours now.
public class TemplateGui extends JFrame {
private final ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textField;
private static String [] sortedRoles_Flags,finalFlagsArr,finalHSArr;
private static String finalFlags="",finalHS="",columnToConvert="Result";
private Vector<String> SF,HS,column;
private JTable hotelSecurityTable,securityFlagsTable;
private DefaultTableModel hsTableModel,sfTableModel;
public TemplateGui(){
super("Galaxy Template Generator V1.0");
//column name
column = new Vector(Arrays.asList(columnToConvert));
getContentPane().setForeground(new Color(0, 0, 0));
getContentPane().setLayout(null);
getContentPane().setBackground(new Color(51, 51, 51));
//radio buttons
JRadioButton rdbtnNewRadioButton = new JRadioButton("Central User ");
rdbtnNewRadioButton.setFont(new Font("Tahoma", Font.BOLD, 11));
rdbtnNewRadioButton.setBackground(Color.WHITE);
buttonGroup.add(rdbtnNewRadioButton);
rdbtnNewRadioButton.setBounds(222, 75, 127, 36);
getContentPane().add(rdbtnNewRadioButton);
final JRadioButton rdbtnPropertyUser = new JRadioButton("Property User");
rdbtnPropertyUser.setFont(new Font("Tahoma", Font.BOLD, 11));
rdbtnPropertyUser.setBackground(Color.WHITE);
buttonGroup.add(rdbtnPropertyUser);
rdbtnPropertyUser.setBounds(222, 38, 127, 34);
getContentPane().add(rdbtnPropertyUser);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.BOLD, 18));
textField.setBounds(10, 35, 53, 34);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblHotelSecurity = new JLabel("Hotel Security (H S)");
lblHotelSecurity.setHorizontalAlignment(SwingConstants.CENTER);
lblHotelSecurity.setFont(new Font("Tahoma", Font.BOLD, 13));
lblHotelSecurity.setBounds(10, 144, 189, 23);
lblHotelSecurity.setBackground(new Color(204, 204, 204));
lblHotelSecurity.setOpaque(true);
getContentPane().add(lblHotelSecurity);
JLabel label = new JLabel("Security Flags (S F)");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Tahoma", Font.BOLD, 13));
label.setBounds(222, 144, 372, 23);
label.setBackground(new Color(204, 204, 204));
label.setOpaque(true);
getContentPane().add(label);
JLabel lblEnterTemplateCode = new JLabel("ENTER TEMPLATE CODE");
lblEnterTemplateCode.setForeground(new Color(255, 255, 255));
lblEnterTemplateCode.setFont(new Font("Tahoma", Font.BOLD, 14));
lblEnterTemplateCode.setBounds(10, 9, 175, 23);
getContentPane().add(lblEnterTemplateCode);
JLabel lblSelectUserRole = new JLabel("SELECT USER ROLE LEVEL");
lblSelectUserRole.setForeground(new Color(255, 255, 255));
lblSelectUserRole.setFont(new Font("Tahoma", Font.BOLD, 14));
lblSelectUserRole.setBounds(222, 13, 195, 14);
getContentPane().add(lblSelectUserRole);
//Submit button action
Button button = new Button("Generate Template");
button.setFont(new Font("Dialog", Font.BOLD, 12));
button.setBackground(new Color(102, 255, 102));
button.setForeground(Color.BLACK);
button.setBounds(467, 83, 127, 41);
getContentPane().add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Query excell = new Query();
//get template text
String template = textField.getText().toUpperCase();
System.out.println(template);
if(rdbtnPropertyUser.isSelected()){
try {
//property user was selected
excell.runProcess(1);
System.out.println("you selected Property user");
} catch (IOException e) {
e.printStackTrace();
}
}
else{
try {
//Central User was selected
excell.runProcess(2);
System.out.println("you selected central user");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("NOW WERE HERE");
//get static variables from Excel Query
for(int i = 0; i< Query.sortedGF.length; i++)
{
if(Query.sortedGF[i].contains(template)){
sortedRoles_Flags =Query.sortedGF[i].split(" ");
System.out.println("THIS RAN"+" :"+i);
break;
}
}
System.out.println("NOW WERE HERE 103 " +Query.securityFlags.length);
//add data to table
int j=0;
int sizeOfFlags = Query.securityFlags.length;
//Add HS to FinalHS Variable only if Yes
for(int i=0;i< sortedRoles_Flags.length-sizeOfFlags;i++)
{
if(sortedRoles_Flags[i].matches("Y|y|Y\\?|\\?Y|y\\?|\\?y"))
{
System.out.println("Hotel security:"+" "+sortedRoles_Flags[i]+" HS Added: "+Query.hotelSecurity[i]);
finalHS += Query.hotelSecurity[i]+" ";
System.out.println("Hotel security:"+" "+finalHS);
}
}
//add Security Flags to Final Flags
for(int i=(sortedRoles_Flags.length-sizeOfFlags);i< sortedRoles_Flags.length;i++)
{
finalFlags += Query.securityFlags[j]+": "+ sortedRoles_Flags[i]+" + ";
j++;
}
//Leave open just incase they would prefer a text file for template in which case we just write it
System.out.println(finalFlags);
System.out.println(finalHS);
//Convert to String Arrays in order to add to our JTable
finalFlagsArr= finalFlags.split("\\+");
finalHSArr = finalHS.split(" ");
//convert to vectors
HS = new Vector<String>(Arrays.asList(finalHSArr));
SF = new Vector<String>(Arrays.asList(finalFlagsArr));
System.out.print(HS);
hsTableModel.fireTableDataChanged();
sfTableModel.fireTableDataChanged();
}
});
//scroll panes for flags
JScrollPane scrollPaneHS = new JScrollPane();
scrollPaneHS.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPaneHS.setBounds(10, 170, 189, 185);
getContentPane().add(scrollPaneHS);
JScrollPane scrollPaneSF = new JScrollPane();
scrollPaneSF.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPaneSF.setBounds(222, 170, 372, 187);
getContentPane().add(scrollPaneSF);
//tables for updates
hsTableModel = new DefaultTableModel(HS,column);
hotelSecurityTable = new JTable(hsTableModel);
scrollPaneHS.setViewportView(hotelSecurityTable);
sfTableModel = new DefaultTableModel(SF,column);
securityFlagsTable = new JTable(sfTableModel);
scrollPaneSF.setViewportView(securityFlagsTable);
}
}
When you do
HS = new Vector<String>(Arrays.asList(finalHSArr));
SF = new Vector<String>(Arrays.asList(finalFlagsArr));
You change what HS and SF where point at, however, it does not change what, internally, the TableModel is pointing at.
You could use DefaultTableModel#setDataVector, but i might simpler to simply create new TableModels and set them to the JTables instead.
hsTableModel = new DefaultTableModel(HS, column);
hotelSecurityTable.setModel(hsTableModel);
sfTableModel = new DefaultTableModel(HS, column);
securityFlagsTable.setModel(sfTableModel);
As it's pretty much the same thing...
Updated
DefaultTableModel is expecting a Vector of Vectors, but you're supplying a Vector of Strings.
Try something like...
hsTableModel.setRowCount(0);
for (String row : HS) {
hsTableModel.addRow(new Object[]{row});
}
Instead...

Connecting of Database per each JFrame

I have created this Automated Library. And I need to know how to connect my Database per each JFrame.
This is my main method:
package com.Student.GUI;
public class Student_HomePage extends JFrame {
private JPanel contentPane;
private JTextField searchBox;
private static String results[];
private static Connection conn;
private static String searchText;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DBConnect db = new DBConnect();
conn = db.openConnection();
Student_HomePage frame = new Student_HomePage();
frame.setVisible(true);
frame.setBounds(400,150,599,489);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student_HomePage() {
setBackground(Color.WHITE);
setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\ITC302-Core Java\\java_workspace\\Pictures\\lala.png"));
setTitle("LookBook");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 599, 489);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnHome.setEnabled(false);
btnHome.setContentAreaFilled(false);
btnHome.setBorder(null);
btnHome.setBounds(144, 24, 95, 25);
contentPane.add(btnHome);
JButton btnAuthors = new JButton("Authors");
btnAuthors.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnAuthors.setContentAreaFilled(false);
btnAuthors.setBorder(null);
btnAuthors.setBounds(241, 24, 95, 25);
contentPane.add(btnAuthors);
JButton btnBooks = new JButton("Books");
btnBooks.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnBooks.setContentAreaFilled(false);
btnBooks.setBorder(null);
btnBooks.setBounds(338, 24, 95, 25);
contentPane.add(btnBooks);
JTextArea textArea = new JTextArea();
textArea.setText("|");
textArea.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea.setEditable(false);
textArea.setBounds(227, 11, 26, 57);
contentPane.add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setText("|");
textArea_1.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea_1.setEditable(false);
textArea_1.setBounds(325, 11, 26, 57);
contentPane.add(textArea_1);
searchBox = new JTextField();
searchBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
searchText = temp;
}
});
searchBox.setColumns(10);
searchBox.setBounds(37, 210, 148, 25);
contentPane.add(searchBox);
JTextArea textArea_2 = new JTextArea();
textArea_2.setText("Search title of books,\r\nauthors or genre");
textArea_2.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 14));
textArea_2.setBounds(37, 248, 188, 40);
contentPane.add(textArea_2);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
btnSearch.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\searchIcon.png"));
btnSearch.setContentAreaFilled(false);
btnSearch.setBorder(null);
btnSearch.setBackground(Color.WHITE);
btnSearch.setBounds(185, 210, 87, 25);
contentPane.add(btnSearch);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\download.jpg"));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(270, 202, 290, 215);
contentPane.add(label);
JLabel bookIcon = new JLabel("");
bookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\BookIcon.png"));
bookIcon.setBounds(101, 78, 116, 90);
contentPane.add(bookIcon);
JLabel lookBookIcon = new JLabel("");
lookBookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\image.png"));
lookBookIcon.setBounds(213, 74, 290, 135);
contentPane.add(lookBookIcon);
}
public void btnSearchActionPerformed (ActionEvent e, String searchText) {
DBConnect db = new DBConnect();
results = db.selectMatchedData(searchText, conn);
//if (results.length != 0) {
this.dispose();
Student_SearchList window = new Student_SearchList();
window.setVisible(true);
//}
//else {
//Student_Warning window = new Student_Warning();
//window.setVisible(true);
//}
}
}
And this is where I want to connect my Database:
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
This whole code is my Main.java.

Categories

Resources