Return the value from JOptionPane - java

I have made a JOptionPane which contains a JPanel. The panel contains one button and one Jtable.
JPanel p = atomicAttack.getPanel(); //make the panel and return it
JOptionPane.showOptionDialog(null, p,"Atomic Attacks",
JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,
null, new Object[]{}, null);
and inside the JButton i have:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
selectedId=jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString();
}
I need to when the user clicks on the button, the JOption get closed and the selectedId get return from the JOptionPane?
I have seen this, but it is not exactly what i am looking for.
Because the button does not return the value for me.

Focus on the models and things will be easier.
public static void main(String[] args) {
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("Selection", new Object[] { "A", "B", "C" });
JTable table = new JTable(tableModel);
ListSelectionModel selectionModel = table.getSelectionModel();
JPanel p = new JPanel(new BorderLayout());
p.add(table, BorderLayout.CENTER);
int option = JOptionPane.showConfirmDialog(null, p, "Atomic Attacks", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (JOptionPane.OK_OPTION == option) {
printSelection(selectionModel, tableModel);
} else {
selectionModel.clearSelection();
}
}
private static void printSelection(ListSelectionModel selectionModel, TableModel tableModel) {
for (int i = selectionModel.getMinSelectionIndex(); i <= selectionModel.getMaxSelectionIndex(); i++) {
if (selectionModel.isSelectedIndex(i)) {
Object selectedValue = tableModel.getValueAt(i, 0);
System.out.println(selectedValue);
}
}
}
If you now select multiple rows
and press the ok button the result will be
A
C
If you want a single selection you can just set
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Related

Java Resultset to JTable with Checkbox

I have this code to which it can display data from database. It's working well but I want it to have checkbox at last column. I've found some codes here but It's only for pre-defined not values and not from database. (How to add checkboxes to JTABLE swing)
Screenshot:
Code:
public print() {
initComponents();
try{
conn = (Connection) db_connect.connectDB();
}
catch(ClassNotFoundException | SQLException ex){
JOptionPane.showMessageDialog(null, ex);
}
update_table("select name, section, student_number, gender from students");
}
public void update_table(String q){
try{
st= conn.createStatement();
st.executeQuery(q);
ResultSet rs = st.executeQuery(q);
users_list.setModel(DbUtils.resultSetToTableModel(rs));
users_list.getColumnModel().getColumn(0).setPreferredWidth(250);
users_list.getColumnModel().getColumn(0).setPreferredWidth(250);
users_list.getColumnModel().getColumn(1).setPreferredWidth(150);
users_list.getColumnModel().getColumn(2).setPreferredWidth(120);
users_list.getColumnModel().getColumn(3).setPreferredWidth(100);
int count= users_list.getModel().getRowCount();
if(count==0){
no_results_found.setVisible(true);
}
else{
no_results_found.setVisible(false);
}
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex);
}
}
You can try something like this:
public class JTableWithCheckBox {
private JFrame mainFrame;
private JTable studentTable;
private JScrollPane scrollPaneTable;
private DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ "Ramesh", "Male" }, { "Sheela", "Female" },
{ "Amithabh", "Male" }, { "Katrina", "Female" } }, new Object[] {
"Name", "Gender" });
public static void main(String[] args) {
final JTableWithCheckBox ui = new JTableWithCheckBox();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ui.initGUI();
}
});
}
private void initGUI() {
mainFrame = new JFrame("View");
mainFrame.getContentPane().setLayout(new BorderLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(300, 200);
mainFrame.setVisible(true);
mainFrame.setLocationRelativeTo(null);
studentTable = new JTable(model);
studentTable.getColumnModel().getColumn(1)
.setCellRenderer(new MFCheckBox());
scrollPaneTable = new JScrollPane(studentTable);
mainFrame.add(scrollPaneTable, BorderLayout.NORTH);
}
private class MFCheckBox implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
JPanel cbPanel = new JPanel();
JCheckBox maleBox = new JCheckBox("Male");
JCheckBox femaleBox = new JCheckBox("Female");
cbPanel.setLayout(new BorderLayout());
cbPanel.add(maleBox, BorderLayout.WEST);
cbPanel.add(femaleBox, BorderLayout.EAST);
if (value != null) {
if (value instanceof String) {
String valStr = (String) value;
switch (valStr) {
case "Male":
maleBox.setSelected(true);
femaleBox.setSelected(false);
break;
case "Female":
maleBox.setSelected(false);
femaleBox.setSelected(true);
break;
default:
maleBox.setSelected(false);
femaleBox.setSelected(false);
break;
}
}
}
return cbPanel;
}
}
}
If you also want checkbox editable, you will have to set TableCellEditor as well.
The easiest way is to NOT use DBUtils and to load the data from the ResultSet into the TableModel` yourself.
The code is not difficult and you can use the Table From Database Example found in Table From Database as the starting point.
The code just loads the data from the ResultSet into Vectors, so you can then manually add another column to contain Boolean data.
The changes to the code would be something like:
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
columnName.addElement( "Check Mark" ); // added
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
row.addElement( Boolean.FALSE ); // added
data.addElement( row );
}
The other option is to create a "wrapper" TableModel that wraps a Boolean column with your DBUtils TableModel. Check out How to add checkbox in Jtable populated using rs2xml for an example of this approach.
That answer places the check box column at the start of the table, so you would need to modify the code to place the check box at the end.

Trouble with listener in Java. I have a drop down box not passing the users selection like I need

I have a project for class due this Wednesday and am having trouble with a few things: I have two if else statements that control the values presented in two different drop down menus. To me, it appears I'm not getting the information of of the previous drop down(there are two drop downs in which affects the values presented in the next).
Here's my code thus far:
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
int number = Integer.parseInt((String) selection);
if(number>2)
{
style=(style2);
}
else
{
style=(style1);
}
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
roomtype_string=(String) room_type.getSelectedItem();
room_type.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Room Style Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection2 = (String) room_type.getSelectedItem();
if(selection2.equals("Cabin"))
{
room_number=(cabin_string);
}
else
{
room_number=(suite_string);
}
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
roomselected = (String) room_list.getSelectedItem();
room_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection3 = (String) room_list.getSelectedItem();
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
dining_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
}
});
String selection4 = (String) dining_list.getSelectedItem();
NOTE: I have since rewritten my code, still no dice:
` //Creates subPanel2 with Occupancy, Room Type, Room, and Dining Time request
JPanel subpanel = new JPanel();
///Occupancy///
JLabel label2 = new JLabel("Please Select the Number of Occupants");
JComboBox occupancy_list = new JComboBox(occupancy_string);
Occupancy_Listener occupancy = new Occupancy_Listener();
occupancy_list.addActionListener(occupancy);
//updateStyle(occupancy_string[occupancy_list.getSelectedIndex()]);
///Room Type///
JLabel label3 = new JLabel("Please Select a Room Style");
//Creates RoomStyle Drop Down
JComboBox room_type = new JComboBox(style);
Style_Listener styleListen = new Style_Listener();
room_type.addActionListener(styleListen);
//updateNumber(style[room_type.getSelectedIndex()]);
///Room Selection///
JLabel label4 = new JLabel("Please Select a Room");
//Creates RoomNumber Drop Down
JComboBox room_list = new JComboBox(room_number);
Room_Listener room = new Room_Listener();
room_list.addActionListener(room);
//updateRoom(room_number[room_list.getSelectedIndex()]);
//Dining
JLabel label5 = new JLabel("Please Select a Dining Time");
JComboBox dining_list = new JComboBox(dining_string);
Din_Listener dining = new Din_Listener();
dining_list.addActionListener(dining);
//updateDin(dining_string[dining_list.getSelectedIndex()]);
...
...
...
...
...
}
private class Occupancy_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
System.out.println(selection);
System.out.println(style[0]);
System.out.println(room_number[0]);
updateStyle(selection);
}
}
private class Style_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateNumber(selection);
}
}
private class Room_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateRoom(selection);
}
}
private class Din_Listener implements ActionListener
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
updateDin(selection);
}
}
protected void updateStyle(String pick)
{
String[] style1 ={"Cabin", "Suite"};
String[] style2 ={"Suite"};
//ocu_string=pick;
number = Integer.parseInt(pick);
if(number>2)
{
style=style2;
}
else
{
style=style1;
}
}
protected void updateNumber(String pick)
{
String[] cabin_string = {"11-1","11-2","11-3","11-4","11-5","11-6","11-7","11-8","11-9","11-10"};
String[] suite_string = {"11-S1","11-S2"};
type=pick;
if(type.equals("cabin"))
{
room_number=cabin_string;
}
else
{
room_number=suite_string;
}
}
protected void updateRoom(String pick)
{
room_num=pick;
}
protected void updateDin(String pick)
{
din_time=pick;
}
//public String getPopulation()
{
//return ocu_string;
}
This might be what your are asking. You select an item from the first combo box and it populates items in a second combo box:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JPanel implements ActionListener
{
private JComboBox<String> mainComboBox;
private JComboBox<String> subComboBox;
private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox<String>( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
add( mainComboBox );
// Create sub combo box with multiple models
subComboBox = new JComboBox<String>();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
add( subComboBox );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ComboBoxTwo() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You may be confused by the fact that code inside anonymous classes (or local classes) is not executed at the same time as the code around it.
So in a code that looks like:
A a = new A();
a.setSomething( new B() {
public void bMethod() {
// Run stuff
}
} );
C c = a.getSomething();
The "Run stuff" part is not ran now. An object is created, with a method that can be used later inside it, and that object is passed into a. The method is not going to run until something specifically calls it. When you get to the getSomething(), the "Run stuff" part has not run.
So in your code:
JComboBox occupancy_list = new JComboBox(occupancy_string);
occupancy_list.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)//Listener for Occupancy Drop Down
{
JComboBox cb = (JComboBox)event.getSource(); //grab the user selection
String selection = (String) cb.getSelectedItem();
int number = Integer.parseInt((String) selection);
}
});
String selection = (String) occupancy_list.getSelectedItem();
You create the occupancy list, you create an action listener for it, and store that action listener inside your occupancy list. But none of the stuff written inside the actionPerformed() method is going to run until the GUI is displayed, the user selects something, and the event is fired.
GUI programming is different than console programming where you call "scan()" and then the program just stops and waits for something to be entered. You first prepare the GUI, and when you display it, the various listeners are called based on what the user does.
So your code jumps straight to the occupancy_list.getSelectedItem() before the list has even been added to the GUI, and of course, nothing is selected, nothing is displayed, yet, so the other drop-down lists are created way before the user even sees the GUI.
This is true for all the action listeners in the code.
The proper way to write an action listener is to think what will be the conditions when the GUI is already running. Your action listeners merely set values in local variables that are going to be discarded. Instead, they should do the things that you want to do when the user makes a selection, right inside the action listener.
This means that the action listener for this combo box will have to create the other lists and add them to the GUI, revalidate and repaint it. Or it may simply modify the other lists which will be created already, depending on what you think is best. But they will have to access those lists, and therefore the lists have to be defined as fields of the surrounding class, and accessed inside the action listener. Note that you can also define a method that does this and call it from inside the action listener.
My suggestion would be to create a simple GUI first with just the first combo box and make it change something simple based on the selection. You can follow the Oracle Tutorial, for example. After you understand how to write an action listener that changes something simple, expand your program to add the other lists and manipulate them from the action listener.

