Getting a row of names from the first column of JTable - java

I have a JTable with the column names " Names " , " Quantity " and " Unit " .
I'm coding a program where you get the ingredients names.
So i need to get the whole row of one column and String it all up together,
because i need to store it in mySql and i have already set it all as String.
Any idea how i can do this ?
My code are as follows :
JTable Code:
DefaultTableModel model = (DefaultTableModel)table.getModel();
if(!txtQty.getText().trim().equals("")){
model.addRow(new Object[]{ingCB.getSelectedItem().toString(),txtQty.getText(),unitCB.getSelectedItem().toString()});
}else{
JOptionPane.showMessageDialog(null,"*Quantity field left blank");
}
Getting the values and for storing :
for(int i = 1; i<= i ; i++){
ingredients = table.getName();
}
This is for loop is wrong and it does not work because i have a constructor to take in Ingredients but because it is inside the loop, it cannot take it in.
Any suggestions please ? Thank you.
Constructor :
Food e2 = new Food(Name, Description, priceDbl, Image, Category, Ingredients, promotion );
e2.createFood();

I'm coding a program where you get the ingredients names. So i need to get the whole row of one column and String it all up together, because i need to store it in mySql and i have already set it all as String.
Want to do so, try this. Here I am getting result into ArrayList and String, as I am commented ArrayList you can avoid it.
public class TableValuePrint extends JFrame implements ActionListener{
private final JButton print;
private final JTable table;
private String str="";
public TableValuePrint() {
setSize(600, 300);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", "Pass"},
{"Jhon", "ewrewr", "Fail"},
{"Max", "zxczxc", "Pass"}
};
table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Result");
setSize(1000,700);
print=new JButton("Print");
JPanel jpi1 = new JPanel();
jpi1.add(print);
tablePanel.add(jpi1,BorderLayout.SOUTH);
print.addActionListener(this);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableValuePrint ex = new TableValuePrint();
ex.setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==print){
// ArrayList list = new ArrayList();
for(int i = 0;i<table.getModel().getRowCount();i++)
{
//list.add(table.getModel().getValueAt(i, 0)); //get the all row values at column index 1
str=str+table.getModel().getValueAt(i,0).toString();
}
//System.out.println("List="+list);
System.out.println("String="+str);
}
}
}
Output
String=MoniJhonMax

Related

How to call the JTable function again

