search result in a JTable - java

I have a program that allows the user to do a search in the warehouse. The result is returned in a JTable.
So far everything is good. When I attempt to do a second search, the old table is still showing.
Image:
Code:
public void panelTable(){
panelTable= new JPanel();
panelTable.setSize(400, 80);
panelTable.setOpaque(true);
panelTab = new JTable();
modele = new DefaultTableModel();
}
public void creerJTable(List<Pneu> liste){
String[] head= {"A", "B", "C"};
Object[][] data = null;
data = new Object[liste.size()][3];
Iterator<Pneu> it = liste.iterator();
int index = 0;
while(it.hasNext()){
Pneu unPneu = it.next();
data[index][0] = unPneu.descrip();
data[index][1] = unPneu.width();
data[index][2] = unPneu.height();
index++;
}
modele.setDataVector(data, head);
panelTab.setModel(modele);
panelTab.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
panelTab.setFillsViewportHeight(true);
panelTab.setPreferredScrollableViewportSize(new Dimension(500, 80));
panelTab.setModel(modeleColonnesNoEdit(data, entete));
panelTab.setRowSelectionInterval(0, 0);
panelTab.getColumnModel().getColumn(0).setPreferredWidth(250);
panelTab.getColumnModel().getColumn(1).setResizable(false);
panelTab.getColumnModel().getColumn(1).setPreferredWidth(50);
panelTab.getColumnModel().getColumn(2).setResizable(false);
panelTab.getColumnModel().getColumn(2).setPreferredWidth(50);
JScrollPane scrollPane = new JScrollPane(panelTab);
scrollPane.setPreferredSize(new Dimension(500, 60));
panelTable.add(scrollPane);
}
When clicking on the search button, you are taken to the class Listener which verifies that the button search was clicked. Once that is done, you have this code:
frame.creerJTable(liste);
This line of code, takes the list created from that search and calls the method creerJTable(List liste) that is shown in the above code.
Here's the code for the modeleColonnesNoEdit()
private DefaultTableModel modeleColonnesNoEdit(Object[][] data, String[] head) {
return new DefaultTableModel(data, head)
{
boolean[] columnEditables = new boolean[] { false, false, false};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
};
}

You should not be re-adding a JScrollPane or adding any new components to the GUI in the search. Instead, take the original JTable, simply change its TableModel, and that's it, do nothing more.

Related

Issue filling a JTable with a List<nftDTO>

I'm filling a JTable with a List of 68 nftDTO objects but the model paint only 48 nftDTO objects and I need to paint all of them. I paste the code:
private JTable setNftTable() {
List<NftDTO> nfts = mainWindow.getPeticiones().obtainNftAccount(user.getErd());
String[] columsName = new String[] { "Nu.","Name", "Collection name", "royalties", "website" };
DefaultTableModel model = new DefaultTableModel(4, columsName.length);
model.setColumnIdentifiers(columsName);
for (NftDTO nft : nfts) {
System.out.println(nft.getNftUrl());
if(nft.getNftUrl()==null) {
nft.setNftUrl("there is no URL");
}
model.addRow(
new Object[] { countNft(), nft.getNftName(), nft.getColletionName(), nft.getRoyalties(), nft.getNftUrl() });
}
model.removeRow(0);
model.removeRow(1);
nftTable = new JTable(model);
nftTable.setPreferredSize(new Dimension(500, 800));
return nftTable;
}
I paste by the way the list i receive and the painting of the method
The list I recieve,
the painting result
Any suggestion on how can I put all the objects on the JTable?

Unable to show JTable in JPanel from dynamically retrieved data