Getting a row of names from the first column of JTable

I have a JTable with the column names " Names " , " Quantity " and " Unit " .
I'm coding a program where you get the ingredients names.
So i need to get the whole row of one column and String it all up together,
because i need to store it in mySql and i have already set it all as String.
Any idea how i can do this ?
My code are as follows :
JTable Code:
DefaultTableModel model = (DefaultTableModel)table.getModel();
if(!txtQty.getText().trim().equals("")){
model.addRow(new Object[]{ingCB.getSelectedItem().toString(),txtQty.getText(),unitCB.getSelectedItem().toString()});
}else{
JOptionPane.showMessageDialog(null,"*Quantity field left blank");
}
Getting the values and for storing :
for(int i = 1; i<= i ; i++){
ingredients = table.getName();
}
This is for loop is wrong and it does not work because i have a constructor to take in Ingredients but because it is inside the loop, it cannot take it in.
Any suggestions please ? Thank you.
Constructor :
Food e2 = new Food(Name, Description, priceDbl, Image, Category, Ingredients, promotion );
e2.createFood();
I'm coding a program where you get the ingredients names. So i need to get the whole row of one column and String it all up together, because i need to store it in mySql and i have already set it all as String.
Want to do so, try this. Here I am getting result into ArrayList and String, as I am commented ArrayList you can avoid it.
public class TableValuePrint extends JFrame implements ActionListener{
private final JButton print;
private final JTable table;
private String str="";
public TableValuePrint() {
setSize(600, 300);
String[] columnNames = {"A", "B", "C"};
Object[][] data = {
{"Moni", "adsad", "Pass"},
{"Jhon", "ewrewr", "Fail"},
{"Max", "zxczxc", "Pass"}
};
table = new JTable(data, columnNames);
JScrollPane tableSP = new JScrollPane(table);
JPanel tablePanel = new JPanel();
tablePanel.add(tableSP);
tablePanel.setBackground(Color.red);
add(tablePanel);
setTitle("Result");
setSize(1000,700);
print=new JButton("Print");
JPanel jpi1 = new JPanel();
jpi1.add(print);
tablePanel.add(jpi1,BorderLayout.SOUTH);
print.addActionListener(this);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableValuePrint ex = new TableValuePrint();
ex.setVisible(true);
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==print){
// ArrayList list = new ArrayList();
for(int i = 0;i<table.getModel().getRowCount();i++)
{
//list.add(table.getModel().getValueAt(i, 0)); //get the all row values at column index 1
str=str+table.getModel().getValueAt(i,0).toString();
}
//System.out.println("List="+list);
System.out.println("String="+str);
}
}
}
Output
String=MoniJhonMax

