I can't figure this out (have been trying to fix this for the past 2-3 hours).
I would like to display the contents of an arraylist, but they do not appear in the table and also there are NO errors, they simply do not appear. Here is my code:
private class examinations{
private int id;
private int candidate_id;
private String date;
private String exam;
private String examNumber;
public examinations(int id, int student_id, String date, String exam, String examNumber) {
this.id = id;
this.student_id = student_id;
this.date = date;
this.exam= exam;
this.examNumber= examNumber;
}
public ArrayList ListExams(){
ArrayList<exams> list = new ArrayList<exams>();
return list;
}
public void addRollToTable(){
DefaultTableModel model = (DefaultTableModel)tableExams.getModel();
ArrayList<exams> list = ListExams();
Object rowData[] = new Object[5];
for(int i = 0; i < list.size(); i++) {
rowData[0] = list.get(i).id;
rowData[1] = list.get(i).student_id;
rowData[2] = list.get(i).date;
rowData[3] = list.get(i).exam;
rowData[4] = list.get(i).examNumber;
model.addRow(rowData);
}
}
}
I tested this loop and the variables coming out of the other list are there, so a System.out.println(list.get(i).exam); will display the correct thing i typed. However the table will NOT display whatever I add in the rowData. It gives, again, no errors. Let me show you the DefaultTableModel code. This code is in the private void initComponents() of my class...
Object [][] data = {};
String[] columnNames = {"Id", "Student_Id", "Date", "Exam",
"Exam_number"};
tableExams= new javax.swing.JTable();
DefaultTableModel model = new DefaultTableModel(data, columnNames);
tableExams.setModel(model);
tableExams.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
jScrollPane4.setViewportView(tableExams);
I've been reading this: DefaultTableModel Class Overview But I still can't find where I am going wrong... Could anyone give a tip?
First of all learn and use Java naming conventions:
Classs names SHOULD start with an upper case character. Can you show me a class in the JDK that does not?
Method should should NOT start with an upper case character. Again, can you show me a method in the JDK the does?
Learn by example and don't make up your own conventions.
so a System.out.println(list.get(i).exam); will display the correct thing i typed
I don't know how this is possible. Your code is as follows:
a) First, you retrieve the ArrayList from the "listExams() method.
ArrayList<exams> list = ListExams();
b) But in the "listExams()" method all you do is create an empty ArrayList.
ArrayList<exams> list = new ArrayList<exams>();
So you are missing the logic that actually adds data to the ArrayList.
Based on the logic provided, you don't even need the ArrayList. Just take the data from the Examination class and add it to the TableModel:
Object rowData[] = new Object[5];
rowData[0] = id;
rowData[1] = student_id;
rowData[2] = date;
rowData[3] = exam;
rowData[4] = examNumber;
model.addRow(rowData);
For a different solution you could create a custom TableModel to hold your "Examination" objects. Check out Row Table Model for a step-by-step example of how this can be done.
OK, I solved it, even though this was just a work around, I'd accept it.
All I did was use this.setVisible(false) and then entered the information in the other JFrame. Clicking add, i make an object of the first JFrame, passed all the variables, used this.dispose() and then called .setVisible(true) to return to the table, which displayed the information. LOL that was a long testing and re-writing of code to actually realize it was something that small...
I am sorry, I did not know where the actual problem was, and yeah thanks a lot for that simple suggestion there camickr. I tried it in the same JFrame and it worked, then I tried it between 2 JFrames and I realized the JFrame with the table DID NOT update the table. repaint() also didn't work. You quite literally helped me out with that small tip, which is all i needed. THANKS!!!!!!
Related
The idea is to set different values from one class to another using the interface.
My code:
public Make(String name, int foundingYear, String founder) {
this.name = name;
this.foundingYear = foundingYear;
this.founder = founder;
}
//other code
So I want to set those values in another class like this:
public record anotherClass (String name, String color, int hp) {
Make make = new Make();
Set<Make> makes = new HashSet<>();
makes.add("name", 1995, "founder");
The thing is when I'm trying to add values (makes.add("name", 1995, "founder");) I can't do that, because it expects just one argument to be added of type makes. What I'm I doing wrong?
You must instantiate Make using the 3 params, then add this make into the Set. See below:
Make make = new Make("name", 1995, "founder"); // use this make
Set<Make> makes = new HashSet<>();
makes.add(make);
I have a long piece of code that looks like this
Kwas a1 = new Kwas("Kwas Azotowy(V)", "HNO3");
// etc..
Kwas a17 = new Kwas("Kwas FluorkoWodorowy", "HF");
How can I write it as an Array? I tried something like
Kwas[] a = new Kwas[17]
But it didn`t work.
My "Kwas" class looks like the following:
public class Kwas {
String name;
String formula;
public Kwas( String nazwa, String wzor)
{
name = nazwa;
formula = wzor;
}
void setName(String c)
{
name = c;
}
void setFormula(String c)
{
formula = c;
}
public String getName()
{
return name;
}
public String getFormula() {return formula;}
}
You can do this:
List<Kwas> list = new ArrayList<Kwas>();
list.add(a2);
Just implement an ArrayList like this:
ArrayList<Kwas> newArray= new ArrayList<>();
And then:
newArray.add(a2);
newArray.add(a3);
newArray.add(a4);
newArray.add(a5);
newArray.add(a6);
newArray.add(a7);
...
...
Then if you want to get an specific item just write something like this:
newArray.get(1).getName(); //for example
I can't comment yet, so I have to provide it as an answer. Everyone is answering here how OP can construct a List, but no one is actually answering how he can create an array, which is probably very confusing for OP who might now think you can't create arrays of self-defined objects. You definitely can. But I don't know what the problem is.
Kwas[] a1 = new Kwas[17];
is definitely the right syntax. Are you sure you include the class? Can you post the exact code and error?
My guess is that you didn't import your class. In Android Studio, try placing your cursor after Kwas and pressing Ctrl+Space. This should show a dropdown list. Select the first line and press enter. Now it should have added an import to your class.
ArrayList<yourObjectName> arrayName = new ArrayList<yourObjectName>();
Then .add(object) on every object
You can simply type:
ArrayList<ObjectType> arrayName = new ArrayList<ObjectType>();
Adding Elements:
arrayName.add(someObject);
Removing Elements:
arrayName.remove(arrayName.get(someInteger));
Getting Elements:
arrayName.get(someInteger);
PS: Don't forget to import:
import java.util.ArrayList;
I am creating a commercial software and got stuck in place, where I need to fill an Array with information from multiple JTextBox fields.
I created an Array -
public String[][] BookAttributes = new String[BookRows][BookLines];
I want to save information added by User from following JTextFields in [BookLines] column for each book, which should auto-increment every time when new book is added to stock.
private JTextField tfBookName;
private JTextField tfBookCost;
private JTextField tfBookYearOfPublication;
private JTextField tfBookPublishingHouse;
private JTextField tfBookISBN;
private JTextField tfBookAuthor;
private JTextField tfBookNrOfPages;
Unfortunately, I cannot find a solution how to put this all together.
Any Help appreciated.
Thank you!
If I understood you correctly then you are looking to save the Book information like Name, Cost etc. to an array.
But, in the above case you are creating a 2-D String Array which looks something like this:
Location (0,0) of array -> "foo"
Location (0,1) of array -> "bar"
...
...
What you actually need is a class say, Book which can hold the information regarding the different attributes. Something like as follows:
public class Book {
private String bookName;
private String bookCost;
private String bookYearOfPublication;
private String bookPublishingHouse;
private String bookISBN;
private String bookAuthor;
private String bookNrOfPages;
/* Constructor, Getter, Setters */
...
}
Next you can create an array of this class like this:
int bookRows = 100;
Book[] booksInfo = new Book[bookRows];
And simply code a for loop for stroing the different book details as follows:
for(int i = 0; i < bookRows; i++) {
Book book = new Book();
book.setBookName(tfBookName);
...
...
booksInfo[i] = book;
}
You can further override the toString() method of the Book class if you want to print the different attributes of any book by simply using System.out.println(...).
Here is the code snippet:
#Override
public String toString() {
return new StringBuilder().append("BookName: ").append(bookName)
.append(" | Book Cost: ").append(bookCost).toString();
}
I am working with a JTable That schould display Some informations sorted By the last two columns. The problem is the last two columns are filled with strings, one of them are Days of the Weak(Monday-Friday) the others are Hours(HH:mm), i would like to sort them going from Monday-Friday and if there are more elements of the same Day they schould be sorted by the Erliest Hour. Until now google was not a realy big help since it schows only ways to sorte something Alphabetically ore in Ascendant/descendant order for numbers, but i dont need an Alphabetically ordered JTable. Does anyone have an idea?
public class ScheduleFrame extends JFrame {
private JPanel contentPane;
private static JTable table;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScheduleFrame frame = new ScheduleFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Exception
*/
public ScheduleFrame(){
setTitle("Schedule");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 627, 405);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
table = new JTable();
scrollPane.setViewportView(table);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Course Name", "Course Room","Course Day", "Course Hour"
}
));}
public static void loadTable()throws Exception{
DefaultTableModel tm = (DefaultTableModel) table.getModel();
BufferedReader bfw = new BufferedReader(new FileReader("Schedulecourses.txt"));
String line;
while( (line = bfw.readLine() ) != null ) {
tm.addRow( line.split("\t") );
}
bfw.close();
}
}
This is how it schould look like
one of them are Days of the Weak(Monday-Friday)
So the data in the TableModel could be stored as an Integer to represent the day of the week. Then you use a custom renderer to convert the Integer value to a descriptive value.
Read the section from the Swing tutorial on Using Custom Renderers for an example.
In your case the code in the setValue(...) method would be something like:
int dayOfWeek = (Integer)value;
switch (dayOfWeek)
{
case 1: setText("Monday"); break;
case 2: setText("Tuesday"); break;
case 3: ...
default: value.toString();
}
the others are Hours(HH:mm),
In this case you are storing two pieces of information. So this means you need to parse the data into two times and then create a custom Comparator to sort based on the first time.
Another option might be to create two columns: "Start Time", "End Time". Then you could store Date objects in the TableModel and then just use the default Comparator that will sort by Date.
Simply implement it yourself. Use some basic sorting algorithm, like quick sort, bubble sort or merge sort (as found on wikipedia), and create your own comparison function to put the entries in order, like, in pseudo code:
bool is_smaller(entry_1, entry_2){
if (entry_1.weekday < entry_2.weekday) return true;
if (entry_1.weekday > entry_2.weekday) return false;
if (entry_1.course hour < entry_2.course_hour) return true;
if (entry_1.course hour > entry_2.course_hour) return false;
return false;
}
(of course with another comparison function for weekday and course hour)
I suggest you try and map the data that you read from the file to some kind of a model object that you can later sort. For example:
public class Course implements Comparable<Course> {
private String name;
private String room;
private String day;
private String hour;
// constructor and getters are omitted. you can add setters as well, but it's best that you keep this class immutable
#Override
public int compareTo(Course course) {
// here you implement the logic of your comparison
}
}
The benefit here is that, by implementing the Comparable<T> interface provided by the Java API, you specify that the instances of your Course class have a natural ordering. Then you can use Collections.sort() and your list of courses will be automatically sorted in the way you want. Then you can use it to back your table model and render it in the table.
Edit 1:
A bit of a clarification on my suggestion:
Right now you read text data from a file, transform each row into an array of strings and pass it to a DefaultTableModel that supplies data to your JTable.
Instead of doing this, you can a bit more complexity to the code, but end up with a better solution from an architectural point of view. What are the steps:
Define a model class (like the example Course class) that will hold the data that is saved in your text file. Implement logic to transform each row of the file into an instance of the Course class. This instances will represent your data and you will use them to populate your table with data.
Implement your own TableModel that holds a sorted list of Course instances (those are the instances you read from the file). Use the implemented model to supply data to your JTable.
I am working with Vaadin and I have some trouble iterating through choices in a ComboBox. I have my object looking like:
class MyObject{
private String text;
private Integer i;
public MyObject(String text,Integer i){
this.text = text;
this.i = i;
}
public String toString(){
return text;
}
//Getters and setters omitted
}
I add it to the box like this:
MyObject o1 = new MyObject("o1",23);
MyObject o2 = new MyObject("o2",44);
ComboBox box=new ComboBox();
box.addItem(o1);
box.addItem(o2);
This works great when I want to get the chosen data:
MyObject o3 = (MyObject)box.getValue();
But now I need to iterate through the choices in the ComboBox and I don't know how. I seem to need some kind of ID but I don't know how to use that. I tried the following with no success but it doesn't work(and is really ugly):
Collection IDs = box.getItemIds();
Iterator it = IDs.iterator();
while(it.hasNext()){
Object id = it.next();
Item item = IDs.getItem(id);
//What to do now?
}
I'd like to keep my object simple and avoid using beans and complex containers. Vaadins examples are mostly for String and that doesn't help me so much. I'd really appreciate any help.
If you look at the javadoc for ComboBox, you'll see that the addItem method is actually defined on the AbstractSelect class, and it actually takes the itemId as the parameter. (This is in turn delegated to the Select's container, which in this default case is an IndexedContainer)
So, Collection IDs=box.getItemIds(); will return you the collection of MyObject - i.e. what you are actually after.