I haven't been able to show a JTable inside a JPanel from dynamically generated data. I have even tried adding a layout manager so that I don't end up with a null layout manager and no table. Here is the code I'm using.
public void setReferencePanel(ArrayList<Item> items, String refFile) {
String[] columns = {"first", "last"};
String[][] data = {{"Adam", "Smith"}, {"Jon", "Bon Jovi"},{"John", "Doe"}};
JTable sample = new JTable(data, columns);
refListingPanel.add(sample);
refListingPanel.setBorder(BorderFactory.createTitledBorder("Reference File - " + refFile));
}
and earlier in the same file.
private JMenuBar menuBar;
private JPanel testListingPanel;
private JScrollPane testScroller;
private JPanel refListingPanel;
private JScrollPane refScroller;
private static Dimension listingDefault = new Dimension(350, 230);
private IDiffPresenter presenter;
private boolean allItems;
private boolean unChangedItems;
private boolean changedItems;
private JTable refTable;
private JTable testTable;
public MasterFrame (IDiffPresenter presenter) {
super("Magic Diff - Under Construction");
this.presenter = presenter;
menuBar = new JMenuBar();
setupFileMenu(presenter);
setupExportMenu(presenter);
setupDisplayChangedMenu();
setupAboutMenu();
setupReferencePanel();
setupTestPanel();
getContentPane().setLayout(new GridLayout(1,2));
setJMenuBar(menuBar);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize((int)listingDefault.getWidth() + 10, (int)listingDefault.getHeight() + 60);
Dimension DimMax = Toolkit.getDefaultToolkit().getScreenSize();
this.setMaximumSize(DimMax);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
...
}
private void setupReferencePanel() {
refListingPanel = new JPanel();
refListingPanel.setLayout(new BorderLayout());
refListingPanel.setBorder(BorderFactory.createTitledBorder("Reference File"));
refScroller = new JScrollPane(refListingPanel);
getContentPane().add(refScroller);
}
What am I missing or failing to do? I have even tried some sample data, what is currently in the code, and I get the same issue.
This is based on what cmickr and Andrew Thompson posted. I modified the following functions to work.
public void setReferencePanel(ArrayList<Item> items, String refFile) {
DefaultTableModel model = new DefaultTableModel(vectorize(items), makeHeaderVector());
refTable.setModel(model);
refListingPanel.setBorder(BorderFactory.createTitledBorder("Reference File - " + refFile));
}
private Vector vectorize(ArrayList<Item> items) {
Vector results = new Vector();
for (int i = 0; i < items.size(); i++) {
results.addElement(items.get(i).vectorize());
}
return results;
}
private Vector makeHeaderVector() {
String[] cols = { ... }; // hid application specific string array
Vector<String> results = new Vector<String>(Arrays.asList(cols));
return results;
}
This is my basic understanding of vectors, since I do not use them much. Also, this may not be the fastest way of approaching the problem, but my first goal is to get it working, then improve it. The important part was to use a TableModel, in my case DefaultTableModel, and then setModel() of the the JTable to the new model, like was referenced.

How to change selected index in JComboBox when refreshing panel?