JTable (BeanTableModel) not updating/refreshing - Java Swing

I've 2 panels. One where the user inserts the data and the other with a JTable where the results will be shown.
My problem is when the user press's the ok (in my case apply) JButton the data is computed but is not shown on the JTable, nothing changes in the JTable.
For my JTable I'm using the Bean Table Model from tips4Java (http://tips4java.wordpress.com/2008/11/27/bean-table-model/).
One weird thing is if I send data (lets call this data 'A') to the table when the program starts it is shown on the table and if later on I try to update the table, the table does not update. But when I don't send data to the table at start up but try to update/send the table with data 'A' it does not update.
So my question is, why is not the JTable showing whatever data I send to?
Here's my code:
JButton listenere that starts the processing and sends the data to the table:
crashForm.setFormListener(new FormListener() {
#Override
public void formEvent(OptionsFormEvent oe) {
String readTable = oe.getReadFromTable();
int access = oe.getAccess();
int transition = oe.getTransition();
boolean smooth = oe.isTrainCrash();
ArrayList<String> allTrains = new ArrayList<>();
List crashedTrainList = new ArrayList<>();
try {
allTrains = controller.getUniqueTrains(controller.connectServer(), readTable, "trainid");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "An error occured while getting trains data\n"
+ "Error description: " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
try {
for (int i = 0; i < allTrains.size(); i++)
{
ArrayList<Train> trainDataList = new ArrayList<>();
ArrayList<Train> crashedProccessedData = new ArrayList<>();
String query = "the sql query...";
trainDataList = controller.getTrainData(controller.connectServer(), readTable, query);
crashedProccessedData = controller.detectCrash(access, transition, trainDataList);
crashedTrainList.addAll(crashedProccessedData);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "An error occured while detecting a crash.\n"
+ "Error description: " + ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
System.out.println("Total crashes detected:" + crashedTrainList.size());
tablePanel.createTable(Train.class, crashedTrainList, true, false, tableLabels);
tablePanel.fireTableDataChanged();
}
});
}
And here's my tablePanel class:
public TablePanel() {
}
public void createTable(Class c, List data, boolean toolBarUp,
boolean toolBarBottom, ArrayList<String> labelsCheckBox) {
beanTableModel = new BeanTableModel(c, data);
columnModel = new XTableColumnModel();
table = new JTable(beanTableModel);
table.setColumnModel(columnModel);
table.createDefaultColumnsFromModel();
if(toolBarUp == true)
{
final JToolBar toolBarTop = new JToolBar();
// Create the Show ALL
JButton reset = new JButton("Reset");
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Component c : toolBarTop.getComponents()){
if(c instanceof JCheckBox){
JCheckBox checkBox = (JCheckBox) c;
checkBox.setSelected(false);
columnModel.setAllColumnsVisible();
}
}
int numberOfColumn = columnModel.getColumnCount();
for(int aux = 0; aux < numberOfColumn; aux++)
{
int num = columnModel.getColumnCount();
TableColumn column = columnModel.getColumnByModelIndex(aux);
columnModel.setColumnVisible(column, true);
}
}
});
toolBarTop.add(reset);
// Create a JCheckBox for each column
for(int i = 0; i < labelsCheckBox.size(); i++)
{
final int index = i;
toolBarTop.add(new JCheckBox(new AbstractAction(labelsCheckBox.get(i)) {
#Override
public void actionPerformed(ActionEvent e) {
TableColumn column = columnModel.getColumnByModelIndex(index);
boolean visible = columnModel.isColumnVisible(column);
columnModel.setColumnVisible(column, !visible);
}
}));
}
setLayout(new BorderLayout());
add(toolBarTop, BorderLayout.NORTH);
add(new JScrollPane(table), BorderLayout.CENTER);
// add(toolBarDown, BorderLayout.SOUTH);
}
final JToolBar toolBarDown = new JToolBar();
toolBarDown.add(new JButton(new AbstractAction("Save Table") {
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}));
}
public void createTable(Class c, Class cAncestor) {
beanTableModel = new BeanTableModel(c, cAncestor);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
public void createTable(Class c, Class cAncestor, List data) {
beanTableModel = new BeanTableModel(c, cAncestor, data);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
beanTableModel.fireTableDataChanged();
}
public void createTable(Class c) {
beanTableModel = new BeanTableModel(c);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
public void createTable(Class c, List data)
{
beanTableModel = new BeanTableModel(c, data);
table = new JTable(beanTableModel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
}
//to refresh the table everytime there is an update
public void fireTableDataChanged()
{
beanTableModel.fireTableDataChanged();
}
So again, my question is: Isn't my JTable not updated with the new results every time I send new data to it?
You should never invoke fireTableDataChanged manually. Only the TableModel is responsible for invoking this event.
From your code it looks like you are creating a new TableModel, JTable and JScrollPane every time you make a change. Any time you add a component to a visible GUI the basic code should be:
panel.add(....);
panel.revalidate();
panel.repaint();
By default all components have a size of zero so since you don't invoke revalidate() then never get a proper size and there is nothing to paint. Also, it is never a good idea to simply keep adding components to the CENTER of your panel since the old component are still part of the container.
However, there is a better solution. There is no need to keep creating new components. All you need to do is create an new TableModel and then use:
table.setModel( newlyCreatedModel );
and the model will be added to the table and the table will repaint itself automatically.

drop down list within JTextField

I wnt that when i enter some letter in the textfield then the related items should be picked up from my database and should appear as a drop down list.
For Example:
I typed 'J' in text Field, in my database is having names such as {"Juby','Jaz','Jasmine','Joggy'....}
Theses names should appear as a list. So that i could select one from them.and so on for other leters as well.
Is there any predefined control in awt??
Thnx
Why not just use a JComboBox? By default, when the user types a keystroke in a read-only combobox and an item in the combobox starts with the typed keystroke, the combobox will select that item.
Or you could set the JComboBox to be editable using setEditable(true), and use a KeySelectionManager. The link explains selecting an item in a JComboBox component with multiple keystrokes.
This is a small example implementing what ( i think) you asked for.. the database in this example is a vector of strings.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Answer extends JFrame {
public static final int MAXITEMS = 100;
JPanel panel = new JPanel();
JTextField textField = new JTextField(10);
String[] myDataBase = { "Juby", "Jaz", "Jasmine", "Joggy", "one", "dog","cat", "parot" };
String[] listItems;
JList theList = new JList();
public Answer() {
this.add(panel);
panel.setPreferredSize(new Dimension(500, 300));
panel.add(textField);
panel.add(theList);
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ke) {
String compareString = ("" + textField.getText() + ke.getKeyChar());
listItems = new String[MAXITEMS];
if (compareString.trim().length() > 0 ){
int counter = 0;
for (int i = 0; i < myDataBase.length; i++) {
if (counter < MAXITEMS) {
if (myDataBase[i].length() >= compareString.length() &&
myDataBase[i].substring(0, compareString.length()).equalsIgnoreCase(compareString)) {
listItems[counter] = myDataBase[i];
counter++;
}
}
}
}
theList.setListData(listItems);
}
});
}
public static void main(String[] args) {
final Answer answer = new Answer();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
answer.pack();
answer.setVisible(true);
}
});
}
}
One option is to use GlazedLists, as it has some support for auto-completion.

Categories