I'm working on my homework and I can't complete one piece of my program ...
I have JTable class which makes table in my code ... i have to write method which takes information from sql database and writes it in list
method MUST look like:
public static List selectAnswers (int questionId) throws SQLException, IOException
following code is written by me:
public static List<AnswerRow> selectAnswers (int questionId) throws SQLException, IOException
{
Connection veza = connectToDatabase();
Properties query = new Properties();
AnswersTableModel atm = new AnswersTableModel();
String selectAnswers = query.getProperty("selectAnswers");
PreparedStatement preparedStatement = veza.prepareStatement(selectAnswers);
ResultSet rs = preparedStatement.executeQuery();
List<AnswerRow> lista = new ArrayList<AnswerRow>();
while(rs.next()){
String answerText = rs.getString("answerText");
boolean isRight = rs.getBoolean("answerRight");
?????????????????????????????????????????????????
}
closeConnectionToDatabase(veza);
return lista;
}
????? field is missing and i dont know what to write there to write information answeText and isRight into AnswerRow class , into AnswerTableModel, into list ...
Code which makes JTable (and is given to me and cannot be changed by my teacher) is here:
package hr.tvz.java.deveti.model;
import java.util.List;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class AnswersTableModel extends AbstractTableModel {
private Object[][] answers;
private String[] columnNames;
public AnswersTableModel (String[] colNames){
super();
columnNames = colNames;
}
public AnswersTableModel() {
super();
this.columnNames = new String[AnswerRow.TABLE_COLUMNS];
this.columnNames[0] = "Odgovor";
this.columnNames[1] = "Točan/Netočan";
}
public java.lang.Class<?> getColumnClass(int columnIndex) {
return getValueAt(0, columnIndex).getClass();
}
public int getColumnCount() {
return AnswerRow.TABLE_COLUMNS;
}
public int getRowCount() {
if (answers != null)
return answers.length;
else
return 0;
}
public Object getValueAt(int row, int column) {
return answers[row][column];
}
public String getColumnName(int column){
return columnNames[column];
}
public void setValueAt (Object aValue, int rowIndex, int columnIndex){
answers[rowIndex][columnIndex] = aValue;
}
public boolean isCellEditable (int rowIndex, int columnIndex){
return true;
}
public void addNewRow(){
Object[] o = new Object[] {"", false};
if ((answers == null) || (answers.length == 0)) {
answers = new Object[][] {o};
}else{
Object[][] answersTemp = new Object[answers.length + 1][AnswerRow.TABLE_COLUMNS];
for (int i = 0; i < answers.length; i++)
answersTemp[i] = answers[i];
answersTemp[answersTemp.length - 1] = o;
answers = answersTemp;
}
}
public List<AnswerRow> getAnswerRows() {
List<AnswerRow> list = new ArrayList<>();
for (Object[] oRow : answers) {
AnswerRow row = new AnswerRow();
row.setAnswer((String) oRow[0]);
row.setRight((boolean) oRow[1]);
list.add(row);
}
return list;
}
public void setAnswerRows(List<AnswerRow> answerRows){
if (answerRows.size() == 0 ) {
this.answers = new Object[0][0];
return;
}
this.answers = new Object[answerRows.size()][AnswerRow.TABLE_COLUMNS];
for (int i = 0; i < answers.length; i++){
answers[i][0] = answerRows.get(i).getAnswer();
answers[i][1] = answerRows.get(i).isRight();
}
this.columnNames = new String[AnswerRow.TABLE_COLUMNS];
this.columnNames[0] = "Odgovor";
this.columnNames[1] = "Točno/Netočno";
}
public class AnswerRow {
public static final int TABLE_COLUMNS = 2;
private boolean isRight;
private String answer;
public AnswerRow(){
answer = "";
isRight = false;
}
public AnswerRow(String answer, boolean isRight){
this.answer = answer;
this.isRight = isRight;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer){
this.answer = answer;
}
public boolean isRight(){
return isRight;
}
public void setRight(boolean isRight){
this.isRight = isRight;
}
}
}
Please help me .. thanks !
List<AnswerRow> lista = new ArrayList<AnswerRow>();
while(rs.next()){
String answerText = rs.getString("answerText");
boolean isRight = rs.getBoolean("answerRight");
//Create AnswerRow instance and set values to it and Add it to list.
AnswersTableModel .AnswerRow ansrow = atm.new AnswerRow();
ansrow.setAnswer(answerText);
ansrow.setRight(isRight);
//Add it to list.
lista.add(ansrow);
}
One thing I am not sure is why you have AnswersTableModel and what you do with that.
Use public AnswerRow(String answer, boolean isRight) constructor to create object
AnswerRow ar=null;
while(rs.next()){
String answerText = rs.getString("answerText");
boolean isRight = rs.getBoolean("answerRight");
ar=new AnswerRow(answerText, isRight);
lista.add(ar);
}
Related
I have this code
public void insertStart_auto_load_test_step_info(int countUsers ) throws SQLException{
String insert_auto_load_test_user_info = "insert into auto_load_test_step_info(id_user_info,start_time,step_id) values(" + getIdValue1()+ getCrokStarTime() + "2";
PreparedStatement pstmt = this.con.prepareStatement(insert_auto_load_test_user_info, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
And this Class
public class Info {
private int crok = 0;
private int testId = 0;
private int testCaseId = 1;
private long starTime;
private long crokStarTime;
private long crokFinishTime;
int [] idValue1 = new int[100];
int [] idValue2 = new int[100];
int id_case_info = 0;
public int[] getIdValue2() {
return idValue2;
}
public void setIdValue2(int idValue2, int i) {
this.idValue2[i] = idValue2;
}
public int getId_case_info() {
return id_case_info;
}
public void setId_case_info(int id_case_info) {
this.id_case_info = id_case_info;
}
public int[] getIdValue1() {
return idValue1;
}
public void setIdValue1(int idValue1, int i) {
this.idValue1[i] = idValue1;
}
I need add to my Insert value from this method getIdValue1(), how can I do that? I think, there must be some sort of index, but I don't know how to use it.
Model it after your setIdValue2() method.
// You should check, somewhere, that i is a valid index of idValue2
public int getIdValue2(int i) {
return idValue2[i];
}
And now, you may call your method: int temp = getIdValue2(0); // Get item at first index
I have a JTable in which I have the operations of several customer accounts.
I want to calculate the cumulative balance with each operation and this for each account. In my JTable I have a column (of type string) in which there is a list of accounts, another column (of type int) in which there is the amount of operations.
How will I be able to retrieve the list of accounts and calculate the cumulative balance of transactions for each account?
I have a solution of my problems
int nombreDeLignes = model.getRowCount();
double cumul=0;
String numcompte=null; // une valeur qui n'existe nulle part
for(int i=0; i<nombreDeLignes; i++) {
String numcompteLigne = model.getValueAt(i, 4).toString();
if ( numcompte==null || !numcompte.equals(numcompteLigne) ) {
numcompte = numcompteLigne;
cumul=0;
}
cumul+= (int) model.getValueAt(i, 5);
model.setValueAt(cumul, i, 9);
}
Here is a code to create Consolidate the Data and create SubTotal
public enum AggregatorType {
SUM, AVG, DISPLAY, LABEL
}
public class DataRow {
private final Object[] values;
private final boolean totalRow;
public DataRow(Object[] values, boolean totalRow) {
this.values = values;
this.totalRow = totalRow;
}
public Object[] getValues() {
return values;
}
public boolean isTotalRow() {
return totalRow;
}
public static Object[] getvalues(Object obj) {
if (obj instanceof DataRow) {
return ( (DataRow) obj).getValues() ;
} else if (obj instanceof Object[]) {
return (Object[]) obj;
} else {
return new Object[] { obj};
}
}
}
public class Aggregator {
private final int column;
private final String prefix;
private final String subfix;
private final AggregatorType type;
public Aggregator( int column,AggregatorType type)
{
this(column,type,null);
}
public Aggregator( int column,AggregatorType type,String prefix)
{
this(column,type,prefix,null);
}
public Aggregator( int column,AggregatorType type,String prefix,String subfix)
{
this.column=column;
this.type=type;
this.prefix=prefix;
this.subfix=subfix;
}
public int getColumn() {
return column;
}
public AggregatorType getType() {
return type;
}
public Object aggregate( List<?> objects) {
Object object = null;
switch(this.type) {
case SUM : object = total(objects); break;
case AVG : object = avg(objects); break;
case LABEL: object = ""; break;
default: object = display(objects); break;
}
if( object != null && ( prefix != null || subfix != null )) {
return ( prefix == null ? "" : prefix.toString() ) +
object.toString() +
( subfix == null ? "" : subfix.toString() );
} else {
return object;
}
}
public Object display( List<?> objects) {
return DataRow.getvalues(objects.get(0))[column];
}
public Object total( List<?> objects) {
double total = 0.0;
for( Object object : objects ) {
Object[] objA = DataRow.getvalues(object);
Object value = objA[column];
if( value instanceof Number ) {
total += ( ( Number ) value ).doubleValue();
}
}
return total;
}
public Object avg( List<?> objects) {
double total = 0.0;
int count = 0;
for( Object object : objects ) {
Object[] objA = DataRow.getvalues(object);
Object value = objA[column];
if( value instanceof Number ) {
total += ( ( Number ) value ).doubleValue();
count++;
}
}
return count > 0 ? ( total / count ) : 0.0;
}
}
import java.util.List;
public class SubTotalCreator {
private final int columnIndex;
private final boolean grandTotal;
private final List<Aggregator> aggregatorList;
public SubTotalCreator(int index, List<Aggregator> aggregatorList) {
this(index, false, aggregatorList);
}
public SubTotalCreator(int index, boolean grandTotal, List<Aggregator> aggregatorList) {
this.aggregatorList = aggregatorList;
this.columnIndex = index;
this.grandTotal = grandTotal;
}
public boolean canCreateSubTotal(Object[] object1, Object[] object2) {
return !object1[columnIndex].equals(object2[columnIndex]);
}
public Object[] createSubTotal(List<?> subList) {
Object[] obj = DataRow.getvalues(subList.get(0));
int length = obj.length;
Object[] subtotal = new Object[length];
for (Aggregator aggregator : aggregatorList) {
Object value = aggregator.aggregate(subList);
subtotal[aggregator.getColumn()] = value;
}
return subtotal;
}
public int getColumnIndex() {
return columnIndex;
}
public boolean isGrandTotal() {
return grandTotal;
}
public List<Aggregator> getAggregatorList() {
return aggregatorList;
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Consolidator {
private final List<SubTotalCreator> list;
private final Comparator<Object[]> comparator;
private List<Object[]> objects;
private List<DataRow> rows;
public Consolidator(Comparator<Object[]> comparator, List<SubTotalCreator> list) {
this.comparator = comparator;
this.list = list;
}
public List<Object[]> getSummary() {
List<Object[]> list = new ArrayList<>();
for (int index = 0; index < rows.size(); index++) {
DataRow row = rows.get(index);
if (row.isTotalRow()) {
list.add(row.getValues());
}
}
return list;
}
public Object[][] getAllRowAsArray() {
Object[][] list =new Object[rows.size()][];
for (int index = 0; index < rows.size(); index++) {
DataRow row = rows.get(index);
list[index]=row.getValues();
}
return list;
}
public List<Object[]> getAllRows() {
List<Object[]> list = new ArrayList<>();
for (int index = 0; index < rows.size(); index++) {
DataRow row = rows.get(index);
list.add(row.getValues());
}
return list;
}
public List<Object[]> getObjects() {
return objects;
}
public List<DataRow> getRows() {
return rows;
}
public void setObjects(Object[][] objects) {
List<Object[]> list = new ArrayList<>();
for (int index = 0; index < objects.length; index++) {
list.add(objects[index]);
}
setObjects(list);
}
public void setObjects(List<Object[]> objects) {
this.objects = objects;
}
private void createDataRow() {
List<DataRow> list = new ArrayList<>();
for (int index = 0; index < objects.size(); index++) {
list.add(new DataRow(objects.get(index), false));
}
this.rows = list;
}
public void consolidate() {
objects.sort(comparator);
createDataRow();
computeSubTotal();
computeGrandTotal();
}
public void computeSubTotal() {
for (SubTotalCreator creator : list) {
if (!creator.isGrandTotal()) {
computeSubTotal(creator);
}
}
}
public void computeGrandTotal() {
for (SubTotalCreator creator : list) {
if (creator.isGrandTotal()) {
computeSubTotal(creator);
}
}
}
public void computeSubTotal(SubTotalCreator creator) {
List<?> list = null;
if (!creator.isGrandTotal()) {
ArrayList<DataRow> subList = new ArrayList<DataRow>();
DataRow prevDataRow = null;
for (int index = 0; index < rows.size(); index++) {
DataRow dataRow = rows.get(index);
if (dataRow.isTotalRow())
continue;
if (prevDataRow != null) {
boolean flag = creator.canCreateSubTotal(prevDataRow.getValues(), dataRow.getValues());
if (flag) {
DataRow subTotal = new DataRow(creator.createSubTotal(subList), true);
rows.add(index, subTotal);
subList.clear();
index++;
}
}
subList.add(dataRow);
prevDataRow = dataRow;
}
list = subList;
} else {
list = objects;
}
DataRow subTotal = new DataRow(creator.createSubTotal(list), true);
rows.add(subTotal);
}
public static void print(Object[][] objects) {
for (Object[] objA : objects) {
System.out.println(Arrays.asList(objA));
}
}
public static void print(List<Object[]> objects) {
for (Object[] objA : objects) {
System.out.println(Arrays.asList(objA));
}
}
public static void main(String[] str) {
Object[][] accountDetails = new Object[][] { { "Abhi", 20 }, { "Abhi", 200 }, { "Sekar", 100 }, { "Abhi", 45 },
{ "Sekar", 120 }, { "Abhi", 35 }, { "Abhi", 40 }, { "Sekar", 500 } };
Comparator<Object[]> comparator = new Comparator<Object[]>() {
public int compare(Object[] obj1, Object[] obj2) {
return ((String) obj1[0]).compareTo((String) obj2[0]);
}
};
List<SubTotalCreator> list = new ArrayList<SubTotalCreator>();
List<Aggregator> aggregatorList = new ArrayList<Aggregator>();
aggregatorList.add(new Aggregator(0, AggregatorType.DISPLAY, null, " 's Total"));
aggregatorList.add(new Aggregator(1, AggregatorType.SUM));
SubTotalCreator creator = new SubTotalCreator(0, aggregatorList);
list.add(creator);
List<Aggregator> grandAggList = new ArrayList<Aggregator>();
grandAggList.add(new Aggregator(0, AggregatorType.LABEL, "Grand Total"));
grandAggList.add(new Aggregator(1, AggregatorType.SUM));
SubTotalCreator creator2 = new SubTotalCreator(0, true, grandAggList);
list.add(creator2);
Consolidator consolidator = new Consolidator(comparator, list);
consolidator.setObjects(accountDetails);
System.out.println("Before Consolidate ");
print(consolidator.getObjects());
consolidator.consolidate();
System.out.println("After Consolidate ");
print(consolidator.getAllRows());
System.out.println("After Consolidate Summary Alone ");
print(consolidator.getSummary());
JFrame frame = new JFrame("test");
JTable table = new JTable( consolidator.getAllRowAsArray(),new String[] {"Name" ,"Amount"});
frame.getContentPane().add( new JScrollPane(table),BorderLayout.CENTER);
frame.setSize( 400,400);
frame.setVisible( true);
}
}
So... My goal here to run this class through an array then fill the array with a .txt document with 43 instances which I will then take user data and compare the two to find an ideal match. I should note that this is for a seating plan -
The text document looks like so -
01 STANDARD True False True F False
public class Seat {
private String eMail = "";
private int number;
private String type;
private boolean window;
private boolean aisle;
private boolean table;
private String f;
private String b;
private boolean ease;
public Seat(int number, String type, boolean window, boolean aisle, boolean table, String f, String b, boolean ease) {
this.number = number;
this.type = type;
this.window = window;
this.aisle = aisle;
this.table = table;
this.f = f;
this.b = b;
this.ease = ease;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isWindow() {
return window;
}
public void setWindow(boolean window) {
this.window = window;
}
public boolean isAisle() {
return aisle;
}
public void setAisle(boolean aisle) {
this.aisle = aisle;
}
public boolean isTable() {
return table;
}
public void setTable(boolean table) {
this.table = table;
}
public String getF() {
return f;
}
public void setF(String f) {
this.f = f;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public boolean isEase() {
return ease;
}
public void setEase(boolean ease) {
this.ease = ease;
}
}
public class Driver {
static Scanner S = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new File("//Users//Mike//Desktop//Seats-2.txt"));
String reservation = inFile.nextLine();
Seat seat [] = new Seat [43];
//while (inFile.hasNextLine()){
//for(int i = 0; i <= reservation.length(); i++){
//System.out.println(reservation.toString(seat));
//}
//}
I've tried methods such as equals(reservation.toString()) how ever these won't work due to the array being built from the Class Seat.
Any guidance will be very helpful.
I'm not looking for easy fix, just some guidance on where to look.
Thank you
If the text file is small, let's just read it whole in a String
public static String ReadWholeFile(String filename) throws IOException
{
final File file = new File(filename);
final FileInputStream fis = new FileInputStream(file);
final byte[] data = new byte[(int)file.length()];
fis.read(data);
fis.close();
return new String(data, "UTF-8");
}
And then parse line by line, converting in Seats
public List<Seat> getSeats(String filename) throws IOException {
final String[] lines = ReadWholeFile(filename).split("\n");
final List<Seat> ret = new ArrayList<Seat>();
for (int i=0; i<lines.length; i++)
try {
final String[] parts = lines[i].split("\\s"); // split on whitespaces
final int num = Integer.parseInt(parts[0]);
ret.add(new Seat(num, parts[1], isTrue(parts[2]), isTrue(parts[3]), isTrue(parts[4]), isTrue(parts[5]), isTrue(parts[6]));
}
catch (Exception e) { /* whatever */ }
return ret;
}
Strings that mean true are "T", "true", ...? If that's the case:
public static isTrue(String x) {
return x.startsWith("T") || x.startsWith("t");
}
if you really don't want to read the whole file, you could go with:
public static List<Seat> getSeats2(String filename) {
final List<Seat> ret = new ArrayList<Seat>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line;
while (line = br.readLine()) {
final String[] parts = line.split("\\s"); // split on whitespaces
// as above
}
}
catch (Exception e) { /* handle errors */ }
finally {
if (br != null)
try { br.close(); }
catch (Exception e) {}
}
return res;
}
I have a TableModel class that extends the AbstrctTableModel class in java swing but when I try to initialise the subclass which is not abstract, the Netbeans 8.0 IDE complains that I am initialising an abstract class.
the code snippets are provide below.
public class TableModel extends AbstractTableModel {
private List<List<Object>> dataList = new ArrayList<>();
private String[] header = { "ID","SUBJECT","LETTTER FROM","LETTER DATE","DATE RECEIVED",
"REMARKS","DATE DISPATCHED","DESTINATION OFFICE"};
private int minRowCount = 5;
public TableModel()
{ }
public List<List<Object>> getDataList() {
return dataList;
}
public void setDataList(List<List<Object>> dataList) {
this.dataList = dataList;
fireTableDataChanged();
fireTableStructureChanged();
}
public void setHeader(String[] header) {
this.header = header;
}
public String[] getHeader() {
return header;
}
#Override
public int getRowCount() {
return Math.max(minRowCount, dataList.size());
}
#Override
public int getColumnCount() {
return header.length;
}
#Override
public String getColumnName(int col) {
return header[col];
}
#Override
public Object getValueAt(int row, int col) {
Object value = null;
if(row < dataList.size())
{value = dataList.get(row).get(col);}
return value;
}
#Override
public Class<?> getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
}
this is the code that initialises the Table Model class.
private TableColumnAdjuster tca;
/**
* Creates new form MyJFrame
*/
private TableModel tableModel ;
public MyJFrame() throws CorruptIndexException, LockObtainFailedException, IOException,
ParseException, java.text.ParseException, SQLException
{
tableModel = new TableModel(); // the Netbeans IDEcomplains about this code
initComponents();
}
You don't provide any info to specify the exact nature of the complaint, but I'm betting that the AbstractTableModel has an abstract method that your TableModel has failed to override. It would be a compilation error in that case.
If that's true, provide a concrete implementation for that method and you'll be able to take the next step.
I should tell this first, this is NOT about Rendering a Table cell.
Here is the TableModel that i'm building using a 2D array based on a User object in my DB.
List<User> userList = userManagerService.getAllUsers();
/* String[] col_user = {"Username", "Name", "Phone", .... } */
String[][] data = new String[userList.size()][col_user.length];
int i = 0;
for (User user : userList) {
String[] userdata = new String[col_user.length];
userdata[0] = user.getUserUsername();
userdata[1] = user.getUserName();
userdata[2] = user.getUserPhone();
userdata[3] = user.getUserNic();
userdata[4] = user.getUserAddress();
userdata[5] = user.getUserEmail();
data[i++] = userdata;
}
VstTableItemModel tiModel = new VstTableItemModel(data, col_user);
dataTable.setModel(tiModel);
My problem is how can i get a User object back, using the selected row in the Table. Note that i can't make a new User object and populate it with the row data. I must get the queried User object(objects in userList). So, is their any way to set a Object with a table row ?
Here is my VstTableItemModel class.
public class VstTableItemModel extends AbstractTableModel {
ArrayList<Object[]> data;
String[] header;
public VstTableItemModel(Object[][] obj, String[] header) {
this.header = header;
data = new ArrayList<Object[]>();
for (int i = 0; i < obj.length; ++i) {
data.add(obj[i]);
}
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return header.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex)[columnIndex];
}
#Override
public String getColumnName(int index) {
return header[index];
}
}
Instead of splitting the User object up before you create the model, add it directly to the model and allow the model to do the work for you...
For example
public class VstTableItemModel extends AbstractTableModel {
private List<User> users;
public VstTableItemModel(List<User> users) {
this.users = new ArrayList<User>(users);
}
#Override
public int getRowCount() {
return users.size();
}
#Override
public int getColumnCount() {
return 6;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = "??";
User user = users.get(rowIndex);
switch (columnIndex) {
case 0:
value = user.getUserUsername();
break;
case 1:
value = user.getUserName();
break;
case 2:
value = user.getUserPhone();
break;
case 3:
value = user.getUserNic();
break;
case 4:
value = user.getUserAddress();
break;
case 5:
value = user.getUserEmail();
break;
}
return value;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return // Return the class that best represents the column...
}
/* Override this if you want the values to be editable...
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
//....
}
*/
/**
* This will return the user at the specified row...
* #param row
* #return
*/
public User getUserAt(int row) {
return users.get(row);
}
}
This way, you should be able to do something like...
List<User> userList = userManagerService.getAllUsers();
VstTableItemModel tiModel = new VstTableItemModel(userList);
Now when you need to...you can grab a the user that is represent at a specific row...
User user = tiModel.getUserAt(rowIndex);