How do you add multiple records (rows) to TableView Through TextField..?
So far i could managed to add a record to TableView through TextField, but when i change TextField values and hit ADD button, it removes previously added record and shows the new Record in TableView.
// Code For Inserting Records to TableView Through TextField //
private void Add_details(){
try {
String Customer = txtCustomer.getText().trim();
String Mobile = txtMobile.getText().trim();
String Item = txtItem.getText().trim();
int unit_price = Integer.parseInt(txtUnitPrice.getText().trim());
int qty = Integer.parseInt(txtQty.getText().trim());
TableItems t = new TableItems();
ObservableList <TableItems> curnt_row = FXCollections.observableArrayList();
t.setCustomer(Customer);
t.setMobile(Mobile);
t.setItem(Item);
t.setUnit_price(String.valueOf(unit_price));
t.setQty(String.valueOf(qty));
t.setTotal(String.valueOf(total));
curnt_row.add(t);
tblItems.setItems(curnt_row);
col_customer.setCellValueFactory(new PropertyValueFactory<>("customer"));
col_mobile.setCellValueFactory(new PropertyValueFactory<>("mobile"));
col_item.setCellValueFactory(new PropertyValueFactory<>("item"));
col_qty.setCellValueFactory(new PropertyValueFactory<>("qty"));
col_unitprice.setCellValueFactory(new PropertyValueFactory<>("unit_price"));
col_total.setCellValueFactory(new PropertyValueFactory<>("total"));
}catch (NumberFormatException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
// CORDING FOR GET SELECTED ITEM FROM TABLEVIEW //
// I WANT TO GET ALL ITEMS,
// NOT ONLY SELECTED ITEM SO THAT I COULD PERFORM BATCH INSERTION
private void Get_table_values(){
/* LAMDA EXPRESSION */
tblItems.getSelectionModel().selectedItemProperty().addListener
((obs, oldSelection, newSelection) -> {
if (newSelection != null) {
TableView.TableViewSelectionModel selectionModel = tblItems.getSelectionModel();
ObservableList selectedCells = selectionModel.getSelectedCells();
TablePosition tablePosition = (TablePosition) selectedCells.get(0);
Object val = tablePosition.getTableColumn().getCellData(newSelection);
String S_value = val.toString();
}
});
}
You're replacing the entire items list, instead of simply adding a single item. The new list starts empty and the only item you add is the one created in the Add_details method. Add the items the existing list instead:
private final ObservableList <TableItems> curnt_row = FXCollections.observableArrayList();
...
// TableView initialisation
tblItems.setItems(curnt_row);
col_customer.setCellValueFactory(new PropertyValueFactory<>("customer"));
col_mobile.setCellValueFactory(new PropertyValueFactory<>("mobile"));
col_item.setCellValueFactory(new PropertyValueFactory<>("item"));
col_qty.setCellValueFactory(new PropertyValueFactory<>("qty"));
col_unitprice.setCellValueFactory(new PropertyValueFactory<>("unit_price"));
col_total.setCellValueFactory(new PropertyValueFactory<>("total"));
...
private void Add_details(){
try {
String Customer = txtCustomer.getText().trim();
String Mobile = txtMobile.getText().trim();
String Item = txtItem.getText().trim();
int unit_price = Integer.parseInt(txtUnitPrice.getText().trim());
int qty = Integer.parseInt(txtQty.getText().trim());
TableItems t = new TableItems();
t.setCustomer(Customer);
t.setMobile(Mobile);
t.setItem(Item);
t.setUnit_price(String.valueOf(unit_price));
t.setQty(String.valueOf(qty));
t.setTotal(String.valueOf(total));
curnt_row.add(t);
} catch (Exception e) {
e.printStackTrace();
}
}
For getting all items, simply use getItems or use the list you know is assigned to the items property, e.g. in the above example the curnt_row field.
Related
I have created a simple address book program which allows the user to add and update a record. There is also a jtable on the address book which shows the user all the records in the address Book. I have recently added logic where the user updates an existing record and the table refreshes. But if I then click on the updated record or any record in the Jtable to display into the Jtext field I get a I get an Array Out of Bounds error.
Code for getting records from the Database
public void addTable() throws Exception {
tableModel = new DefaultTableModel();
xtable = new JTable(tableModel);
tableModel.addColumn("ID");
tableModel.addColumn("First Name");
tableModel.addColumn("Surname");
tableModel.addColumn("Address Line 1");
tableModel.addColumn("Address Line 2");
tableModel.addColumn("Address Line 3");
tableModel.addColumn("City");
tableModel.addColumn("Post Code");
tableModel.addColumn("Email Address");
tableModel.addColumn("Phone Number");
db.connectDb();
String outQuery = "SELECT * FROM Contacts";
db.myFs = db.st.executeQuery(outQuery);
while (db.myFs.next()) {
String id = db.myFs.getString("ContactID");
String fName = db.myFs.getString("FirstName");
String sName = db.myFs.getString("Surname");
String adOne = db.myFs.getString("AddressLineOne");
String adTwo = db.myFs.getString("AddressLineTwo");
String adThree = db.myFs.getString("AddressLineThree");
String cCity = db.myFs.getString("City");
String pCode = db.myFs.getString("PostCode");
String eAddress = db.myFs.getString("EmailAddress");
String eName = db.myFs.getString("PhoneNumber");
tableModel.insertRow(0, new Object[] { id, fName,sName, adOne, adTwo, adThree, cCity,
pCode, eAddress, eName });
}
db.st.close();
db.con.close();
pane = new JScrollPane(xtable);
pane.setBounds(700, 100, 400, 100);
panel.add(pane);
}
Code to display record into JTextField
public void fetchRec() {
xtable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
String col0 = (String) xtable.getValueAt(xtable.getSelectedRow(),0);
String col1 = (String) xtable.getValueAt(xtable.getSelectedRow(),1);
String col2 = (String) xtable.getValueAt(xtable.getSelectedRow(),2);
String col3 = (String) xtable.getValueAt(xtable.getSelectedRow(),3);
String col4 = (String) xtable.getValueAt(xtable.getSelectedRow(),4);
String col5 = (String) xtable.getValueAt(xtable.getSelectedRow(),5);
String col6 = (String) xtable.getValueAt(xtable.getSelectedRow(),6);
String col7 = (String) xtable.getValueAt(xtable.getSelectedRow(),7);
String col8 = (String) xtable.getValueAt(xtable.getSelectedRow(),8);
String col9 = (String) xtable.getValueAt(xtable.getSelectedRow(),9);
idLabelField.setText(col0);
firstNameLabelField.setText(col1);
surNameLabelField.setText(col2);
addressLineOneField.setText(col3);
addressLineTwoField.setText(col4);
addressLineThreeField.setText(col5);
cityField.setText(col6);
postCodeField.setText(col7);
emailAddressField.setText(col8);
phoneNumberField.setText(col9);
}
});
}
Code to Update a record in the Db
public void updateButton() {
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
number = Integer.parseInt(idLabelField.getText());
setID(number);
setFirstName(firstNameLabelField.getText());
setSurName(surNameLabelField.getText());
setAddressLineOne(addressLineOneField.getText());
setAddressLineTwo(addressLineTwoField.getText());
setAddressLineThree(addressLineThreeField.getText());
setCity(cityField.getText());
setPostCode(postCode.getText());
setEmailAddress(emailAddressField.getText());
setPhoneNumber(phoneNumberField.getText());
try {
db.updateDB(getID(),getFirstName(), getSurName(), getAddressLineOne(), getAddressLineTwo(),
getAddressLineThree(), getCity(), getPostCode(), getEmailAddress(), getPhoneNumber());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
addTable();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
The error i am getting is Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 8
First of all don't use a null layout and setBounds(). Swing was designed to be used for layout managers.
I have recently added logic where the user updates an existing record and the table refreshes.
I would guess the problem is that you keep creating new components (ie. JTable and JScrollPane) and then add the components to the screen.
The problem is you never remove the previous components so you have multiple instances of each component being painted on the frame and your variables don't reference the visible components.
So the solution is create your JTable and JScrollPane and add the components to the frame when you first create the frame. Then, when you "referesh" the data you just create a new DefaultTableModel and use the setModel(...) method to update the table.
Or you can use setRowCount(0) of your current DefaultTableModel to remove all the current data and then use use the addRow(...) method to repopulate the model with the dat in the ResultSet.
Hi I'm using Codename One and Parse Server to save database in my Mobile App, but I wanna put each result of the query inside a button, because I need to click on each element of the List. ParseQuery.getQuery("List") "List" is the ID referenced in the database and "Title" return String.
//Method:
public Container retrieveList(String content) {
Container list = new Container(BoxLayout.y());
ParseObject po = null;
try {
po = ParseObject.fetch(content /*class name*/, "nsC2NdmCuQ" /*objectId*/);
} catch (ParseException e) {
Dialog.show("Err", "Oops! Database is not available at the moment" + e.getCode(), "OK", null);
}
Label title = new Label("Book's Title: " + po.getString("Title"));
list.addComponent(title);
return list;
}
//MENU:
public void listMenu() {
final Form listMenu = new Form("Welcome to the List Menu");
listMenu.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
ParseQuery<ParseObject> query = ParseQuery.getQuery("List");
query.whereExists("Title");
List<ParseObject> results = null;
Container dumpList = null;
listMenu.add(dumpList).removeAll();
ParseServerDAO ps = new ParseServerDAO();
try {
results = query.find();
int index = 0;
for(;index < results.size();) {
dumpList = ps.retrieveList(//How to get each element from results?);
//Add each element of results to a button.
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Oops! Try later, server is not working right now.", "", "OK", null);
}
listMenu.add(dumpList);
}
If you want a list of buttons you should probably do something like this:
public MultiButton retrieveListItem(String content, ActionListener l) {
ParseObject po = null;
try {
po = ParseObject.fetch(content /*class name*/, "nsC2NdmCuQ" /*objectId*/);
} catch (ParseException e) {
Dialog.show("Err", "Oops! Database is not available at the moment" + e.getCode(), "OK", null);
}
MultiButton title = new MultiButton("Book's Title: " + po.getString("Title"));
title.addActionListener(l);
title.putClientProperty("ParseObject", po);
return title;
}
Notice you can use Button, MultiButton, SpanButton etc. for various use cases.
Notice that in the action listener you would want to invoke getActualComponent() on the event object and not getComponent().
E.g. event handling code:
public void actionPerformed(ActionEvent ev) {
MultiButton mb = ev.getActualComponent();
ParseObject po = (ParseObject)mb.getClientProperty("ParseObject");
}
I'm trying to fill my list selection listener method with code, but I don't know how to approach it. Essentially, I would like for the method to fill multiple text fields when an item is selected from the JList.
My JList looks like this:
private JList <String> contactList;
private DefaultListModel<String> model;
//Textfields
comboBookType = new JComboBox(BookType.values());
nameText = new JTextField("", 17);
authorText = new JTextField("", 17);
genreText = new JTextField ("", 17);
comboCategory = new JComboBox (readCategory());
//initialize defaultlistmodel and jlist
model = new DefaultListModel <String>();
bookList = new JList (model);
bookList.setVisibleRowCount(10);
bookList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
bookList.setFixedCellHeight (20);
bookList.setFixedCellWidth (130);
bookList.setBorder (BorderFactory.createLineBorder(Color.BLACK,1));
JPanel left = new JPanel(new BorderLayout());
left.add (new JScrollPane(bookList), BorderLayout.NORTH);
bookList.addListSelectionListener (new ListSelection());
//populating Jlist
class openFileListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
book.getBooks();
for (String name : addressBook.getBooks())
{
model.addElement(name);
}
}
}
//the getBooks() method in my Library class
public ArrayList<String> getBooks ()
{
File file;
Scanner input;
BookType type;
ArrayList<String> books;
ArrayList<String> names = new ArrayList<String>();
try
{
file = new File ("Books.txt");
input = new Scanner (file);
while (input.hasNext())
{
String line = input.nextLine ( );
String [] book = line.split(",");
type = BookType.valueOf(info[0]);
String name = book[1];
b = new Book (type, book[1], book[2], book[3], book[4], info[5]);
list.add (b);
information.add (name);
numOfBooks++;
}
input.close ( );
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog (null, "File not found");
}
return information;
}
Here's what I have so far in my list selection listener:
private class ListSelection implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent e)
{
book.getInfo ( );
int index = bookList.getSelectedIndex ( );
}
//getInfo() method in Library class
public ArrayList<Book> getInfo ()
{
File file;
Scanner input;
BookType type;
ArrayList<String> book;
try
{
file = new File ("Book.txt");
input = new Scanner (file);
while (input.hasNext())
{
String line = input.nextLine ( );
String [] info = line.split(",");
type = BookType.valueOf(info[0]);
String name = info[1];
Book b = new Contact (type, info[1], info[2], info[3], info[4],info[5]);
list.add (b);
}
input.close ( );
}
catch (FileNotFoundException e)
{
JOptionPane.showMessageDialog (null, "File not found");
}
return list;
It's not much, but I have no ideas on where to go from here. I know I have to utilize the index that I got from from getSelectedIndex but I don't know how, please help, thank you.
I know I have to utilize the index that I got from from getSelectedIndex but I don't know how
You would use the index to get the selection item from the ListModel:
String book = model.getElementAt(index);
Or the easier approach is to get the element from the JList using the getSelectedValue() method:
private class ListSelection implements ListSelectionListener
{
public void valueChanged (ListSelectionEvent e)
{
if (e.getValueIsAdjusting()) return;
//book.getInfo ( );
//int index = bookList.getSelectedIndex ( );
String book = bookList.getSelectedValue();
}
}
Now the problem you have is finding the information about the book. You are creating Book objects and adding them to an ArrayList. So now you need to create a loop to look at all entries in the ArrayList. Something like:
ArrayList<Book> bookInfo = getInfo();
for (Book book: bookInfo)
{
if (book.equals(book.getTitle())
{
authorTextField.setText( book.getAuthor());
// ... for the rest of the text fields
return;
}
}
Note a better design would be to read the book info into your class when the class is constructed. This way to don't read the data from the text file every time a selection is made in the JList.
I am new on Java. I am generating a menubar from database table, i am able to generate three levels submenus but i was wondering what if one day we decided to add a level.I know that my logic for the menu generation is bad but I can't find the logic to generate the childs on primefaces. Here's the sql result of my query.Can anyone help for getting the solution? Or any idea for creating a loop instead of repeating the 2 queries? Any tutorial would be really appreciated or any source code example.
Here's my source code for generating 3 levels menu
connexion c1 = new connexion();
Connection con = c1.getConnected();
PreparedStatement ps = con
.prepareStatement("SELECT * FROM menu_options where parent_option_id is null");
// get first level menu options from database
ResultSet result = ps.executeQuery();
while (result.next()) {
DefaultSubMenu firstSubmenu = new DefaultSubMenu(
result.getString("name"));
PreparedStatement ps2 = con
.prepareStatement("SELECT * FROM menu_options where parent_option_id="
+ result.getInt("id"));
// get menu second level options from database
ResultSet result2 = ps2.executeQuery();
DefaultMenuItem item = null;
while (result2.next()) {
PreparedStatement ps3 = con
.prepareStatement("SELECT * FROM menu_options where parent_option_id="
+ result2.getInt("id"));
// get menu third level options from database
ResultSet result3 = ps3.executeQuery();
int rowcount = 0;
if (result3.last()) {
rowcount = result3.getRow();
result3.beforeFirst();
}
if (rowcount == 0) {
item = new DefaultMenuItem(result2.getString("name"));
item.setUrl(result2.getString("url"));
item.setIcon("ui-icon-arrowreturnthick-1-e");
// item.setId("fils");
firstSubmenu.addElement(item);
} else {
DefaultSubMenu firstSubmenu2 = null;
firstSubmenu2 = new DefaultSubMenu(result2.getString("name"));
while (result3.next()) {
item = new DefaultMenuItem(result3.getString("name"));
item.setUrl(result3.getString("url"));
item.setIcon("ui-icon-arrowreturnthick-1-e");
// item.setId("fils");
firstSubmenu2.addElement(item);
}
firstSubmenu.addElement(firstSubmenu2);
}
}
menu.addElement(firstSubmenu);
}
A possible solution might be implementing theses methods:
// Returns the item with no parent
private List<Item> searchParentlessItems();
// Returns the item with the given item as parent
private List<Item> searchItemChildren(Item item);
// Returns the children count
private Long countItemChildren(Item item);
// Build a SubMenu for the specified item
private SubMenu createSubMenu(Item item);
// Build a MenuItem for the specified item
private MenuItem createMenuItem(Item item);
Then generation might look like
private MenuModel createMenuModel() {
MenuModel model = new DefaultMenuModel();
List<Item> rootItems = searchParentlessItems();
for (Item item : rootItems) {
boolean hasChildren = countItemChildren(item) > 0;
if (hasChildren) {
SubMenu subMenu = createSubMenu(item);
model.addElement(subMenu);
appendChildren(subMenu, item);
} else {
MenuItem menuItem = createMenuItem(item);
model.addElement(menuItem);
}
}
}
private void appendChildren(MenuGroup parentMenuItem, Item parentItem) {
List<Item> children = searchItemChildren(parentItem);
for (Item child : children) {
boolean hasChildren = countItemChildren(child) > 0;
if (hasChildren) {
SubMenu subMenu = createSubMenu(child);
parentMenuItem.addElement(subMenu);
appendChildren(subMenu, child);
} else {
MenuItem menuItem = createMenuItem(child);
parentMenuItem.addElement(menuItem);
}
}
}
I have a text file that looks like this:
Person1 Name
Person1 age
Person1 Address
Person2 Name
Person2 age
Person2 Address
Person3 Name
Person2 age
Person3 Address
and I need to get the information to a database.
I have the database connection and know how to enter the info into the database once I have the lines put into the correct variables . . . but how do I get java to identify each new line and set the info to a variable.
Basically I need to take the textfile info and add to the following variables
$Name
$Age
$Address
I thought of using an Array but since I'm mixing strings and numbers, I can't use a String array.
Since I'm using Line per line there is no delimiter.
** Updated info **
I used name, age and address as example variables, and got some of the answers kind of working but I still can't get it completely working, so I should post the whole code . . .
I'm open to code cleanup as well (I'm really new to Java)
The answers given I kind of got to work, except the reader is separating the variables by spaces and in a situation like name and address both have spaces in them, the space delimiter isn't giving me the results I need.
Here is the textfile contents:
Ray Wade
200
American Foundation for Children with AIDS
Tom Hardy
125.50
American Red Cross
As you can see I call the LoadTextFile(); within the CreateTables() function
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.sql.*;
import javax.sql.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Charity extends JFrame
{
JButton btnCalc = new JButton("Donate"), btnLoad = new JButton("Load File"), btnExit = new JButton("Exit");
JLabel name, amount, intro = new JLabel("Would You Like to Donate to a Charity Today? It Only Takes a Few Moments"), message1 = new JLabel(""), message2 = new JLabel("");
JTextField textName, textAmount;
// Create String Array to list charities in the combobox
String[] charities = { "Choose a Charity or Enter a New Charity",
"American Foundation for Children with AIDS",
"American Red Cross",
"Breast Cancer Research Foundation",
"Livestrong *Formerly Lance Armstrong Foundation*",
"Michael J. Fox Foundation for Parkinson's Research" };
JComboBox charityList = new JComboBox(charities);
String file ="Charity.txt";
// Variables used later
double dAmount;
String Charity = null;
int debug = 0; // change to 1 to turn debug mode on
// Variables initialized for Database Stuff
Object[][] databaseInfo;
Object[] columns = {"name", "charity", "amount"};
Connection conn = null;
ResultSet rows;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String DBname = "charity";
String DBusername = "root";
String DBpass = "password";
// Variables and Class for TableModel
DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns){
public Class getColumnClass(int column) {
Class returnValue;
// Verifying that the column exists (index > 0 && index < number of columns
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
// Returns the class for the item in the column
returnValue = Object.class;
}
return returnValue;
}
};
/**
Sets the title, size and layout of the JFrame.<!-- -->Also calls the methods to setup the panels.
*/
public Charity()
{
super("Donations to Charities"); // Title of frame
setLayout(new FlowLayout()); // Declare layout of frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Default close
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get screen size
this.setResizable( false ); // turn off frame resize
this.setSize(600, dim.height-100); // set size of frame
CreatePanels();
GetAction(); // Call ActionListeners
CreateDatabase();
}
public void CreatePanels()
{
SetupCharityGroup(); // Call method to setup charity list panel
SetupDataPanel(); // Call method to setup data collection panel
SetupDisplayTable();
setVisible(true); // Make frame visible
}
/**
Method to setup the display panel containing a JTable that will show the information read from the database.
*/
private void SetupDisplayTable()
{
JTable table = new JTable(dTableModel); // Create a JTable using the custom DefaultTableModel
table.setFont(new Font("Serif", Font.PLAIN, 16)); // Increase the font size for the cells in the table
table.setRowHeight(table.getRowHeight()+5); // Increase the size of the cells to allow for bigger fonts
table.setAutoCreateRowSorter(true); // Allows the user to sort the data
// right justify amount column
TableColumn tc = table.getColumn("amount");
RightTableCellRenderer rightRenderer = new RightTableCellRenderer();
tc.setCellRenderer(rightRenderer);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Disable auto resizing
// Set the width for the columns
TableColumn col1 = table.getColumnModel().getColumn(0);
col1.setPreferredWidth(200);
TableColumn col2 = table.getColumnModel().getColumn(1);
col2.setPreferredWidth(275);
TableColumn col3 = table.getColumnModel().getColumn(2);
col3.setPreferredWidth(75);
// Put the table in a scrollpane and add scrollpane to the frame
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(552, 400));
this.add(scrollPane, BorderLayout.CENTER);
}
/**
Method to setup the data panel containing textFields, Labels, and buttons.
*/
private void SetupDataPanel()
{
JPanel pan = new JPanel();
GridLayout grid = new GridLayout(0, 1, 5, 5);
pan.setLayout(grid);
// Setup TextFields and Labels for name of person donating
// and add them to the panel
name = new JLabel("Name");
textName = new JTextField("", 16);
textName.setHorizontalAlignment(JTextField.RIGHT);
pan.add(name);
pan.add(textName);
// Setup TextFields and Labels for amount being donated
// and add them to the panel
amount = new JLabel("Donation Amount");
textAmount = new JTextField("", 4);
textAmount.setHorizontalAlignment(JTextField.RIGHT);
pan.add(amount);
pan.add(textAmount);
// add buttons and message labels to panel
pan.add(intro);
pan.add(btnCalc);
pan.add(btnLoad);
pan.add(btnExit);
pan.add(message1);
pan.add(message2);
this.add(pan);
}
/**
Method to setup the charity panel with a border containing an editable combobox filled with a list of charities.
*/
private void SetupCharityGroup()
{
JPanel Boxpan=new JPanel();
Boxpan.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Charities"));
this.add(Boxpan);
charityList.setEditable(true);
Boxpan.add(charityList);
}
/**
Add ActionHandlers to interactive elements.
*/
private void GetAction()
{
ActionHandler handler = new ActionHandler();
btnLoad.addActionListener(handler);
btnCalc.addActionListener(handler);
btnExit.addActionListener(handler);
charityList.addActionListener( handler );
}
/**
Method to make ActionHandlers into ActionListeners.
*/
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
String incmd = evt.getActionCommand();
if (incmd.equals("Donate")) // If Donate button is pressed
if (textName.getText().isEmpty())
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: Name of Donor missing!<font>");
} else
CheckDonate();
else if (incmd.equals("Load File")) // If Load File button is pressed
DatabaseLoad();
else if (incmd.equals("Exit")) // If Exit button is pressed
System.exit(0);
}
}
/**
Method to check if charity is selected in the combobox.<!-- -->If a charity is selected, call CharitySelected method, otherwise send error message to Frame.
*/
private void CheckCharity()
{
Object selectedCharity = charityList.getSelectedItem();
if (charityList.getSelectedIndex() == 0) // if charity is not selected
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: No Charity Selected!<font>");
} else CharityIsSelected();
}
/**
If charity is selected, set the selected value to "Charity" variable and call method to thank donator.
*/
private void CharityIsSelected()
{
Object selectedCharity = charityList.getSelectedItem();
Charity = selectedCharity.toString(); // selectedCharity Object converted to String
ThankYou();
}
/**
Thank the donator and call the databseAdd method.
*/
private void ThankYou()
{
message1.setText("Thank You! "+textName.getText());
message2.setText(" $"+textAmount.getText()+" Will be donated to "+Charity);
DatabaseAdd();
}
/**
Method that will check that donation amount is a number in a range between 1 and 1000000000.
*/
private void CheckDonate()
{ try
{
dAmount = Double.parseDouble(textAmount.getText());
if(dAmount <= 0.0 || dAmount > 1000000000 )
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount invalid</font>");
} else CheckCharity();
} catch (NumberFormatException ex) {
// Executes if the data entered is not a number
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount Not Recognized</font>");
}
}
}
public void DBConnection()
{ try
{
// The driver allows you to query the database with Java
// forName dynamically loads the class for you
Class.forName(driver);
// DriverManager is used to handle a set of JDBC drivers
// getConnection establishes a connection to the database
// You must also pass the userid and password for the database
conn = DriverManager.getConnection (url, DBusername, DBpass);
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
} catch (ClassNotFoundException ex) {
// Executes if the driver can't be found
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
message1.setText("Driver Error: contact admin");
message2.setText("");
}
}
/**
Method to add the entered information to the database.<!-- -->Once the information is added to the database, clear the form fields.
*/
private void DatabaseAdd()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// Prepare the query and values to be inserted into the database
String str="INSERT INTO donations(name,charity,amount) VALUES (?,?,?)";
java.sql.PreparedStatement statement = conn.prepareStatement(str);
statement.setString(1,textName.getText());
statement.setString(2,Charity);
statement.setDouble(3,dAmount);
statement.executeUpdate();
// Reset form after saved to database
textName.setText("");
textAmount.setText("");
charityList.setSelectedIndex(0);
s.close();
DatabaseLoad(); // Call the Database Info
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will load the database information and display it in Frame in a JTable.
*/
private void DatabaseLoad()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// This is the query I'm sending to the database
String selectStuff = "SELECT `name`, `charity`, `amount` FROM `"+DBname+"`.`donations` ";
// A ResultSet contains a table of data representing the
// results of the query. It can not be changed and can
// only be read in one direction
rows = s.executeQuery(selectStuff);
// Set the table RowCount to 0
dTableModel.setRowCount(0);
// Temporarily holds the row results
Object[] tempRow;
// next is used to iterate through the results of a query
while(rows.next())
{
// Gets the column values based on class type expected
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getDouble(3) };
dTableModel.addRow(tempRow); // Adds the row of data to the end of the model
}
// Successfully loaded, message the user
message1.setText("<html><font color='red'>Database Info Loaded</font>");
message2.setText("");
s.close();
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will create the database if it does not exist.
*/
private void CreateDatabase()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String dbCreate = "CREATE DATABASE "+DBname;
s.executeUpdate(dbCreate);
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
CreateTables();
}
/**
Method will create the table needed in the database.
*/
private void CreateTables()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String tableCreate = "create table "+DBname+".donations " + "(`name` varchar(200), " + "`charity` varchar(200), " + "amount double)";
s.executeUpdate(tableCreate);
// After creating the tables
// Load the information from the textfile
LoadTextFile();
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
}
public void LoadTextFile()
{
}
// To change justification to the right
class RightTableCellRenderer extends DefaultTableCellRenderer {
public RightTableCellRenderer() {
setHorizontalAlignment(JLabel.RIGHT);
}
}
// Main method calls the constructor
public static void main(String[] args)
{
new Charity();
}
}
Following code snippet will solve your problem.
public class Test {
public static void main( String[] args ) throws Exception
{
HashMap<String, Person> personMap = new HashMap<String, Person>();
try
{
BufferedReader in = new BufferedReader( new FileReader( "File Path" ) );
String str;
Person person = new Person();
int count = 0;
String key = "";
while( ( str = in.readLine() ) != null )
{
if ( null != str && str.trim().length() == 0 )
{
personMap.put( key, person );
count = -1;
person = new Person();
}
else {
String arr[] = str.split( " " );
key = arr[0];
if (count == 0) {
person.setName( arr[1] );
}
else if (count == 1) {
person.setAge( arr[1] );
}
else if (count == 2) {
person.setAddress( arr[1] );
}
}
count ++;
}
personMap.put( key, person );
in.close();
}
catch( IOException e )
{
System.out.println( "Exception" + e.getMessage() );
}
}
}
public class Person
{
private String name = null;
private String age = null;
private String Address = null;
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public String getAge()
{
return age;
}
public void setAge( String age )
{
this.age = age;
}
public String getAddress()
{
return Address;
}
public void setAddress( String address )
{
Address = address;
}
}
I hope it helps
Use BufferedReader to read one line at a time, extract the required info from that line and assign it to the variables. In case you want to hold it in the memory, use a POJO with those 3 properties.
You may use regex to split the line and get the required value(s).
I wrote a set of functions that does something similar. I use a bufferedReader like the other user suggested.
public ArrayList<String> readFileToMemory(String filepath)
{
BufferedReader br = null;
String currentLine = null;
ArrayList<String> fileContents = new ArrayList<String>();
try
{
br = new BufferedReader(new FileReader(filepath));
while((currentLine = br.readLine()) != null)
{
//fileContents.add(br.readLine());
fileContents.add(currentLine);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
return fileContents;
}
This will just read in the each line of a file as a separate entry in a list. Just take the entries and do what you need.
If you're only doing this once, just do 3 replaces in notepad ++
Replace \r\n\r\n with "|||"
replace \r\n with ","
replace ||| with \r\n
then you've got a regular .csv file.