I've been searching for many hours on how to add linked list data to a Jtable but none of the results I found were satisfying. I'm trying to teach myself java so it's a bit difficult for me. Anyways, here is my code. I know it's probably really bad so please be patient with me and help me in making it better.
public class node {
public node next,pre;
public String name;
public double price;
public node (String n,double p){
this (n,p,null,null);
}
public node (String n,double p, node ne,node pr){
name = n;
price = p;
next = ne;
pre = pr;
}
}
public class list {
public node head, tail;
public list (){
head = tail = null;
}
public void addHead (String n,double p){
if (head != null){
head = new node (n,p,head, null);
head.next.pre = head;
}
else
head = tail = new node (n,p);
}
public int size (){
int size = 0;
for(node n = head; n.next != null; n = n.next)
size++;
return size;
}
public String print (){
String s = "";
if (head !=null){
for (node p = head; p !=null; p = p.next)
return p.name +"\t"+ p.price;
}
return s;
}
}
I don't know what to write in the getValueAt method
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.table.*;
class gui extends JFrame implements ActionListener {
list li = new list ();
JButton ad;
JTextField t,t1;
JTextField t2;
JTable table = new JTable (new table_model());
public gui (){
setSize(500,500);
setTitle("DEMO");
setLocationRelativeTo(null);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,2));
t = new JTextField ("");
add(t);
t1 = new JTextField ("");
add(t1);
ad = new JButton ("add");
ad.addActionListener(this);
add(ad);
add(table);
}
public class table_model extends AbstractTableModel {
public list data;
String [] columns = {"Name","Price",
};
public void addList (list data){
this.data = data;
}
public int getColumnCount() {
return columns.length;
}
public int getRowCount() {
return data.size();
}
public String getColumnName(int col) {
return columns[col];
}
public Object getValueAt(int row, int col)
{
}
}
public void actionPerformed (ActionEvent e){
if (e.getSource() == ad && !t.equals("")){
li.addHead(t.getText(),Integer.parseInt(t1.getText()));
}
}
}
class test{
public static void main (String [] aed){
gui g = new gui();
g.setVisible (true);
}
}