Search Results

Search found 26 results on 2 pages for 'defaulttablemodel'.

Page 1/2 | 1 2  | Next Page >

  • JTable's and DefaultTableModel's row indexes lose their synchronization after I sort JTable

    - by Stefanos Kargas
    JAVA NETBEANS // resultsTable, myModel JTable resultsTable; DefaultTableModel myModel; //javax.swing.table.DefaultTableModel myModel = (DefaultTableModel) resultsTable.getModel(); // event of clicking on item of table String value = (String) myModel.getValueAt(resultsTable.getSelectedRow(), columnIndex) I use JTable and DefaultTableModel to view a table of various info and I want to get a value of a certain column of the selected index of the table. The code I wrote above works fine except when: I use the sort of the GUI (click on the field name I want to sort on the table) The table is properly sorted but after that when I select a row, it gets the value of the row that was there before the sort. This means that after sorting (using the JTable's GUI) the 'myModel' and 'resultsTable' objects have different row indexes. How do I synchronize those two?

    Read the article

  • JTable data only shown after scrolling

    - by Christian 'fuzi' Orgler
    I wrote a method, that creates my DefaultTableModel and there I'm going to add my records. When I set the model to my JTable, the data rows are blank. After scrolling the data gets displayed correct. How can I avoid this and display the data from the first moment? EDIT: I imported the javax.swing.table.DefaultTableModel -- is this correct? private DefaultTableModel _dtm; private void loadTable(Vector<Member> members) { loadTableModel(); try { lbl_state.setText("Please wait"); for (Member actMember : members) { String gender = ""; if (actMember.getGender() == MemberView.MEMBER_MALE) { gender = "männlich"; } else { gender = "weiblich"; } _dtm.addRow(new Object[]{ actMember.getNname(), actMember.getVname(), actMember.getCity(), actMember.getStreet(), actMember.getPlz(), actMember.getMail(), actMember.getPhonenumber(), actMember.getBirthdayString(), actMember.getStartDateString(), gender, actMember.getBankname(), actMember.getAccountnumber(), actMember.getBanknumber(), actMember.getGroup().toString(), (actMember.hasAccess() ? "JA" : "NEIN"), actMember.getWriteDateString(), (actMember.hasDrinkAbo() ? "JA" : "NEIN") }); } } catch (Exception ex) { System.err.println(ex.getMessage()); } tbl_results.setModel(_dtm); } private void loadTableModel() { _dtm = new DefaultTableModel(new Object[]{"Nachname", "Vorname", "Ort", "Straße", "PLZ", "E-Mail", "Telefon", "Geburtsdatum", "Beitrittsdatum", "Geschlecht", "Bankname", "Kontonummer", "Bankleitzahl", "Gruppe", "hat Zugriff", "Einschreibdatum", "Getränkeabo"}, 0); tbl_results.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); }

    Read the article

  • Context Sensitive JTable

    - by Geertjan
    Here's a plain old JTable on the NetBeans Platform. Whenever the toolbar button is clicked, information about the currently selected row is displayed in the status bar: Normally, the above would be achieved in NetBeans Platform applications via Nodes publishing their underlying business object when the selection changes. In this case, there are no Nodes at all. There's only a JTable and a DefaultTableModel, i.e., all pure Java Swing. So, how does it work? To follow the logic, it makes sense to create the example yourself, starting with the Stock object: public class Stock {     String name;     String desc;     public Stock() {     }     public Stock(String name, String desc) {         this.name = name;         this.desc = desc;     }     public String getDesc() {         return desc;     }     public String getName() {         return name;     }     public void setDesc(String desc) {         this.desc = desc;     }     public void setName(String name) {         this.name = name;     } } Next, create a new Window Component via the wizard and then rewrite the constructor as follows: public final class MyWindowTopComponent extends TopComponent {     private final InstanceContent ic = new InstanceContent();     public MyWindowTopComponent() {         initComponents();         //Statically create a few stocks,         //in reality these would come from a data source         //of some kind:         List<Stock> list = new ArrayList();         list.add(new Stock("AMZN", "Amazon"));         list.add(new Stock("BOUT", "About.com"));         list.add(new Stock("Something", "Something.com"));         //Create a JTable, passing the List above         //to a DefaultTableModel:         final JTable table = new JTable(StockTableModel (list));         //Whenever the mouse is clicked on the table,         //somehow construct a new Stock object //(or get it from the List above) and publish it:         table.addMouseListener(new MouseAdapter() {             @Override             public void mousePressed(MouseEvent e) {                 int selectedColumn = table.getSelectedColumn();                 int selectedRow = table.getSelectedRow();                 Stock s = new Stock();                 if (selectedColumn == 0) {                     s.setName(table.getModel().getValueAt(selectedRow, 0).toString());                     s.setDesc(table.getModel().getValueAt(selectedRow, 1).toString());                 } else {                     s.setName(table.getModel().getValueAt(selectedRow, 1).toString());                     s.setDesc(table.getModel().getValueAt(selectedRow, 0).toString());                 }                 ic.set(Collections.singleton(s), null);             }         });         JScrollPane scrollPane = new JScrollPane(table);         add(scrollPane, BorderLayout.CENTER);         //Put the dynamic InstanceContent into the Lookup:         associateLookup(new AbstractLookup(ic));     }     private DefaultTableModel StockTableModel (List<Stock> stockList) {         DefaultTableModel stockTableModel = new DefaultTableModel() {             @Override             public boolean isCellEditable(int row, int column) {                 return false;             }         };         Object[] columnNames = new Object[2];         columnNames[0] = "Symbol";         columnNames[1] = "Name";         stockTableModel.setColumnIdentifiers(columnNames);         Object[] rows = new Object[2];         ListIterator<Stock> stockListIterator = stockList.listIterator();         while (stockListIterator.hasNext()) {             Stock nextStock = stockListIterator.next();             rows[0] = nextStock.getName();             rows[1] = nextStock.getDesc();             stockTableModel.addRow(rows);         }         return stockTableModel;     }     ...     ...     ... And now, since you're publishing a new Stock object whenever the user clicks in the table, you can create loosely coupled Actions, like this: @ActionID(category = "Edit", id = "org.my.ui.ShowStockAction") @ActionRegistration(iconBase = "org/my/ui/Datasource.gif", displayName = "#CTL_ShowStockAction") @ActionReferences({     @ActionReference(path = "Menu/File", position = 1300),     @ActionReference(path = "Toolbars/File", position = 300) }) @Messages("CTL_ShowStockAction=Show Stock") public final class ShowStockAction implements ActionListener {     private final Stock context;     public ShowStockAction(Stock context) {         this.context = context;     }     @Override     public void actionPerformed(ActionEvent ev) {         StatusDisplayer.getDefault().setStatusText(context.getName() + " / " + context.getDesc());     } }

    Read the article

  • Setting the height of a row in a JTable in java

    - by Douglas Grealis
    I have been searching for a solution to be able to increase the height of a row in a JTable. I have been using the setRowHeight(int int) method which compiles and runs OK, but no row[s] have been increased. When I use the getRowHeight(int) method of the row I set the height to, it does print out the size I increased the row to, so I'm not sure what is wrong. The code below is a rough illustration how I am trying to solve it. My class extends JFrame. String[] columnNames = {"Column 1", "Column 2", "Column 1 3"}; JTable table = new JTable(new DefaultTableModel(columnNames, people.size())); DefaultTableModel model = (DefaultTableModel) table.getModel(); int count =1; for(Person p: people) { model.insertRow(count,(new Object[]{count, p.getName(), p.getAge()+"", p.getNationality})); count++; } table.setRowHeight(1, 15);//Try set height to 15 (I've tried higher) Can anyone tell me where I am going wrong? I am trying to increase the height of row 1 to 15 pixels?

    Read the article

  • Data from 6 ArrayLists into a single JTable - Java Swing

    - by Splunk
    I have created a JTable which is populated by various arraylists which get their data from a text list using a "~" to split. The issue I am having is that the table is displaying all data from the list on a single row. For example: Column1 Column2 Column2 Column2 Column3 Column4 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 1,2,3,4,5 When I want it to display Column1 Column2 Column2 Column2 Column3 Column4 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 You get the idea. From previous advice, I think the issue may be looping, but I am not sure. Any advice would be great. The code is below: private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); } This is the class that has the arraylists: import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; public class FileIOManagement { private ArrayList<String> nameList = new ArrayList<String>(); private ArrayList<String> courseList = new ArrayList<String>(); private ArrayList<String> semesterList = new ArrayList<String>(); private ArrayList<String> moderatorList = new ArrayList<String>(); private ArrayList<String> programList = new ArrayList<String>(); private ArrayList<String> majorList = new ArrayList<String>(); public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public FileIOManagement(){ setNameList(new ArrayList<String>()); setCourseList(new ArrayList<String>()); setSemesterList(new ArrayList<String>()); setModeratorList(new ArrayList<String>()); setProgramList(new ArrayList<String>()); setMajorList(new ArrayList<String>()); readTextFile(); getNameList(); getCourseList(); } private void readTextFile(){ try{ Scanner scan = new Scanner(new File("Course.txt")); while(scan.hasNextLine()){ String line = scan.nextLine(); String[] tokens = line.split("~"); String course = tokens[0].trim(); String examiner = tokens[1].trim(); String moderator = tokens[2].trim(); String semester = tokens[3].trim(); String program = tokens[4].trim(); String major = tokens[5].trim(); courseList.add(course); semesterList.add(semester); nameList.add(examiner); moderatorList.add(moderator); programList.add(program); majorList.add(major); HashSet hs = new HashSet(); hs.addAll(nameList); nameList.clear(); nameList.addAll(hs); Collections.sort(nameList); } scan.close(); } catch (FileNotFoundException e){ e.printStackTrace(); } } } This is the class where I need to have the JTable: import java.awt.*; import javax.swing.*; import java.io.*; import javax.swing.border.EmptyBorder; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.table.DefaultTableModel; public class AllDataGUI extends JFrame{ private JButton saveCloseBtn = new JButton("Save Changes and Close"); private JButton closeButton = new JButton("Exit Without Saving"); private JFrame frame=new JFrame("Viewing All Program Details"); private final FileIOManagement fileManage = new FileIOManagement(); private ArrayList<String> nameList = new ArrayList(); private ArrayList<String> courseList = new ArrayList(); private ArrayList<String> semesterList = new ArrayList(); private ArrayList<String> moderatorList = new ArrayList(); private ArrayList<String> majorList = new ArrayList(); private ArrayList<String> programList = new ArrayList(); private JTable textArea; public ArrayList<String> getNameList(){ return this.nameList; } public ArrayList<String> getCourseList(){ return this.courseList; } public ArrayList<String> getSemesterList(){ return this.semesterList; } public ArrayList<String> getModeratorList(){ return this.moderatorList; } public ArrayList<String> getProgramList(){ return this.programList; } public ArrayList<String> getMajorList(){ return this.majorList; } public void setNameList(ArrayList<String> nameList){ this.nameList = nameList; } public void setCourseList(ArrayList<String> courseList){ this.courseList = courseList; } public void setSemesterList(ArrayList<String> semesterList){ this.semesterList = semesterList; } public void setModeratorList(ArrayList<String> moderatorList){ this.moderatorList = moderatorList; } public void setProgramList(ArrayList<String> programList){ this.programList = programList; } public void setMajorList(ArrayList<String> majorList){ this.majorList = majorList; } public AllDataGUI(){ getData(); table(); panels(); } public Object getValueAt(int rowIndex, int columnIndex) { String[] token = nameList.get(rowIndex).split(","); return token[columnIndex]; } private void table(){ String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; DefaultTableModel model = new DefaultTableModel(colName,0); for(Object item : courseList){ Object[] row = new Object[6]; // String[] row = new String[6]; row[0] = fileManage.getCourseList(); row[1] = fileManage.getNameList(); row[2] = fileManage.getModeratorList(); row[3] = fileManage.getSemesterList(); row[4] = fileManage.getProgramList(); row[5] = fileManage.getMajorList(); model.addRow(row); textArea = new JTable(model); // String END_OF_LINE = ","; // // String[] colName = { "Course", "Examiner", "Moderator", "Semester Available ", "Associated Programs", "Associated Majors"}; //// textArea.getTableHeader().setBackground(Color.WHITE); //// textArea.getTableHeader().setForeground(Color.BLUE); // // Font Tablefont = new Font("Details", Font.BOLD, 12); // // textArea.getTableHeader().setFont(Tablefont); // Object[][] object = new Object[100][100]; // int i = 0; // if (fileManage.size() != 0) { // for (fileManage book : fileManage) { // object[i][0] = fileManage.getCourseList(); // object[i][1] = fileManage.getNameList(); // object[i][2] = fileManage.getModeratorList(); // object[i][3] = fileManage.getSemesterList(); // object[i][4] = fileManage.getProgramList(); // object[i][5] = fileManage.getMajorList(); // // textArea = new JTable(object, colName); // } // } } } public void getData(){ nameList = fileManage.getNameList(); courseList = fileManage.getCourseList(); semesterList = fileManage.getSemesterList(); moderatorList = fileManage.getModeratorList(); majorList = fileManage.getMajorList(); programList = fileManage.getProgramList(); // textArea.(write()); } private JButton getCloseButton(){ return closeButton; } private void panels(){ JPanel panel = new JPanel(new GridLayout(1,1)); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10)); rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10)); JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); panel.add(scrollBarForTextArea); frame.add(panel); frame.getContentPane().add(rightPanel,BorderLayout.EAST); rightPanel.add(saveCloseBtn); rightPanel.add(closeButton); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.dispose(); } }); saveCloseBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //saveBtn(); frame.dispose(); } }); frame.setSize(1000, 700); frame.setVisible(true); frame.setLocationRelativeTo(null); } // private void saveBtn(){ // File file = null; // FileWriter out=null; // try { // file = new File("Course.txt"); // out = new FileWriter(file); // out.write(textArea.getText()); // out.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // JOptionPane.showMessageDialog(this, "File Successfully Updated"); // // } }

    Read the article

  • StackOverflowError being caused by a TableModelListener

    - by me_here
    I'm not sure why this is recursing. jTable1.getModel().addTableModelListener(new TableModelListener() { public void tableChanged(TableModelEvent evt) { int sum = 0; int i=0; for (i =0 ; i<2; i++){ sum = sum + Integer.parseInt(jTable1.getValueAt(0, i).toString()); } jTable1.setValueAt(sum, 0, 2); } }); The exception is: (it keeps repeating) Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277) at javax.swing.JTable.convertColumnIndexToModel(JTable.java:2553) at javax.swing.JTable.getValueAt(JTable.java:2695) at testprogram.guitest.TestTableModel$1.tableChanged(TestTableModel.java:63) at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280) at javax.swing.table.AbstractTableModel.fireTableCellUpdated(AbstractTableModel.java:259) at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:650) at javax.swing.JTable.setValueAt(JTable.java:2719) Any help appreciated.

    Read the article

  • how to put jcheckbox to table cell?

    - by joseph
    Hello, I cannot put jChceckBox to jTable cell. More likely I can put checkBox to table, but when I run module with that table, the cell where should be checkBox shows text "true" or "false". The behaviors of that cell are the same like checkbox, but it shows text value instead of checkbox. Here is the code. DefaultTableModel dm = new DefaultTableModel(); dm.setDataVector(new Object[][]{{"dd", "Edit", "Delete"}, {"dd","Edit", "Delete"}}, new Object[]{"Include","Component", "Ekvi"}); jTable1 = new javax.swing.JTable(); jTable1.setModel(dm); JCheckBox chBox=new JCheckBox(); jTable1.getColumn("Include").setCellEditor(new DefaultCellEditor(chBox)); jScrollPane1.setViewportView(jTable1);

    Read the article

  • Using MigLayout, why is a JButton following a JTable unresponsive and how to fix this?

    - by M. Joanis
    Hi everyone, I am having a mind-boggling problem regarding the use of a JButton following a JTable with MigLayout. It is totally unresponsive unless I push it far enough past the JTable (then it can behave correctly). I have tried running the code with both the MigLayout JAR of the version we use for end user products and with the very most recent one; same result. Here is a sample code reproducing the problem (Main.java): import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; @SuppressWarnings("serial") public class Main extends JFrame { private JPanel panel; private JTextField textField; private JButton chooseButton; private JTable table; private JButton reloadButton; private final DefaultTableModel model = new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { return false; } }; public Main() { panel = new JPanel(new MigLayout("debug", "[][grow][]")); setContentPane(panel); setDefaultCloseOperation(EXIT_ON_CLOSE); /*** First row ***/ // "File:" panel.add(new JLabel("File:")); // textField for filename textField = new JTextField("No file selected yet!"); textField.setEditable(false); panel.add(textField, "growx"); // "Choose..." button chooseButton = new JButton("Choose..."); panel.add(chooseButton, "wrap, sg buttons"); /*** Second row ***/ panel.add(new JLabel()); table = new JTable(model); model.setColumnIdentifiers(new String[] {"col title"}); JScrollPane scrollpane = new JScrollPane(table); Dimension scrollpaneDimension = new Dimension(125, 110); scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); table.setPreferredScrollableViewportSize(scrollpaneDimension); table.setFillsViewportHeight(true); panel.add(table.getTableHeader(), "grow"); panel.add(scrollpane, "grow"); reloadButton = new JButton("Reload"); panel.add(reloadButton, "top, wrap, sg buttons"); pack(); setVisible(true); } public static void main(String[] args) { new Main(); } } I suppose it has something to do with the table header and the table itself ending up in the same layout cell, but I'm really not sure of this. As I said, if I push the button far enough past the JTable, it will work again. If I drop it on the next row, it doesn't work, I have to move it down one more row. The only library you need in your workspace to run the code is MigLayout. Thank you all for your help, much appreciated! M. Joanis

    Read the article

  • MouseMotionListener inside JTable

    - by Harish
    I am trying to add MouseMotion event to the label and move it based on the dragging of the mouse and make it move along with my mouse.However the mousemotion is very difficult to control making this action not usable. Here is the code import java.awt.Color; import java.awt.Component; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; public class TableTest { public TableTest() { String[] columnNames = { "FileName", "Integer" }; Object[][] data = { { new FileName("AAA.jpg", Color.YELLOW), new Integer(2) }, { new FileName("BBB.png", Color.GREEN), new FileName("BBB.png", Color.GREEN) }, { new FileName("CCC.jpg", Color.RED), new Integer(-1) }, }; DefaultTableModel model = new DefaultTableModel(data, columnNames) { public Class getColumnClass(int column) { System.out.println("column is" + column); return getValueAt(0, column).getClass(); } }; JTable table = new JTable(model); //JTable table = new JTable(data, columnNames); table.setDefaultRenderer(FileName.class, new FileNameCellRenderer()); final JLabel label = new JLabel("TESTING", SwingConstants.CENTER); label.setBackground(java.awt.Color.RED); label.setBounds(450, 100, 90, 20); label.setOpaque(true); label.setVisible(true); label.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent arg0) { label.setBounds(arg0.getX(), arg0.getY(), 90, 20); } public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } }); table.add(label); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(table); frame.setSize(800, 600); frame.setLocationRelativeTo(null); frame.setVisible(true); } static class FileNameCellRenderer extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object v, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, v, isSelected, hasFocus, row, column); FileName fn = (FileName) v; setBorder(BorderFactory.createMatteBorder(0, 60, 0, 0, new java.awt.Color(143, 188, 143))); return this; } } static class FileName { public final Color color; public final String label; FileName(String l, Color c) { this.label = l; this.color = c; } public String toString() { return label; } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TableTest(); } }); } } I just want to make the label follow the label follow my mouse and the label should be attached to the table.Is there an easy way than this.

    Read the article

  • FindBugs controversial description

    - by Tom Brito
    Am I understanding it wrong, or is the description wrong? Equals checks for noncompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS) This equals method is checking to see if the argument is some incompatible type (i.e., a class that is neither a supertype nor subtype of the class that defines the equals method). For example, the Foo class might have an equals method that looks like: public boolean equals(Object o) { if (o instanceof Foo) return name.equals(((Foo)o).name); else if (o instanceof String) return name.equals(o); else return false; This is considered bad practice, as it makes it very hard to implement an equals method that is symmetric and transitive. Without those properties, very unexpected behavoirs are possible. From: http://findbugs.sourceforge.net/bugDescriptions.html#EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS The description says that the Foo class might have an equals method like that, and after it says that "This is considered bad practice". I'm not getting the "right way".. How should the following method be to be right? @Override public boolean equals(Object obj) { if (obj instanceof DefaultTableModel) return model.equals((DefaultTableModel)obj); else return false; }

    Read the article

  • FindBugs controversal description

    - by Tom Brito
    Am I understanding it wrong, or is the description wrong? Equals checks for noncompatible operand (EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS) This equals method is checking to see if the argument is some incompatible type (i.e., a class that is neither a supertype nor subtype of the class that defines the equals method). For example, the Foo class might have an equals method that looks like: public boolean equals(Object o) { if (o instanceof Foo) return name.equals(((Foo)o).name); else if (o instanceof String) return name.equals(o); else return false; This is considered bad practice, as it makes it very hard to implement an equals method that is symmetric and transitive. Without those properties, very unexpected behavoirs are possible. From: http://findbugs.sourceforge.net/bugDescriptions.html#EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS The description says that the Foo class might have an aquals method like that, and after it says that "This is considered bad practice". I'm not getting the "right way".. How should the following method be to be right? @Override public boolean equals(Object obj) { if (obj instanceof DefaultTableModel) return model.equals((DefaultTableModel)obj); else return false; }

    Read the article

  • Java Swing Table questions

    - by Dalton Conley
    Hey guys, working on an event calendar. I'm having some trouble getting my column heads to display.. here is the code private JTable calendarTable; private DefaultTableModel calendarTableModel; final private String [] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; ////////////////////////////////////////////////////////////////////// /* Setup the actual calendar table */ calendarTableModel = new DefaultTableModel() { public boolean isCellEditable(int row, int col){ return false; } }; // setup columns for(int i = 0; i < 7; i++) calendarTableModel.addColumn(days[i]); calendarTable = new JTable(calendarTableModel); calendarTable.getTableHeader().setResizingAllowed(false); calendarTable.getTableHeader().setReorderingAllowed(false); calendarTable.setColumnSelectionAllowed(true); calendarTable.setRowSelectionAllowed(true); calendarTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); calendarTable.setRowHeight(105); calendarTableModel.setColumnCount(7); calendarTableModel.setRowCount(6); Also, Im sort of new with tables.. how can I make the rowHeight split between the max size of the table?

    Read the article

  • Jtable live updating problem

    - by Fishinastorm
    Hi all, I'm trying to display a jtable in a pop up Jframe and am running into some problems. What i'am trying to do is as follows: catch a button action event in the main frame and display a pop up frame with a jtable populated with some data. The problem i have is that the jtable is populated with metadata i receive from a website and if i'm receiving many records, then the jtable is not displayed until all the records(metadata) is received from the website. I would like to change it such that as soon as the button event is detected in the main frame, I display the pop up frame along with the jtable and insert/update rows "as and when i receive the data from the website". In another words, i want to display the table and have the records appearing one at a time rather than displaying the jtable only after i receive all records.Below is how i'm trying to do it (but in vain :( ): ......... //add the table to the popup frame when application is started, but don't display the frame `until button action is //detected` extraInfoFrame.add(tblMetadata); extraInfoFrame.setVisible(false); //handle code for button press; display the popup private void butMetadataActionPerformed(java.awt.event.ActionEvent evt) { extraInfoFrame.pack(); extraInfoFrame.toFront(); //frame.setSize(350, 250); extraInfoFrame.setVisible(true); //retrieve rows data for the table for(int i=0;i<len;i++){ Object[] data=new Object[4];data=getMetadata(); //get model and insert row ((javax.swing.table.DefaultTableModel)tblMetadata.getModel()).insertRow(i,data); //tried something to notify the view abt change in table data ((javax.swing.table.DefaultTableModel)tblMetadata.getModel()).fireTableRowsInserted(0, 0); tblMetadata.revalidate(); tblMetadata.repaint(); } } Have been racking my head to try and figure something out. A sample example would be greatly appreciated.

    Read the article

  • Create JTable in a JPanel and add row

    - by DK64
    On my program I've dinamically created a JFrame that contains a JPanel called jp. jp also contains a JTable that I would like to fill with some rows. case KeyEvent.VK_R: JFrame frame = new JFrame("Snake v2.0 - Rankings"); JPanel jp = new JPanel(); jp.setPreferredSize(new Dimension(300,300)); JTable table = new JTable(); JScrollPane tableContainer = new JScrollPane(table); jp.add(tableContainer, BorderLayout.CENTER); DefaultTableModel tm = (DefaultTableModel) table.getModel(); tm.addRow(new Object[] {"#","Player","Score","Date"}); frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setResizable(false); frame.getContentPane().add(jp); frame.pack(); frame.setVisible(true); break; This is my code. When I press R on the keyboard, the JFrame with that JPanel inside appears but the table doesnt (picture). What could I do?

    Read the article

  • Swing JTable Scrolling not working properly

    - by Marko
    I'm doing an application, which uses Swing JTable. I used drag and drop in NetBeans, to add the JTable. When I add the JTable, JScrollPane is added automaticly. All the look is done with drag and drop. By pressing the first button, I set the number of rows in the table. This is the code to set my DataModel int size = 50; String[] colNames = {"Indeks", "Ime", "Priimek", "Drzava"}; DefaultTableModel model = new DefaultTableModel(size, colNames.length); model.setColumnIdentifiers(colNames); table.setModel(model); So if the size is, let's say 10, it works OK, since there is no scroll bar. When I add 50 empty rows, when trying to scroll for 5 seconds, it doesn't work properly and crashes in some time. I added the picture, for better understanding (this is what happens to the rows when I scroll up and down for a while). What could be wrong? Am I not using the DataModel as it is supposed to be used, should I .revalidate() or .repaint() the JTable?

    Read the article

  • jtable update data not visible

    - by Thomas n
    I am running into a problem similar to what I have read here about inserted data and added data not showing up on jtable. I have tried repaint() and revalidate(), but to no avail. Basically, I have two classes say A and B. A calls a function in class B to add a row of data to the table. Here is the code.(By the way I am using Netbeans 7.1.2 to add a table and then add some code to handle the update.) public void callUpdateTable(){ DefaultTableModel myModel = (DefaultTableModel)jTable1.getModel(); DateFormat dateFormate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Object[] str = new Object[3]; Date date = new Date(); str[0] = dateFormate.format(date); str[1] = "Robot"; str[2] = "hello"; // myModel.addRow(str); myModel.insertRow(1, str); myModel.setValueAt("Hello", 1, 2); System.out.println("count = " + myModel.getValueAt(1, 2)); jTable1.repaint(); } The funny thing is on system print it prints out the value at the cell(1,2) I set the value, but doesn't show up on the table. Thank you for your help.

    Read the article

  • How to implement button in a vector

    - by user1880497
    In my table. I want to put some buttons into each row that I can press. But I do not know how to do it public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException { java.sql.ResultSetMetaData metaData = rs.getMetaData(); // names of columns Vector<String> columnNames = new Vector<String>(); int columnCount = metaData.getColumnCount(); for (int column = 1; column <= columnCount; column++) { columnNames.add(metaData.getColumnName(column)); } // data of the table Vector<Vector<Object>> data = new Vector<Vector<Object>>(); while (rs.next()) { Vector<Object> vector = new Vector<Object>(); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { vector.add(rs.getObject(columnIndex)); } data.add(vector); } return new DefaultTableModel(data, columnNames); }

    Read the article

  • Structure of a correctly implemented JTable with TableModel and Listeners?

    - by bamboocha
    I am pretty new to Java and its JTables and this is where I am struggling at the moment. I need to create a GUI which shows me results of a sql query like SELECT * FROM tblPeople WHERE name='Doe'. My idea was to create a a JFrame which displays a JTable with all found records. Besides this, I need to also implement some code to handle when a user is double clicking a record or selecting it by using his arrow keys (additional feature: pressing 12(e.g.) should select the 12th record). What is the best way to structure my program (what classes do I need and especially where do I store my logic)? I came up with structuring it the following way: Main.java ("view") SQLConnection.java PeopleTableModel.java (only stores and returns data given by the passed ResultSet, "model" inherits from DefaultTableModel) PeopleTable.java (stores basically all my logic including KeyListener and MouseListener, "controller", inherits from JTable) Are there better ways to achieve my goals? If so, what are they?

    Read the article

  • JAVA - Strange problem (probably thread problem) with JTable & Model

    - by Stefanos Kargas
    I am using 2 Tables (JTable) with their DefaultTableModels. The first table is already populated. The second table is populated for each row of the first table (using an SQL Query). My purpose is to export every line of the first table with it's respective lines of the second in an Excel File. I am doing it with a for (for each line of 1st table), in which I write a line of the 1st table in the Excel File, then I populate the 2nd table (for this line of 1st Table), I get every line from the Table (from it's Model actually) and put it in the Excel File under the current line of 1st table. This means that if I have n lines in first table I will clear and populate again the second table n times. All this code is called in a seperate thread. THE PROBLEM IS: Everything works perfectly fine ecxept that I am getting some exceptions. The strange thing is that I'm not getting anything false in my result. The Excel file is perfect. Some of the lines of the exceptions are: Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 = 0 at java.util.Vector.elementAt(Vector.java:427) at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:632) at javax.swing.JComponent.paint(JComponent.java:1017) at javax.swing.RepaintManager.paint(RepaintManager.java:1220) at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:803) I am assuming that the problem lies in the fact that the second table needs some more time to be populated before I try to get any data from it. That's why I see RepaintManager and paintDirtyRegions in my exceptions. Another thing I did is that I ran my program in debug mode and I put a breakpoint after each population of the 2nd table. Then I pressed F5 to continue for each population of 2nd table and no exception appeared. The program came to it's end without any exceptions. This is another important fact that tells me that maybe in this case I gave the table enough time to be populated. Of course you will ask me: If your program works fine, why do you care about the exceptions? I care for avoiding any future problems and I care to have a better understanding of Java and Java GUI and threads. Why do you depend on a GUI component (and it's model) to get your information and why don't you recreate the resultset that populates your tables using an SQL Query and get your info from the resultset? That would be the best and the right way. The fact is that I have the tables code ready and it was easier for me to just get the info from them. But the right way would be to get everything direct from database. Anyway what I did brought out my question, and answering it would help me understand more things about java. So I posted it.

    Read the article

  • Creating a table with an initial element selected

    - by Tony
    I want to create a table which displays in each row a set of data, in addition to a radio button for possible selection. This can be achieved easily by using a simple table model class which extends the DefaultTableModel and a cell renderer and editor class which implements the TableCellRenderer and TableCellEditor interfaces respectively. What I really couldn't manage to do is to make the table to display initially one of the elements (rows) initially selected. It seems straightforward but it isn't...does anybody have a clue about it?

    Read the article

  • how to sort JTable by providing column index externally.

    - by user345940
    I would like to implement sorting on JTable by providing column index externally in program. Here is my sample code in which i have initialize JTable, Add one Column and 30 rows to JTable. After rows has been added i am sorting JTable by providing column index 0 but i could not get sorted data. how can i get my first column in sorted order? what's wrong with my code. **Why sortCTableonColumnIndex() method could not sort data for specify column index? ` public class Test { private JTable oCTable; private DefaultTableModel oDefaultTableModel; private JScrollPane oPane; private JTableHeader oTableHeader; private TableRowSorter sorter; public void adddata() { for (int i = 0; i < 30; i++) { Object[] row = new Object[1]; String sValueA = "A"; String sValueB = "A"; row[0] = ""; if (i % 2 == 0) { if (i < 15) { sValueA = sValueA + sValueA; row[1] = sValueA; } else { if (i == 16) { sValueB = "D"; row[1] = sValueA; } else { sValueB = sValueB + sValueB; row[1] = sValueA; } } } else { if (i < 15) { sValueB = sValueB + sValueB; row[1] = sValueB; } else { if (i == 17) { sValueB = "C"; row[1] = sValueB; } else { sValueB = sValueB + sValueB; row[1] = sValueB; } } } } } public void createTable() { oCTable = new JTable(); oDefaultTableModel = new DefaultTableModel(); oCTable.setModel(oDefaultTableModel); oTableHeader = oCTable.getTableHeader(); oCTable.setAutoResizeMode(oCTable.AUTO_RESIZE_OFF); oCTable.setFillsViewportHeight(true); JTable oTable = new LineNumberTable(oCTable); oPane = new JScrollPane(oCTable); oPane.setRowHeaderView(oTable); JPanel oJPanel = new JPanel(); oJPanel.setLayout(new BorderLayout()); oJPanel.add(oPane, BorderLayout.CENTER); JDialog oDialog = new JDialog(); oDialog.add(oJPanel); oDialog.setPreferredSize(new Dimension(500, 300)); oDialog.pack(); oDialog.setVisible(true); } public void insert() { oDefaultTableModel.addColumn("Name"); int iColumnPlace = ((DefaultTableModel) oCTable.getModel()).findColumn("Name"); CellRendererForRowHeader oCellRendererForRowHeader = new CellRendererForRowHeader(); TableColumn Column = oCTable.getColumn(oTableHeader.getColumnModel().getColumn(iColumnPlace).getHeaderValue()); Column.setPreferredWidth(300); Column.setMaxWidth(300); Column.setMinWidth(250); Column.setCellRenderer(oCellRendererForRowHeader); for (int i = 0; i < 30; i++) { Object[] row = new Object[1]; String sValueA = "A"; if (i % 2 == 0) { if (i < 15) { sValueA = sValueA + "a"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { if (i == 16) { sValueA = sValueA + "b"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { sValueA = sValueA + "c"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } } } else { if (i < 15) { sValueA = sValueA + "d"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { if (i == 17) { sValueA = sValueA + "e"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } else { sValueA = sValueA + "f"; oDefaultTableModel.insertRow(oCTable.getRowCount(), new Object[]{""}); oDefaultTableModel.setValueAt(sValueA, i, 0); } } } } } public void showTable() { createTable(); insert(); sortCTableonColumnIndex(0, true); } public void sortCTableonColumnIndex(int iColumnIndex, boolean bIsAsc) { sorter = new TableRowSorter(oDefaultTableModel); List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>(); if (bIsAsc) { sortKeys.add(new RowSorter.SortKey(iColumnIndex, SortOrder.ASCENDING)); } else { sortKeys.add(new RowSorter.SortKey(iColumnIndex, SortOrder.DESCENDING)); } sorter.setSortKeys(sortKeys); oDefaultTableModel.fireTableStructureChanged(); oCTable.updateUI(); } public static void main(String[] argu) { Test oTest = new Test(); oTest.showTable(); } class CellRendererForRowHeader extends DefaultTableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JLabel label = null; try { label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == 0) { label.setBackground(new JLabel().getBackground()); label.setForeground(Color.BLACK); } } catch (RuntimeException ex) { } return label; } } class LineNumberTable extends JTable { private JTable mainTable; public LineNumberTable(JTable table) { super(); mainTable = table; setAutoCreateColumnsFromModel(false); setModel(mainTable.getModel()); setAutoscrolls(false); addColumn(new TableColumn()); getColumnModel().getColumn(0).setCellRenderer(mainTable.getTableHeader().getDefaultRenderer()); getColumnModel().getColumn(0).setPreferredWidth(40); setPreferredScrollableViewportSize(getPreferredSize()); } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public Object getValueAt(int row, int column) { return Integer.valueOf(row + 1); } @Override public int getRowHeight(int row) { return mainTable.getRowHeight(); } } } `

    Read the article

  • My Jtable is blank

    - by mazin
    Hello my q is about a jtable that i have ,i fill it with components from a .txt ,I have a main (menu ) JFrame and by pressing a jbutton i want the jtable to pop out ! My problem is that my jtable is blank and it supposed to show some date !I would appreciated any help , Thanks. this is my ''reading'' class` public static void main(String[] args) { company Company=new company(); payFrame jframe=new payFrame(Company); jframe.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); jframe.setSize(600,300); jframe.setVisible(true); readClass(); } //diavasma public static void readClass(){ ArrayList<Employee> emp =new ArrayList<Employee>() ; //Employee[] emp=new Employee[7]; //read from file try { int i=0; // int rowCounter; // int payments=0; String inputDocument = ("src/Employees.txt"); FileInputStream is = new FileInputStream(inputDocument); Reader iD = new InputStreamReader(is); BufferedReader buf = new BufferedReader(iD); String inputLine; while ((inputLine = buf.readLine()) != null) { String[] lineParts = inputLine.split(","); String email = (lineParts[7]); int EmpNo = Integer.parseInt(lineParts[0]); String type = lineParts[10]; int PostalCode = Integer.parseInt(lineParts[5]); int phone = Integer.parseInt(lineParts[6]); int DeptNo = (short) Integer.parseInt(lineParts[8]); double Salary; int card = (short) Integer.parseInt(lineParts[10]); int emptype = 0; int hours=Integer.parseInt(lineParts[11]); if (type.equals("FULL TIME")) { emptype = 1; } else if (type.equals("SELLER")) { emptype = 2; } else { emptype = 3; } /** * Creates employee instances depending on their type of employment * (fulltime=1, salesman=2, parttime=3) */ switch (emptype) { case 1: Salary = Double.parseDouble(lineParts[10]); emp.add(new FullTime(lineParts[1], lineParts[2], EmpNo, lineParts[3], lineParts[4], PostalCode, phone, email, DeptNo, card, Salary,hours, type)); i++; break; and this is my class where i make my Jtable and fill him public class company extends JFrame { private ArrayList<Employee> emp = new ArrayList<Employee>(); public void addEmployee(Employee emplo) { emp.add(emplo); } public ArrayList<Employee> getArray() { return emp; } public void getOption1() { ArrayList<Employee> employee = getArray(); JTable table = new JTable(); DefaultTableModel model = new DefaultTableModel(); table.setModel(model); model.setColumnIdentifiers(new String[]{"Code", "First Name", "Last Name", "Address", "City", "Postal Code", "Phone", "Email", "Dept Code", "Salary", "Time Card", "Hours"}); for (Employee current : employee) { model.addRow(new Object[]{current.getempCode(), current.getfirst(), current.getlast(), current.getaddress(), current.getcity(), current.getpostalCode(), current.gettelephone(), current.getemail(), current.getdep(), current.getsalary(), current.getcardcode(), current.getHours() }); } table.setPreferredScrollableViewportSize(new Dimension(500, 50)); table.setFillsViewportHeight(true); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane); setVisible(true); table.revalidate();

    Read the article

  • timetable in a jTable

    - by chandra
    I want to create a timetable in a jTable. For the top row it will display from monday to sunday and the left colume will display the time of the day with 2h interval e.g 1st colume (0000 - 0200), 2nd colume (0200 - 0400) .... And if i click a button the timing will change from 2h interval to 1h interval. I do not want to hardcode it because i need to do for 2h, 1h, 30min , 15min, 1min, 30sec and 1 sec interval and it will take too long for me to hardcode. Can anyone show me an example or help me create an example for the 2h to 1h interval so that i know what to do? The data array is for me to store data and are there any other easier or shortcuts for me to store them because if it is in 1 sec interval i got thousands of array i need to type it out. private void oneHour() //1 interval functions { if(!once) { initialize(); once = true; } jTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"0000 - 0100", data[0][0], data[0][1], data[0][2], data[0][3], data[0][4], data[0][5], data[0][6]}, {"0100 - 0200", data[2][0], data[2][1], data[2][2], data[2][3], data[2][4], data[2][5], data[2][6]}, {"0200 - 0300", data[4][0], data[4][1], data[4][2], data[4][3], data[4][4], data[4][5], data[4][6]}, {"0300 - 0400", data[6][0], data[6][1], data[6][2], data[6][3], data[6][4], data[6][5], data[6][6]}, {"0400 - 0600", data[8][0], data[8][1], data[8][2], data[8][3], data[8][4], data[8][5], data[8][6]}, {"0600 - 0700", data[10][0], data[4][1], data[10][2], data[10][3], data[10][4], data[10][5], data[10][6]}, {"0700 - 0800", data[12][0], data[12][1], data[12][2], data[12][3], data[12][4], data[12][5], data[12][6]}, {"0800 - 0900", data[14][0], data[14][1], data[14][2], data[14][3], data[14][4], data[14][5], data[14][6]}, {"0900 - 1000", data[16][0], data[16][1], data[16][2], data[16][3], data[16][4], data[16][5], data[16][6]}, {"1000 - 1100", data[18][0], data[18][1], data[18][2], data[18][3], data[18][4], data[18][5], data[18][6]}, {"1100 - 1200", data[20][0], data[20][1], data[20][2], data[20][3], data[20][4], data[20][5], data[20][6]}, {"1200 - 1300", data[22][0], data[22][1], data[22][2], data[22][3], data[22][4], data[22][5], data[22][6]}, {"1300 - 1400", data[24][0], data[24][1], data[24][2], data[24][3], data[24][4], data[24][5], data[24][6]}, {"1400 - 1500", data[26][0], data[26][1], data[26][2], data[26][3], data[26][4], data[26][5], data[26][6]}, {"1500 - 1600", data[28][0], data[28][1], data[28][2], data[28][3], data[28][4], data[28][5], data[28][6]}, {"1600 - 1700", data[30][0], data[30][1], data[30][2], data[30][3], data[30][4], data[30][5], data[30][6]}, {"1700 - 1800", data[32][0], data[32][1], data[32][2], data[32][3], data[32][4], data[32][5], data[32][6]}, {"1800 - 1900", data[34][0], data[34][1], data[34][2], data[34][3], data[34][4], data[34][5], data[34][6]}, {"1900 - 2000", data[36][0], data[36][1], data[36][2], data[36][3], data[36][4], data[36][5], data[36][6]}, {"2000 - 2100", data[38][0], data[38][1], data[38][2], data[38][3], data[38][4], data[38][5], data[38][6]}, {"2100 - 2200", data[40][0], data[40][1], data[40][2], data[40][3], data[40][4], data[40][5], data[40][6]}, {"2200 - 2300", data[42][0], data[42][1], data[42][2], data[42][3], data[42][4], data[42][5], data[42][6]}, {"2300 - 2400", data[44][0], data[44][1], data[44][2], data[44][3], data[44][4], data[44][5], data[44][6]}, {"2400 - 0000", data[46][0], data[46][1], data[46][2], data[46][3], data[46][4], data[46][5], data[46][6]}, }, new String [] { "Time/Day", "(Mon)", "(Tue)", "(Wed)", "(Thurs)", "(Fri)", "(Sat)", "(Sun)" } )); } private void twoHour() //2 hour interval functions { if(!once) { initialize(); once = true; } jTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"0000 - 0200", data[0][0], data[0][1], data[0][2], data[0][3], data[0][4], data[0][5], data[0][6]}, {"0200 - 0400", data[4][0], data[4][1], data[4][2], data[4][3], data[4][4], data[4][5], data[4][6]}, {"0400 - 0600", data[8][0], data[8][1], data[8][2], data[8][3], data[8][4], data[8][5], data[8][6]}, {"0600 - 0800", data[12][0], data[12][1], data[12][2], data[12][3], data[12][4], data[12][5], data[12][6]}, {"0800 - 1000", data[16][0], data[16][1], data[16][2], data[16][3], data[16][4], data[16][5], data[16][6]}, {"1000 - 1200", data[20][0], data[20][1], data[20][2], data[20][3], data[20][4], data[20][5], data[20][6]}, {"1200 - 1400", data[24][0], data[24][1], data[24][2], data[24][3], data[24][4], data[24][5], data[24][6]}, {"1400 - 1600", data[28][0], data[28][1], data[28][2], data[28][3], data[28][4], data[28][5], data[28][6]}, {"1600 - 1800", data[32][0], data[32][1], data[32][2], data[32][3], data[32][4], data[32][5], data[32][6]}, {"1800 - 2000", data[36][0], data[36][1], data[36][2], data[36][3], data[36][4], data[36][5], data[36][6]}, {"2000 - 2200", data[40][0], data[40][1], data[40][2], data[40][3], data[40][4], data[40][5], data[40][6]}, {"2200 - 2400",data[44][0], data[44][1], data[44][2], data[44][3], data[44][4], data[44][5], data[44][6]} },

    Read the article

  • can i add the combobox into particular cell of the JTable?

    - by Venkats
    I want to add combobox into a cell of JTable. model=new DefaultTableModel(data,col); JTableHeader head=new JTableHeader(); head.setBackground(Color.BLUE); table=new JTable(model); table.add(head); JComboBox combo = new JComboBox(); combo.addItem("Names"); combo.addItem("Antony"); combo.addItem("Victor"); combo.addItem("Ramkumar"); table.add(combo); But i cant get the combobox in the cell. Is it possible to set combo box?

    Read the article

  • Displaying emails in a JTable (Java Swing)

    - by Paul
    Hi I'm new to all this. I have been trying to display fetched emails in a JTable using the JavaMail add-on. However when I ask the program to set the value it never does. I have been working in NetBeans if that is any help? the fetchMail class finds all may on a server. The gui class is used to display all emails in a table as well as creating mail. You will probably think that I have tried it like a bull in a china shop, I am new to Java and trying to give myself a challenge. Any help/advice would be greatly appreciated fetchMail: package mail; import java.util.; import java.io.; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.mail.; import javax.mail.internet.; import javax.mail.search.; import javax.activation.; public class fetchMail { public void fetch(String username, String pass, String search){ MessagesTableModel tableModel = new MessagesTableModel(); String complete; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); gui gui = new gui(); // SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!! String host = "imap.gmail.com"; // SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!! String user = username; String password = pass; // SUBSTITUTE YOUR SUBJECT SUBSTRING TO SEARCH HERE!!! String subjectSubstringToSearch = search; // Get a session. Use a blank Properties object. Session session = Session.getInstance(new Properties()); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); try { // Get a Store object Store store = session.getStore("imaps"); store.connect(host, user, password); // Get "INBOX" Folder fldr = store.getFolder("INBOX"); fldr.open(Folder.READ_WRITE); int count = fldr.getMessageCount(); System.out.println(count + " total messages"); // Message numebers start at 1 for(int i = 1; i <= count; i++) { // Get a message by its sequence number Message m = fldr.getMessage(i); // Get some headers Date date = m.getSentDate(); int pos = i - 1; String d = df.format(date); Address [] from = m.getFrom(); String subj = m.getSubject(); String mimeType = m.getContentType(); complete = date + "\t" + from[0] + "\t" + subj + "\t" + mimeType; //tableModel.setMessages(m); gui.setDate(d, pos); // System.out.println(d + " " + i); } // Search for e-mails by some subject substring String pattern = subjectSubstringToSearch; SubjectTerm st = new SubjectTerm(pattern); // Get some message references Message [] found = fldr.search(st); System.out.println(found.length + " messages matched Subject pattern \"" + pattern + "\""); for (int i = 0; i < found.length; i++) { Message m = found[i]; // Get some headers Date date = m.getSentDate(); Address [] from = m.getFrom(); String subj = m.getSubject(); String mimeType = m.getContentType(); //System.out.println(date + "\t" + from[0] + "\t" + // subj + "\t" + mimeType); Object o = m.getContent(); if (o instanceof String) { // System.out.println("**This is a String Message**"); // System.out.println((String)o); } else if (o instanceof Multipart) { // System.out.print("**This is a Multipart Message. "); Multipart mp = (Multipart)o; int count3 = mp.getCount(); // System.out.println("It has " + count3 + // " BodyParts in it**"); for (int j = 0; j < count3; j++) { // Part are numbered starting at 0 BodyPart b = mp.getBodyPart(j); String mimeType2 = b.getContentType(); // System.out.println( "BodyPart " + (j + 1) + // " is of MimeType " + mimeType); Object o2 = b.getContent(); if (o2 instanceof String) { // System.out.println("**This is a String BodyPart**"); // System.out.println((String)o2); } else if (o2 instanceof Multipart) { // System.out.print( // "**This BodyPart is a nested Multipart. "); Multipart mp2 = (Multipart)o2; int count2 = mp2.getCount(); // System.out.println("It has " + count2 + // "further BodyParts in it**"); } else if (o2 instanceof InputStream) { // System.out.println( // "**This is an InputStream BodyPart**"); } } //End of for } else if (o instanceof InputStream) { // System.out.println("**This is an InputStream message**"); InputStream is = (InputStream)o; // Assumes character content (not binary images) int c; while ((c = is.read()) != -1) { // System.out.write(c); } } // Uncomment to set "delete" flag on the message //m.setFlag(Flags.Flag.DELETED,true); } //End of for // "true" actually deletes flagged messages from folder fldr.close(true); store.close(); } catch (MessagingException mex) { // Prints all nested (chained) exceptions as well mex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } } } gui: /* * gui.java * * Created on 13-May-2010, 18:29:30 */ package mail; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import javax.mail.Address; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class gui extends javax.swing.JFrame { private MessagesTableModel tableModel; // Table listing messages. private JTable table; String date; /** Creates new form gui */ public gui() { initComponents(); } @SuppressWarnings("unchecked") private void initComponents() { recieve = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); inboxTable = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); recieve.setText("Receve"); recieve.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { recieveActionPerformed(evt); } }); jButton1.setText("new"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); inboxTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Date", "subject", "sender" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(inboxTable); inboxTable.getColumnModel().getColumn(0).setResizable(false); inboxTable.getColumnModel().getColumn(1).setResizable(false); inboxTable.getColumnModel().getColumn(2).setResizable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 558, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(recieve) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(73, 73, 73)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(recieve) .addComponent(jButton1)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(179, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void recieveActionPerformed(java.awt.event.ActionEvent evt) { fetchMail fetch = new fetchMail(); fetch.fetch(email goes here, password goes here, search goes here); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { createMail create = new createMail(); centerW center = new centerW(); //create.attVis(); center.center(create); create.setVisible(true); } public void setDate(String Date, int pos){ //pos = pos + 1; String [] s = new String [5]; s[pos] = Date; inboxTable.setValueAt(Date, pos, 0); } public String getDate(){ return date; } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new gui().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTable inboxTable; private javax.swing.JButton jButton1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton recieve; // End of variables declaration }

    Read the article

1 2  | Next Page >