I am making a simple sudoku and when I want to start a new game, I reload the panel. I first remove it and then add it to the frame. The problem is that I can choose the difficulty for new game, but it always selects the first "Easy" dificulty, not selected. So if I change it in JComboBox to "medium", when page is reloaded it will load the game with "Easy", not "medium".
What should I do so my refreshed panel will accept changed difficulty?
Here are methods that are used for this in my program:
JComboBox difficulty = new JComboBox();
DefaultComboBoxModel difficultyModel = new DefaultComboBoxModel();
difficultyModel.addElement("Easy");
difficultyModel.addElement("Medium");
difficultyModel.addElement("Hard");
difficulty.setModel(tezavnostModel);
difficulty.setSelectedIndex(0);
difficulty.setPreferredSize(new Dimension(100, 25));
newGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainFrame.reloadSudokuBoard();
sudokuBoard.pickDifficulty(getDifficulty()));
}
});
public String getDifficulty() {
return (String)difficulty.getSelectedItem();
}
public void board(int[][] numbers, int zeros) {
int numberZeros = setDifficulty(sudokuForm.getDifficulty());
int[][] boardNumbers = gameNumbers();
public void reloadSudokuBoard() {
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
}
Hope this helps.
public void reloadSudokuBoard() {
int index = difficulty.getSelectedIndex();
String newDifficulty = (sudokuForm.getDifficulty());
remove(sudokuBoard);
sudokuBoard.board(sudokuBoard.gameNumbers(), sudokuBoard.setDifficulty(newDifficulty ));
add(sudokuBoard, BorderLayout.WEST);
SwingUtilities.updateComponentTreeUI(sudokuBoard);
difficulty.setSelectedIndex(index);
}
Before removing components, you can use the getSelectedIndex to get the index that was selected. After the element have been added, the setSelectedIndex will fix it

Java jTable color row on defined cell change

Hi all I am not finding what's incorrect about my code below. It populates the table and headers just fine. However, when I change row 1, colum 1 to test and click off it does not color the row like I was expecting. Then clicking off the one I clicked on turns green and anywhere I click on the table from then on just changes green.
The column won't change from 1 (Company) as that will be the default column which changes will be made. The row is the only dynamic number here.
The flow to test:
double-click IBM.
type in test.
click on any another cell in order to save that cell value.
the row does not change (row 1).
click on the test cell again.
all rows will change to the green color.
The Expected flow:
double-click IBM.
type in test.
click on any another cell in order to save that cell value.
the cell that was changed to test changes that row green.
click on Shares for cell (3, 3).
double-click and change 4000 to 1000.
click on any another cell in order to save that cell value.
the cell that was changed to 1000 changes that row red.
Populated the table and headers:
Clicking and changing the row 1, column 1 value to test:
Clicking off that cell onto another one after edit:
And now, click on any other cell (notice the test row is not green as it should be):
Now clicking on the cell I edited to test:
And you see above it's just coloring each row I click on regardless of the logic I said
if ("test".equals(type)) {....
The java code:
#SuppressWarnings("serial")
public class TableRowRenderingTip extends JPanel {
public TableRowRenderingTip() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data =
{
{"Buy", "IBM", new Integer(1000), new Double(80.5), Boolean.TRUE},
{"Sell", "Dell", new Integer(2000), new Double(6.25), Boolean.FALSE},
{"Short Sell", "Apple", new Integer(3000), new Double(7.35), Boolean.TRUE},
{"Buy", "MicroSoft", new Integer(4000), new Double(27.50), Boolean.FALSE},
{"Short Sell", "Cisco", new Integer(5000), new Double(20), Boolean.TRUE}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
#SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int column) {
return getValueAt(1, column).getClass();
}
};
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Border", createBorder(model));
add(tabbedPane);
}
private JComponent createBorder(DefaultTableModel model) {
JTable table = new JTable(model) {
private Border outside = new MatteBorder(1, 0, 1, 0, Color.RED);
private Border _outside = new MatteBorder(1, 0, 1, 0, Color.GREEN);
private Border inside = new EmptyBorder(0, 1, 0, 1);
private Border highlight = new CompoundBorder(outside, inside);
private Border _highlight = new CompoundBorder(_outside, inside);
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
JComponent jc = (JComponent)c;
String type = (String)getModel().getValueAt(convertRowIndexToModel(row), 1);
if (isRowSelected(row)) {
if ("test".equals(type)) {
jc.setBorder( _highlight ); // Green color
jc.setBackground(Color.GREEN);
} else {
jc.setBorder( highlight ); //Red color
}
}
return c;
}
};
//table.setPreferredScrollableViewportSize(table.getPreferredSize());
//table.changeSelection(0, 0, false, false);
return new JScrollPane( table );
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Table Row Rendering");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableRowRenderingTip() );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
So needless to say I am a little frustrated to say the lest since I've been working on this for a few hours now trying to find out what could be the issue.
I'm sure it will be something simple that I'm looking over...
You're forgetting to set the border and highlighting back to default if the test condition is not true. For example
if (isRowSelected(row)) {
if ("test".equals(type)) {
jc.setBorder(_highlight); // Green color
jc.setBackground(Color.GREEN);
} else {
jc.setBorder(highlight); // Red color
}
} else {
jc.setBorder(null);
jc.setBackground(null);
}

Dispose_on_Close closes JFrame but it is still active

I am writing a program where I need to open a JFrame if a button is clicked. I set the default close operation to Dispose_on_close so that when I close the window the program doesn't shutdown completely.
In the frame that will be opened, i want to put a JTable, so I wrote two methods, a createFrame() method and a mechanicListTableProperties() which is the method that creates the JTable and adds elements to it. I then call the mechanicListTableProperties inside the createFrame() and the createFrame inside the actionPerformed() method. When I open the frame 1 time, the table is shown inside the window, but if I close and reopen the frame, the table is also readded and I see 2 tables, when I am trying to just see the one table again. Here is my source code:
public class SeeMechanicsButtonHandler implements ActionListener {
JFrame mechanicListFrame;
boolean isOpen = false;
JTable mechanicListTable;
JPanel tablePanel = new JPanel(new GridLayout());
JScrollPane sp;
List<String> names = new ArrayList<String>();
String[] namesArray;
public void createFrame() {
mechanicListFrame = new JFrame();
mechanicListFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
mechanicListFrame.setSize(new Dimension(500,500));
mechanicListFrame.add(tablePanel);
mechanicListFrame.setVisible(true);
//Prevents the window from being opened multiple times
mechanicListFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
isOpen = false;
}
});
}
public void mechanicListTableProperties(){
mechanicListTable = new JTable(){
public boolean isCellEditable(int row, int column) {
return false;
}
};
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Nome", namesArray);
//Creates a column with title as Nome and lines as the array
mechanicListTable.setModel(model); //adds column to the the table
mechanicListTable.setBounds(30, 40, 200, 300); //table size
mechanicListTable.setFont(new Font("Arial Rounded MT", Font.BOLD, 15));
// adding it to JScrollPane
sp = new JScrollPane(mechanicListTable);
tablePanel.add(sp);
}
public void actionPerformed(ActionEvent e) {
if(!isOpen) {
try {
//SQL code to get the data from mechanics table
ResultSet rs = ServerConnection.createQueryStatement("SELECT * FROM mechanics");
while (rs.next()){
//loop to add each entry in the table to an array list
names.add(rs.getString("nome"));
}
//creates an array to put the values from the arraylist
namesArray = new String[names.size()];
for (int iterate = 0; iterate < names.size(); iterate++){
//loop that iterates through the arraylist and puts the values in the array
namesArray[iterate] = names.get(iterate);
System.out.println(namesArray[iterate]);
//prints to the console for testing purposes
}
} catch (SQLException e1) {
e1.printStackTrace();
}
createFrame();
isOpen = true;
}
}
}

Categories

Resources