I'm trying to make a GUI interface using java swing that is able to add users to a text file that I treat as a database. The GUI interface has a JTable which pulls the existing items in the text file and displays it initially. Once I go to add a new item, it gets updated on the text file but not on the JTable. This is mainly because I only call the JTable once the way I set up my code. I'm wondering how I can call the JTable multiple times or make a button for it to call a refresh of the table and display the newly added items alongside the old items.
I want it to be able to either call the refresh of the table in the updateList function or once the viewButton is pressed which triggers an else if statement which can do that in the actionPerformed function.
Here is my code:
class UserManager extends JFrame implements ActionListener {
private JTextField firstNameField, lastNameField, salaryField;
private JButton addButton, removeButton, viewButton, sortButton, getButton;
private JList<Employee> userList;
private ArrayList<Employee> users;
public UserManager() {
setTitle("Employee Manager");
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
firstNameField = new JTextField(20);
lastNameField = new JTextField(20);
salaryField = new JTextField(20);
addButton = new JButton("Add");
addButton.addActionListener(this);
removeButton = new JButton("Remove");
removeButton.addActionListener(this);
viewButton = new JButton("Refresh List"); // POTENTIAL BUTTON TO REFRESH JTABLE?
viewButton.addActionListener(this);
sortButton = new JButton("Sort List");
sortButton.addActionListener(this);
// Pulling data from text file database
ArrayList<ArrayList<String>> databaseData = ReadFile();
users = new ArrayList<Employee>();
// Adding existing databaseData to users
for (int i = 0; i < databaseData.size(); i++) {
Employee user = new Employee(databaseData.get(i).get(0), databaseData.get(i).get(1), Integer.valueOf(databaseData.get(i).get(2)));
users.add(user);
}
userList = new JList<Employee>(users.toArray(new Employee[0]));
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JPanel firstNamePanel = new JPanel();
firstNamePanel.add(new JLabel("First Name:"));
firstNamePanel.add(firstNameField);
JPanel lastNamePanel = new JPanel();
lastNamePanel.add(new JLabel("Last Name:"));
lastNamePanel.add(lastNameField);
JPanel salaryPanel = new JPanel();
salaryPanel.add(new JLabel("Salary:"));
salaryPanel.add(salaryField);
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
buttonPanel.add(viewButton);
buttonPanel.add(sortButton);
// Converting 2D arraylist to normal 2D array for JTable
String[][] data = databaseData.stream().map(u -> u.toArray(new String[0])).toArray(String[][]::new);
// Initializing column names of JTable
String[] columnNames = { "FName", "LName", "Salary" };
// Initializing the JTable (THIS IS WHAT I NEED TO REFRESH)
JTable j = new JTable(data, columnNames);
j.setBounds(1000, 1000, 900, 900);
// adding it to JScrollPane
JScrollPane table = new JScrollPane(j);
JPanel mainPanel = new JPanel(new GridLayout(5, 3));
mainPanel.add(firstNamePanel);
mainPanel.add(lastNamePanel);
mainPanel.add(salaryPanel);
mainPanel.add(buttonPanel);
mainPanel.add(table);
add(mainPanel);
}
public void actionPerformed(ActionEvent e) {
// "Add" button is clicked
if (e.getSource() == addButton) {
String firstName = firstNameField.getText();
String lastName = lastNameField.getText();
int salary = 0;
try {
salary = Integer.parseInt(salaryField.getText());
}
catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(this, "Please enter a valid salary", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
// Error check to see if full name and age is entered
if (!firstName.equals("") && !lastName.equals("")) {
Employee user = new Employee(firstName, lastName, salary);
users.add(user);
updateList();
firstNameField.setText("");
lastNameField.setText("");
salaryField.setText("");
}
else {
JOptionPane.showMessageDialog(this, "Please enter a valid full name", "Error", JOptionPane.ERROR_MESSAGE);
}
}
// POTENTIAL BUTTON THAT REFRESHES JTABLE?
else if (e.getSource() == viewButton) {
}
}
// Updates the list after a CRUD operation is called
private void updateList() {
userList.setListData(users.toArray(new Employee[0]));
try {
FileWriter fw = new FileWriter("db.txt", false);
// BufferedWriter bw = new BufferedWriter(fw);
// PrintWriter pw = new PrintWriter(bw);
// Loop through each student and write to the text file
for (int i = 0; i < users.size(); i++) {
fw.write(toString(users.get(i).getFirstName(), users.get(i).getLastName(), users.get(i).getSalary()));
}
fw.close();
// CALL A REFRESH FOR THE TABLE HERE??
}
catch (IOException io) {
}
}
// Combing multiple string and ints into a string
public String toString(String firstName, String lastName, int salary) {
return firstName + ", " + lastName + ", " + salary + "\n";
}
// Reading database
public static ArrayList<ArrayList<String>> ReadFile() {
try {
// Choose grades.txt file to look at
File myObj = new File("db.txt");
// Create scanner object
Scanner myReader = new Scanner(myObj);
// Create 2d list array to hold all the single list arrays of single information
ArrayList<ArrayList<String>> combinedArr = new ArrayList<ArrayList<String>>();
// While the file reader is still reading lines in the text
while (myReader.hasNextLine()) {
// Read strings of text in txt file
String data = myReader.nextLine();
// Get first and last name from a string
ArrayList<String> temp = GetName(data);
// Add the person and their salary to the combined array that holds everyones
combinedArr.add(temp);
}
// Close file once there are no more lines to read
myReader.close();
return combinedArr;
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
// Return invalid list string with nothing if error
ArrayList<ArrayList<String>> Invalid = new ArrayList<ArrayList<String>>();
return Invalid;
}
// Parses name in db
public static ArrayList<String> GetName(String data) {
String first = "";
String last = "";
String sal = "";
// System.out.println(data[0])
for (int i = 0; i < data.length(); i++) {
if (data.charAt(i) == ',') {
// Start from 2 indexes after the first occurance of the comma
for (int j = i+2; j < data.length(); j++) {
if (data.charAt(j) == ',') {
for (int n = j+2; n < data.length(); n++) {
sal += data.charAt(n);
}
break;
}
last += data.charAt(j);
}
break;
}
first += data.charAt(i);
}
// Initializing package array to send all values
ArrayList<String> arr = new ArrayList<String>();
arr.add(first);
arr.add(last);
arr.add(sal);
return arr;
}
public static void main(String[] args) {
UserManager frame = new UserManager();
frame.setVisible(true);
}
}
class Employee {
// Initalizing variables
private String firstName;
private String lastName;
private int salary;
// Assigning variables
public Employee(String firstName, String lastName, int salary) {
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
// return first name
public String getFirstName() {
return firstName;
}
// return last name
public String getLastName() {
return lastName;
}
// return salary
public int getSalary() {
return salary;
}
}
Initializing the JTable (THIS IS WHAT I NEED TO REFRESH)
You don't refresh the table. The data for all Swing components is contained in a "model". You change the data in the model. When changes to the model are made the table is repainted to reflect the change.
So you could either:
create a new DefaultTableModel (which is unnecessary)
update the existing DefaultTableModel, by using the addRow(...) method to update the model every time you write a new item to your file.
Instead of using code like:
JTable j = new JTable(data, columnNames);
You can use:
model = new DefaultTableModel(data, columnNames)
table = new JTable(model)
Now you can access the DefaultTableModel any time you need to by creating an instance variable in your class or by using the table.getModel() method.
Usually lists and tables are updated through their models. They represent the information shown to the user. You can try this.
Create in your class a new field. Use this field when initializing the table in your constructor.
private JTable userTable;
In your update function, try this:
DefaultTableModel model = new DefaultTableModel();
users = // fetch here for your users
for (int i = 0, i < user.length, i++)
model.addRow(users[i]);
}
// finally set new model in your table
userTable.setModel(model);
userTable.doLayout();

data from arraylist is not added to tableModel

I made a GUI using JTable(tableModel) and a JPanel where the user can add data through JTextFields to an Arraylist, but for some reason when I click the add JButton, the adding fails and points to the line where I want to add the arraylist row to the tableModel.
public final static ArrayList<Members> adat = new ArrayList<>();
DefaultTableModel tableModel;
String[][] dummy = new String[][]{{"001", "Jack Black", "London", "20"}};
String[] header = new String[]{"id", "Name", "City", "Age"};
tableModel = new DefaultTableModel(dummy, header);
JTable t = new JTable();
t.setModel(tableModel);
panel1.add(new JScrollPane(t));
frame.add(panel1);
JPanel jp = new EditPanel();
frame.add(jp);
public static void newData() { // the "add" button function
Members newMember = null;
try {
newMember = new Members(
Integer.parseInt(EditPanel.idEdit.getText()),
EditPanel.nameEdit.getText(),
EditPanel.cityEdit.getText(),
Integer.parseInt(EditPanel.ageEdit.getText())
);
adat.add(newMember);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error in modification", ERROR_MESSAGE);
}
toTable();
}
and the method toTable() gets the members data from the arraylist to the JTable
static void toTable() { // adding the users data to the table
if (adat.size() > 0) {
for (int i = 0; i < adat.size(); i++) {
int id = adat.get(i).id;
String name = adat.get(i).name;
String city = adat.get(i).city;
int age = adat.get(i).age;
Object[] data = new Object[4];
data[0] = id;
data[1] = name;
data[2] = city;
data[3] = age;
tableModel.addRow(data); // this is the line where the error points
}
}
}
You're encountering an error at tableModel.addRow(data); because tableModel does not have a method called addRow (docs).
You probably mixed up the DefaultTableModel tableModel with the actual JTable t.
It should be t.addRow(data), although you need to make t global first!

Return the value from JOptionPane

I have made a JOptionPane which contains a JPanel. The panel contains one button and one Jtable.
JPanel p = atomicAttack.getPanel(); //make the panel and return it
JOptionPane.showOptionDialog(null, p,"Atomic Attacks",
JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,
null, new Object[]{}, null);
and inside the JButton i have:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
selectedId=jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString();
}
I need to when the user clicks on the button, the JOption get closed and the selectedId get return from the JOptionPane?
I have seen this, but it is not exactly what i am looking for.
Because the button does not return the value for me.
Focus on the models and things will be easier.
public static void main(String[] args) {
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("Selection", new Object[] { "A", "B", "C" });
JTable table = new JTable(tableModel);
ListSelectionModel selectionModel = table.getSelectionModel();
JPanel p = new JPanel(new BorderLayout());
p.add(table, BorderLayout.CENTER);
int option = JOptionPane.showConfirmDialog(null, p, "Atomic Attacks", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (JOptionPane.OK_OPTION == option) {
printSelection(selectionModel, tableModel);
} else {
selectionModel.clearSelection();
}
}
private static void printSelection(ListSelectionModel selectionModel, TableModel tableModel) {
for (int i = selectionModel.getMinSelectionIndex(); i <= selectionModel.getMaxSelectionIndex(); i++) {
if (selectionModel.isSelectedIndex(i)) {
Object selectedValue = tableModel.getValueAt(i, 0);
System.out.println(selectedValue);
}
}
}
If you now select multiple rows
and press the ok button the result will be
A
C
If you want a single selection you can just set
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Arraylist to 2D array and then to a JTable

i'm struggeling to make my arraylist into an 2D array and then adding it on a table to show the data.
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class Planettabell
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame vindu = new Test();
vindu.setVisible(true);
}
});
}
}
class Test extends JFrame
{
private String[] name = {"Name", "grade"};
Object[][] cell = {{"nameHer", "GradeHer"}};
Object[][] cell2 = {{"nameHer2", "gradeHer2"}};
Object[][] cell3 = {{"nameHer3", "gradeHer3"} };
public Test()
{
setTitle("Planettabell");
setSize(500, 210);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
List<Object[]> list = new ArrayList<Object[]>();
list.add(cell);
list.add(cell2);
list.add(cell3);
Object[][]array = list.toArray(new Object[list.size()][]);
JTable tabell = new JTable(array, name);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(new JScrollPane(tabell), BorderLayout.CENTER);
}
}
i will get this message if i run it
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
this code is working if i add 'cell' instead of 'array' on JTable, but i need the entire array from list to work.
i have also tried:
int number = list.size()/2;
Object[][] ArrayNew = new Object[number][2];
for(int x = 0; x< number; x++)
{
for(int z = 0; z < 2; z++)
{
int y = 2 * x;
ArrayNew [x][z] = list.get(y+z);
}
}
JTable tabell = new JTable(ArrayNew, name);
instead of list.toarray. But then i only gett [[Ljava.lang.Object;#28864ae7 and [[Ljava.lang.Object;#49214a13 where the text in the table supposed to be.
would appreicate any answer :)
Your list is effectively a 3D data structure (a list of 2D arrays), it should be only 2D (a list of arrays):
Object[] information = {"nameHer", "GradeHer"};
List<Object[]> list = new ArrayList<Object[]>();
list.add(information); // more data here
Object[][]array = list.toArray(new Object[list.size()][]);
In your code, Object[][] cell = {{"nameHer", "GradeHer"}}; is a 2D array, then you add it into a list (making your list 3 dimensionnal in the process).
Your cells shouldn't be 2D, they represent your rows and must be1D arrays.
Replace by Object[] cell = {"nameHer", "GradeHer"}; and it will work
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class Planettabell
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame vindu = new Test();
vindu.setVisible(true);
}
});
}
}
class Test extends JFrame
{
private String[] name = {"Name", "grade"};
Object[][] cells = {
{"nameHer", "GradeHer"},
{"nameHer2", "gradeHer2"},
{"nameHer3", "gradeHer3"}
};
public Test()
{
setTitle("Planettabell");
setSize(500, 210);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable tabell = new JTable(cells, name);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(new JScrollPane(tabell), BorderLayout.CENTER);
}
}
You're approaching this problem entirely wrong.
a DefaultTableModel takes a 2d array and displays everything for you including column headers. So, without seeing the code to your KarakterTabell I can't imagine what more you're trying to achieve.
To do a table model correctly all you need to do is have a means to access your data in an x,y fashion. Then, pass in the data stream into this new model it will run when the table comes up:
public class KarakterTableModel implements TableModel {
List<String[]> data = new ArrayList<String[]>();
public KarakterTableModel(BufferedReader reader) {
while(reader.ready()) {
String columnData = reader.readLine();
String[] columns = columnData.split(" ");
data.add(columns);
}
}
public Object getValueAt(int x, int y) {
String[] row = data.get(x);
return row[y];
}
}
JTable table = new Jtable(new KarakterMode(new BufferedReader(System.in));
Also remember: it's public Object getValueAt() -- the JTable will put the "toString()" call of whatever is returned from this call into the cell.

drop down list within JTextField

I wnt that when i enter some letter in the textfield then the related items should be picked up from my database and should appear as a drop down list.
For Example:
I typed 'J' in text Field, in my database is having names such as {"Juby','Jaz','Jasmine','Joggy'....}
Theses names should appear as a list. So that i could select one from them.and so on for other leters as well.
Is there any predefined control in awt??
Thnx
Why not just use a JComboBox? By default, when the user types a keystroke in a read-only combobox and an item in the combobox starts with the typed keystroke, the combobox will select that item.
Or you could set the JComboBox to be editable using setEditable(true), and use a KeySelectionManager. The link explains selecting an item in a JComboBox component with multiple keystrokes.
This is a small example implementing what ( i think) you asked for.. the database in this example is a vector of strings.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Answer extends JFrame {
public static final int MAXITEMS = 100;
JPanel panel = new JPanel();
JTextField textField = new JTextField(10);
String[] myDataBase = { "Juby", "Jaz", "Jasmine", "Joggy", "one", "dog","cat", "parot" };
String[] listItems;
JList theList = new JList();
public Answer() {
this.add(panel);
panel.setPreferredSize(new Dimension(500, 300));
panel.add(textField);
panel.add(theList);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ke) {
String compareString = ("" + textField.getText() + ke.getKeyChar());
listItems = new String[MAXITEMS];
if (compareString.trim().length() > 0 ){
int counter = 0;
for (int i = 0; i < myDataBase.length; i++) {
if (counter < MAXITEMS) {
if (myDataBase[i].length() >= compareString.length() &&
myDataBase[i].substring(0, compareString.length()).equalsIgnoreCase(compareString)) {
listItems[counter] = myDataBase[i];
counter++;
}
}
}
}
theList.setListData(listItems);
}
});
}
public static void main(String[] args) {
final Answer answer = new Answer();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
answer.pack();
answer.setVisible(true);
}
});
}
}
One option is to use GlazedLists, as it has some support for auto-completion.

Categories