How do I show a new Jframe when clicked on a button - java

I just want to go from one frame to the other.
I made a list where you could choose from and then when you would click the button confirm it should show a different window. Sadly it doens't.
This is the class from my first Jframe, so my first window with that confirm button:
package view;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.jgoodies.forms.factories.DefaultComponentFactory;
public class Scherm1pursco extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Scherm1pursco frame = new Scherm1pursco();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Scherm1pursco() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblSelectCategory = DefaultComponentFactory.getInstance()
.createTitle("Select Category");
lblSelectCategory.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSelectCategory.setBounds(141, 49, 149, 16);
contentPane.add(lblSelectCategory);
ArrayList<String> purposeCategories = new ArrayList<String>();
purposeCategories.add("Behavioral");
purposeCategories.add("Structural");
purposeCategories.add("Creational");
JList list_purpose = new JList(purposeCategories.toArray());
list_purpose
.setToolTipText("Choose at least one categorie of purpose.");
list_purpose.setBounds(50, 121, 121, 63);
contentPane.add(list_purpose);
ArrayList<String> scopeCategories = new ArrayList<String>();
scopeCategories.add("Class");
scopeCategories.add("Object");
JList list_Scope = new JList(scopeCategories.toArray());
list_Scope.setToolTipText("Choose at least one categorie of Scope");
list_Scope.setBounds(244, 121, 121, 63);
contentPane.add(list_Scope);
JLabel lblPurpose = new JLabel("Purpose categories:");
lblPurpose.setBounds(50, 92, 121, 16);
contentPane.add(lblPurpose);
JLabel lblScopCategories = new JLabel("Scope categories:");
lblScopCategories.setBounds(244, 92, 121, 16);
contentPane.add(lblScopCategories);
Button button = new Button("Confirm>>");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Structural"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);;
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Behavioral"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Creational"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Object")
&& (list_purpose.getSelectedValue()
.equals("Structural"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Object")
&& (list_purpose.getSelectedValue()
.equals("Creational"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals("Class")
&& (list_purpose.getSelectedValue()
.equals("Behavioral"))) {
Scherm2FilterdPatterns S2FP = new Scherm2FilterdPatterns();
S2FP.setVisible(true);
} else {
System.out.println("error");
}
if (list_Scope.getSelectedValue().equals(null)
&& (list_purpose.getSelectedValue()
.equals(null))) {
System.out.println("error");
}
}
});
button.setBounds(169, 203, 79, 24);
contentPane.add(button);
}
}
This is my second Jframe, this the class where it should be referred to:
package view;
import java.awt.Dimension;
import javax.swing.BoxLayout;
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.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
public class Scherm2FilterdPatterns extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
private boolean DEBUG = false;
private JTextField filterText;
private JTextField statusText;
private TableRowSorter<MyTableModel> sorter;
/**
* Launch the application.
*/
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
/**
* Create the frame.
*/
public Scherm2FilterdPatterns() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// Create a table with a sorter.
MyTableModel model = new MyTableModel();
sorter = new TableRowSorter<MyTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
// For the purposes of this example, better to have a single
// selection.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// When selection changes, provide user with row numbers for
// both view and model.
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
int viewRow = table.getSelectedRow();
if (viewRow == 0) {
// Selection got filtered away.
statusText.setText("Diagram is");
} else {
System.out.print("THIS IS THE SOLUTION");
if (viewRow == 1) {
statusText.setText("diagram2 is");
} else {
int modelRow = table
.convertRowIndexToModel(viewRow);
statusText.setText(String.format("poep",
viewRow, modelRow));
if (viewRow == 2) {
statusText.setText("diagram3 is");
} else {
System.out.println("THIS IS THE SOLUTION");
}
}
}
}
});
// Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
// Add the scroll pane to this panel.
add(scrollPane);
// Create a separate form for filterText and statusText
JPanel form = new JPanel(new SpringLayout());
JLabel l1 = new JLabel("Filter on problem or consequences:",
SwingConstants.TRAILING);
form.add(l1);
filterText = new JTextField();
// Whenever filterText changes, invoke newFilter.
filterText.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
newFilter();
}
public void insertUpdate(DocumentEvent e) {
newFilter();
}
public void removeUpdate(DocumentEvent e) {
newFilter();
}
});
l1.setLabelFor(filterText);
form.add(filterText);
JLabel l2 = new JLabel("Select pattern for more info:",
SwingConstants.TRAILING);
form.add(l2);
statusText = new JTextField();
l2.setLabelFor(statusText);
form.add(statusText);
SpringUtilities.makeCompactGrid(form, 2, 2, 6, 6, 6, 6);
add(form);
}
/**
* Update the row filter regular expression from the expression in the text
* box.
*/
// filter on problem and consequences
private void newFilter() {
RowFilter<MyTableModel, Object> rf = null;
// If current expression doesn't parse, don't update.
try {
rf = RowFilter.regexFilter(filterText.getText(), 1, 2);
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(rf);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = { "Pattern Name:", "Problem",
"Consequences", };
private Object[][] data = { { "Interpreter", "Smith", "Snowboarding" },
{ "Template Method", "Doe", "Rowing" },
{ "Chain of Responsibility", "Black", "Knitting", },
{ "Command", "White", "Speed reading", },
{ "Iterator", "Brown", "Pool" },
{ "Mediator", "Brown", "Pool", },
{ "Memento", "Brown", "Pool", },
{ "Observer", "Brown", "Pool", },
{ "State", "Brown", "Pool", },
{ "Strategy", "Brown", "Pool", },
{ "Visitor", "Brown", "Pool", }, };
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/ editor for
* each cell. If we didn't implement this method, then the last column
* would contain text ("true"/"false"), rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's editable.
*/
public boolean isCellEditable(int row, int col) {
// Note that the data/cell address is constant,
// no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's data can
* change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value + " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i = 0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j = 0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Filterd Patterns");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
TableFilterDemo newContentPane = new TableFilterDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
// Display the window.
frame.pack();
frame.setVisible(true);
}
}
I am really stuck here, please help! Thank you for your time:) Sorry for my English

Your code seems too broad and unnecessary to demonstrate whereas the minimal code needed is very small.
Even then, I'm writing a brief answer to your question. Considering that you have to exit jframe1 and move to jframe2, In the action performed event of confirm button, just add the following lines :-
public static void jButton1 ActionPerformed......{
jFrame1.dispose();
jFrame2.setVisible(true);
}

Related

Edit selected item in JComboBox

My goal is to create a list with a length controlled by another component where each item's value can be edited.
My attempt uses an editable JComboBox that has a certain number of elements. In my code below, however, the selected index keeps changing to -1, which does not allow me to modify the item. Is there a way to select and edit an item using JComboBox?
//cb is a JComboBox with elements of type ComboItem. idx is defined elsewhere.
cb.addItemListener(new ItemListener() {
#SuppressWarnings("unchecked")
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
idx = ((JComboBox<ComboItem>) e.getSource()).getSelectedIndex();
System.out.println("idx:"+idx);
}
});
//Pressing enter should commit changes.
cb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER) {
String parse = ((JTextComponent) cb.getEditor().getEditorComponent()).getText();
parse = parse.substring(parse.lastIndexOf(":")+1).replaceAll("[^0-9]+", ""); //Processes edits.
cb.getItemAt(idx).change("Layer "+idx, Integer.parseInt(parse)); //This method should change the
System.out.println("selected item:"+cb.getSelectedItem()); // data for each item.
}
}
});
//Editing the text in the JComboBox and pressing the enter key should update the selected item.
JComboBox is not required, so feel free to suggest a different component if it is a better choice for this task.
After a day's worth of trial and error, I finally made a working solution. Instead of using a JComboBox, which was probably not designed to perform the desired task, I made a JScrollPane that adds a child JPanel every time a button is pressed. Each panel has a text field object that can be customized and a button to delete it. In my case, I added a DocumentFilter that allows positive < 5 digit integers.
I cannot figure out how to remove the spacing between the added panels before the scroll bar appears, so please comment a solution if you have one. Also, if there are any other improvements that can be made, please comment those suggestions as well.
Scroll Panel
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.JLabel;
#SuppressWarnings("serial")
public class TestScrollPane extends JPanel {
private int w,h;
private JPanel content;
private JScrollPane scroll;
private JButton add;
private JLabel getTextLabel;
private JButton getTextBtn;
/**
* Create the panel.
*/
public TestScrollPane(int width, int height) {
setLayout(null);
w = width; h = height;
scroll = new JScrollPane();
scroll.setBounds(0, 0, w, h);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
content = new JPanel();
scroll.setViewportView(content);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
add = new JButton("+");
add.setBounds(0, h, 89, 23);
add(add);
getTextLabel = new JLabel("");
getTextLabel.setBounds(10, 425, 215, 14);
add(getTextLabel);
getTextBtn = new JButton("Get Text");
getTextBtn.setBounds(225, 425, 215, 14);
getTextBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String a[] = getText(),
b = "";
b += "[";
for(int i = 0; i < a.length - 1; i++)
b += a[i]+", ";
b += a[a.length-1]+"]";
System.out.println(b);
getTextLabel.setText(b);
}
});
add(getTextBtn);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("adding "+content.getComponentCount());
content.add(new ScrollItem(content.getComponentCount()));
validate();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
public String[] getText() {
String out[] = new String[content.getComponentCount()],s;
for(int i = 0; i < out.length; i++)
out[i] = (s = ((ScrollItem) content.getComponent(i)).out) == null ? "0" : s;
return out;
}
private class ScrollItem extends JPanel {
private JTextField text;
private JButton del;
private int idx;
private String out;
public ScrollItem(int id) {
idx = id;
setBounds(0, idx*20, w-5, 20);
setLayout(null);
text = new JTextField();
text.setBounds(0, 0, (w-5)*3/4, 20);
text.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
out = text.getText();
}
});
AbstractDocument d = (AbstractDocument) text.getDocument();
d.setDocumentFilter(new TextFilter(4));
del = new JButton("X");
del.setBounds((w-5)*3/4, 0, (w-5)/4, 20);
del.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
content.remove(idx);
for(int i = idx; i < content.getComponentCount(); i++)
((ScrollItem) content.getComponent(i)).moveUp();
content.validate();
content.repaint();
System.out.println("Removed "+idx);
}
});
add(text);
add(del);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w-5, 20);
}
public void moveUp() {
idx--;
content.validate();
content.repaint();
}
}
private class TextFilter extends DocumentFilter {
private int max;
public TextFilter(int maxChars) {
max = maxChars;
}
#Override
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
System.out.println("insert");
if ((fb.getDocument().getLength() + str.length()) <= max && str.matches("\\d+"))
super.insertString(fb, offs, str, a);
else
showError("Length: "+((fb.getDocument().getLength() + str.length()) <= max)+" | Text: "+str.matches("\\d+")+" | Str: "+str);
}
#Override
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
System.out.println("replace");
if ((fb.getDocument().getLength() + str.length() - length) <= max && str.matches("\\d+"))
super.replace(fb, offs, length, str, a);
else
showError("Length: "+((fb.getDocument().getLength() + str.length() - length) <= max)+" | Text: "+str.matches("\\d+")+" | Str: "+str);
}
private void showError(String cause) {
JOptionPane.showMessageDialog(null, cause);
}
}
}
Test Window
import java.awt.EventQueue;
import javax.swing.JFrame;
public class TestWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestWindow window = new TestWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 435, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestScrollPane(430, 247));
}
}

how to set filter combo box for jtable

This is my Jtable code.filter combo box separately working fine. but in jtable when i typed in combo box field that accept only one char as a input and perform filtering.. i can not type more characters or word.
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.Vector;
public class TableRenderDemo extends JPanel {
private boolean DEBUG = false;
private TableRowSorter<MyTableModel> sorter;
FilterComboBox acb;
public TableRenderDemo() {
super(new GridLayout(1,0));
acb = new FilterComboBox(populateArray());
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
//Create a table with a sorter.
/* MyTableModel model = new MyTableModel();
sorter = new TableRowSorter<MyTableModel>(model);
table = new JTable(model);
table.setRowSorter(sorter);
final JTextField textfield = (JTextField) acb.getEditor().getEditorComponent();
RowFilter rowFilter = RowFilter.regexFilter(textfield.getText(), 1);
sorter.setRowFilter(rowFilter);
table.remove();*/
//table.setRowSorter(sorter);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Set up column sizes.
initColumnSizes(table);
//Fiddle with the Sport column's cell editors/renderers.
setUpSportColumn(table, table.getColumnModel().getColumn(2));
//Add the scroll pane to this panel.
add(scrollPane);
}
/*
* This method picks good column sizes.
* If all column heads are wider than the column's cells'
* contents, then you can just use column.sizeWidthToFit().
*/
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel)table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer =
table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(
null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, longValues[i],
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
public static Vector<String> populateArray() {
Vector<String> test = new Vector<String>();
test.add("");
test.add("Mountain Flight");
test.add("Mount Climbing");
test.add("Trekking");
test.add("Rafting");
test.add("Jungle Safari");
test.add("Bungie Jumping");
test.add("Para Gliding");
return test;
}
public void setUpSportColumn(JTable table,
TableColumn sportColumn) {
//Set up the editor for the sport cells.
/* JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
comboBox.setEditable(true);*/
acb = new FilterComboBox(populateArray());
sportColumn.setCellEditor(new DefaultCellEditor(acb));
//Set up tool tips for the sport cells.
/* DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);*/
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Kathy", "Smith",
"", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};
public final Object[] longValues = {"Jane", "Kathy",
"None of the above",
new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
FilterComboBox.java
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class FilterComboBox extends JComboBox {
private List<String> array;
JTextField textfield;
public FilterComboBox(Vector<String> array) {
super(array.toArray());
this.array = array;
this.setEditable(true);
textfield = (JTextField) this.getEditor().getEditorComponent();
textfield.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final String inputTxt=textfield.getText();
comboFilter(inputTxt);
}
});
}
});
}
public void comboFilter(String enteredText) {
if (!this.isPopupVisible()) {
this.showPopup();
}
Vector<String> filterArray= new Vector<String>();
for (int i = 0; i < array.size(); i++) {
if (array.get(i).toLowerCase().contains(enteredText.toLowerCase())) {
filterArray.add(array.get(i));
}
}
System.out.println("val "+enteredText+" size "+filterArray);
if (filterArray.size() > 0) {
DefaultComboBoxModel model = (DefaultComboBoxModel) this.getModel();
model.removeAllElements();
for (String s: filterArray)
model.addElement(s);
textfield.setText(enteredText);
//System.out.println("set txt "+enteredText);
}
else if(filterArray.size()==0)
{
DefaultComboBoxModel model = (DefaultComboBoxModel) this.getModel();
model.removeAllElements();
textfield.setText(enteredText);
// System.out.println("set txt "+enteredText);
}
}
/* Testing Codes */
public static Vector<String> populateArray() {
Vector<String> test = new Vector<String>();
test.add("");
test.add("Mountain Flight");
test.add("Mount Climbing");
test.add("Trekking");
test.add("Rafting");
test.add("Jungle Safari");
test.add("Bungie Jumping");
test.add("Para Gliding");
return test;
}
public static void makeUI() {
JFrame frame = new JFrame("Adventure in Nepal - Combo Filter Test");
FilterComboBox acb = new FilterComboBox(populateArray());
frame.getContentPane().add(acb);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) throws Exception {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
makeUI();
}
}

Get value jtable after filter (jtable on combobox multiple column)

You can copy the search in combobox test run and after the filter selected it still get the original value.
You can see my code and complete the data received after the data filtering help me, more than a week searching but could not do it. hope you help. Thank you very much
Form.java:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
public class Form implements Runnable {
private static JFrame frame;
private static DetailedComboBox combo;
private static JTextField textField;
private static DetailedComboBox comboLop;
private static JTextField textField2;
/**
* #wbp.parser.entryPoint
*/
#Override
public void run() {
// TODO Auto-generated method stub
List<List<?>> tableData = new ArrayList<List<?>>();
tableData.add(new ArrayList<String>(
Arrays.asList("0","Nam", "Phan Nam", "1")));
tableData.add(new ArrayList<String>(
Arrays.asList( "1","Long", "Dinh Hoang Long", "2")));
tableData.add(new ArrayList<String>(
Arrays.asList( "3","Luc", "Phan Cong Luc", "4")));
tableData.add(new ArrayList<String>(
Arrays.asList( "4","Hoang", "Tran Hoang", "5")));
String[] columns = new String[]{"ID","Name", "Full Name", "Capital"};
int[] widths = new int[]{0,80, 200, 100};
combo = new DetailedComboBox(columns, widths, 0);
combo.setEditable(true);
// comboNhanVien.setEditable(true);
combo.setBounds(58, 50, 154, 23);
combo.setTableData(tableData);
combo.setSelectedIndex(-1);
combo.setPopupAlignment(DetailedComboBox.Alignment.LEFT);
combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showDetails();
}
});
/* combo.getEditor().getEditorComponent().addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
combo.showPopup();
combo.hidePopup();
}
#Override
public void focusLost(FocusEvent arg0) {
//combo.hidePopup();
}
});*/
combo.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
System.out.print(e.getKeyCode());
String value= combo.getEditor().getItem().toString();
if (value.trim().length() == 0 && e.getKeyCode() != 40) {
combo.hidePopup();
// System.out.print(e.getKeyCode());
}else {
combo.showPopup();
//System.out.print("X: "+e.getKeyCode());
}
}
});
List<List<?>> tableDataLop = new ArrayList<List<?>>();
tableDataLop.add(new ArrayList<String>(
Arrays.asList("0","Class A")));
tableDataLop.add(new ArrayList<String>(
Arrays.asList("1","Class B")));
String[] columnsLop = new String[]{"ID","Class"};
int[] widthsLop = new int[]{0,100};
comboLop = new DetailedComboBox(columnsLop, widthsLop, 0);
comboLop.setEditable(true);
// comboNhanVien.setEditable(true);
comboLop.setBounds(58, 50, 154, 23);
comboLop.setTableData(tableDataLop);
comboLop.setSelectedIndex(-1);
comboLop.setPopupAlignment(DetailedComboBox.Alignment.LEFT);
comboLop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
showDetailsLop();
}
});
comboLop.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
System.out.print(e.getKeyCode());
String value= comboLop.getEditor().getItem().toString();
if (value.trim().length() == 0 && e.getKeyCode() != 40) {
comboLop.hidePopup();
// System.out.print(e.getKeyCode());
}else {
comboLop.showPopup();
//System.out.print("X: "+e.getKeyCode());
}
}
});
comboLop.setEditable(true);
comboLop.setBounds(58, 94, 154, 23);
JPanel p = new JPanel();
p.setLayout(null);
p.add(combo);
p.add(comboLop);
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(p, BorderLayout.CENTER);
p.add(getTextField());
p.add(getTextField2());
//frame.getContentPane().setLayout(null);
//frame.getContentPane().add(comboNhanVien);
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* Launch the application.
*/
/**
* Create the application.
*/
private static void showDetails()
{
List<? extends Object> rowData = combo.getSelectedRow();
textField.setText(rowData.get(1).toString());
// capital.setText(rowData.get(2).toString());
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Form());
}
private JTextField getTextField() {
if (textField == null) {
textField = new JTextField();
textField.setBounds(234, 52, 86, 20);
textField.setColumns(10);
}
return textField;
}
private JTextField getTextField2() {
if (textField2 == null) {
textField2 = new JTextField();
textField2.setColumns(10);
textField2.setBounds(234, 96, 86, 20);
}
return textField2;
}
private static void showDetailsLop()
{
List<? extends Object> rowData = comboLop.getSelectedRow();
textField2.setText(rowData.get(1).toString());
// capital.setText(rowData.get(2).toString());
}
}
and DetailedComboBox.java
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
import javax.swing.table.*;
/**
* A JComboBox that has a JTable as a drop-down instead of a JList
*/
#SuppressWarnings({ "rawtypes", "serial" })
public class DetailedComboBox extends JComboBox
{
public static enum Alignment {LEFT, RIGHT}
private List<List<? extends Object>> tableData;
private String[] columnNames;
private int[] columnWidths;
private Alignment popupAlignment = Alignment.LEFT;
/**
* Construct a TableComboBox object
*/
public DetailedComboBox(String[] colNames, int[] colWidths,
int displayColumnIndex)
{
super();
this.columnNames = colNames;
this.columnWidths = colWidths;
setUI(new TableComboBoxUI());
setEditable(false);
}
/**
* Set the type of alignment for the popup table
*/
public void setPopupAlignment(Alignment alignment)
{
popupAlignment = alignment;
}
/**
* Populate the combobox and drop-down table with the supplied data.
* If the supplied List is non-null and non-empty, it is assumed that
* the data is a List of Lists to be used for the drop-down table.
* The combobox is also populated with the column data from the
* column defined by <code>displayColumn</code>.
*/
#SuppressWarnings("unchecked")
public void setTableData(List<List<? extends Object>> tableData)
{
this.tableData = (tableData == null ?
new ArrayList<List<? extends Object>>() : tableData);
// even though the incoming data is for the table, we must also
// populate the combobox's data, so first clear the previous list.
removeAllItems();
// then load the combobox with data from the appropriate column
Iterator<List<? extends Object>> iter = this.tableData.iterator();
while (iter.hasNext())
{
List<? extends Object> rowData = iter.next();
// System.out.print(rowData.get(1));
addItem(rowData.get(1));
// addItem(rowData.get(displayColumn));
}
}
public List<? extends Object> getSelectedRow()
{
List<? extends Object> data = null;
if(tableData.get(getSelectedIndex()) != null){
data=tableData.get(getSelectedIndex());
}
System.out.println(data);
return data;
}
/**
* The handler for the combobox's components
*/
private class TableComboBoxUI extends MetalComboBoxUI
{
/**
* Create a popup component for the ComboBox
*/
#Override
protected ComboPopup createPopup()
{
return new TableComboPopup(comboBox, this);
}
/**
* Return the JList component
*/
public JList getList()
{
return listBox;
}
}
/**
* The drop-down of the combobox, which is a JTable instead of a JList.
*/
private class TableComboPopup extends BasicComboPopup
implements ListSelectionListener, ItemListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JTable table;
private TableComboBoxUI comboBoxUI;
private PopupTableModel tableModel;
private JScrollPane scroll;
// private JList list = new JList();
// private ListSelectionListener selectionListener;
// private ItemListener itemListener;
private void selectRow()
{
int index = comboBox.getSelectedIndex();
if (index != -1)
{
int idc=table.getRowCount();
if(idc>0){
//System.out.println("idc "+idc);
//table.setRowSelectionInterval(index, index);
//table.scrollRectToVisible(table.getCellRect(index, 0, true));
}
}
}
/**
* Construct a popup component that's a table
*/
public TableComboPopup(JComboBox combo, TableComboBoxUI ui)
{
super(combo);
this.comboBoxUI = ui;
tableModel = new PopupTableModel();
table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getTableHeader().setReorderingAllowed(false);
TableColumnModel tableColumnModel = table.getColumnModel();
tableColumnModel.setColumnSelectionAllowed(false);
for (int index = 0; index < table.getColumnCount(); index++)
{
TableColumn tableColumn = tableColumnModel.getColumn(index);
tableColumn.setPreferredWidth(columnWidths[index]);
}
table.removeColumn(table.getColumnModel().getColumn(0));
scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
selectionModel.addListSelectionListener(this);
combo.addItemListener(this);
table.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent event)
{
// java.awt.Point p = event.getPoint();
// int row = table.rowAtPoint(p);
//int row = table.convertRowIndexToModel(table.getEditingRow());
//System.out.println("row 2: "+row);
/// comboBox.setSelectedIndex(row);
//comboBox.getEditor().setItem("Text Has Changed");
hide();
}
});
table.setBackground(UIManager.getColor("ComboBox.listBackground"));
table.setForeground(UIManager.getColor("ComboBox.listForeground"));
}
/**
* This method is overridden from BasicComboPopup
*/
#Override
public void show()
{
if (isEnabled())
{
super.removeAll();
int scrollWidth = table.getPreferredSize().width +
((Integer) UIManager.get("ScrollBar.width")).intValue() + 1;
int scrollHeight = comboBoxUI.getList().
getPreferredScrollableViewportSize().height;
scroll.setPreferredSize(new Dimension(scrollWidth, scrollHeight));
super.add(scroll);
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.removeListSelectionListener(this);
selectRow();
selectionModel.addListSelectionListener(this);
int scrollX = 0;
int scrollY = comboBox.getBounds().height;
if (popupAlignment == Alignment.RIGHT)
{
scrollX = comboBox.getBounds().width - scrollWidth;
}
show(comboBox, scrollX, scrollY);
// table.setRowSelectionInterval(0, 0);
comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
String value= comboBox.getEditor().getItem().toString();
//System.out.println("value: " +value);
TableRowSorter<TableModel> rowSorter
= new TableRowSorter<>(table.getModel());
table.setRowSorter(rowSorter);
if (value.trim().length() == 0) {
rowSorter.setRowFilter(null);
table.setRowSelectionInterval(0, 0);
}else {
rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + value,1));
int index = comboBox.getSelectedIndex();
if (index != -1)
{
int idc=table.getRowCount();
if(idc>0){
//System.out.println("idc "+idc);
//table.setRowSelectionInterval(index, index);
//table.scrollRectToVisible(table.getCellRect(index, 0, true));
}
}
}
}
});
}
}
/**
* Implemention of ListSelectionListener
*/
public void valueChanged(ListSelectionEvent event)
{
int index = table.getSelectedRow();
int row = table.convertRowIndexToView(table.getEditingRow());
System.out.println("B "+row);
if (index != -1)
{
//System.out.print("B "+index);
comboBox.setSelectedIndex(table.getSelectedRow());
}
}
#Override
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub
}
}
/**
* A model for the popup table's data
*/
private class PopupTableModel extends AbstractTableModel
{
/**
* Return the # of columns in the drop-down table
*/
public int getColumnCount()
{
return columnNames.length;
}
/**
* Return the # of rows in the drop-down table
*/
public int getRowCount()
{
return tableData == null ? 0 : tableData.size();
}
/**
* Determine the value for a given cell
*/
public Object getValueAt(int row, int col)
{
if (tableData == null || tableData.size() == 0)
{
return "";
}
return tableData.get(row).get(col);
}
/**
* All cells in the drop-down table are uneditable
*/
#Override
public boolean isCellEditable(int row, int col)
{
return false;
}
/**
* Pull the column names out of the tableInfo object for the header
*/
#Override
public String getColumnName(int column)
{
String columnName = null;
if (column >= 0 && column < columnNames.length)
{
columnName = columnNames[column].toString();
}
return (columnName == null) ? super.getColumnName(column) : columnName;
}
}
}
You need to be aware of the model/view index relationship between the combo box, table and model.
Your combo box will always have all the entries so its index is equivalent to the model index.
The table may be filtered or not so you need to convert its index to the model index so you can set the combo box index.
If I understand what you are attempting to do then this is the change I made to your valueChanged() method:
public void valueChanged(ListSelectionEvent event)
{
int index = table.getSelectedRow();
if (index != -1)
{
int row = table.convertRowIndexToModel(index);
comboBox.setSelectedIndex(row);
}
}

set focus to JList and have cursor on textField swing java autocomplete

I started to develop my own auto complete swing component and I want to set focus to the list when user press up or down keys and in the same time let the cursor on the textfield to allow him to type text or number....
to set focus to JList when typing up or down I have used
list.requestFocus();
is there any way to have focus on JList and cursor on JTextField
please view the image in here
here my code :
package examples.autocomplete;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import com.gestioncaisse.dao.ClientDAO;
import com.gestioncaisse.dao.DAO;
import com.gestioncaisse.dao.MyConnection;
import com.gestioncaisse.pojos.Client;
import com.gestioncaisse.utils.utils;
public class testcombo extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
final DAO<Client> clientDao;
List<Client> list_clients;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testcombo frame = new testcombo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
boolean first_time = true;
/**
* Create the frame.
*/
public testcombo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
clientDao = new ClientDAO(MyConnection.getInstance());
list_clients = clientDao.findAll();
textField = new JTextField();
textField.setBounds(5, 11, 113, 20);
textField.setColumns(10);
final JButton btnNewButton = new JButton("...");
btnNewButton.setBounds(116, 10, 45, 23);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 31, 156, 144);
final JList list = new JList(
utils.fromListToObjectTable2Clients(list_clients));
scrollPane.setViewportView(list);
list.setVisibleRowCount(5);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
contentPane.add(scrollPane);
contentPane.add(textField);
contentPane.add(btnNewButton);
textField.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
int a = list.getSelectedIndex();
if (arg0.getKeyCode() == KeyEvent.VK_UP) {
list.requestFocus();
} else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
list.requestFocus();
} else if (!first_time) {
} else {
first_time = false;
}
}
#Override
public void keyPressed(KeyEvent arg0) {
}
});
}
}
//if (a > 0)
//list.setSelectedIndex(a - 1);
//int first_vis = list.getFirstVisibleIndex();
//list.setListData(utils.fromListToObjectTable2Clients(clientDao.findByString(textField.getText())));
//list.setSelectedIndex(0);
Leave the focus on the JTextField but add KeyBindings to the UP/DOWN key. In the actions just change selection in JList (public void setSelectedIndex(int index) method)
UPDATE
An aslternative way would be to have focus on JList and add KeyListener translating typed chars to the JTextField. To Show caret use
jTextFieldInstance.getCaret().setVisible(true);
jTextFieldInstance.getCaret().setSelectionVisible(true);
Here i used to retrieve matched data from database
keywordssearcher.setEditable(true);
final JTextComponent sfield = (JTextComponent) keywordssearcher.getEditor().getEditorComponent();
sfield.setVisible(true);
sfield.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent ke) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
comboFilter(sfield.getText(), con);
}
});
}
#Override
public void keyPressed(KeyEvent e) {
if (!(sfield.getText().equals("")) || (sfield.getText() == null)) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
addKeyWord(sfield.getText().toString());
}
}
}
});
public void comboFilter(String enteredText, Connection ncon) {
log.info("ncon autosuggest--->" + ncon);
ArrayList<String> filterArray = new ArrayList<String>();
String str1 = "";
try {
Statement stmt = dc.ConnectDB().createStatement();
String str = "SELECT k_word FROM T_KeyWords WHERE k_word LIKE '" + enteredText + "%'";
ResultSet rs = stmt.executeQuery(str);
while (rs.next()) {
str1 = rs.getString("k_word");
filterArray.add(str1);
con.close();
}
} catch (Exception ex) {
log.error("Error in getting keywords from database" + ex.toString());
JOptionPane.showMessageDialog(null, "Error in getting keywords from database" + ex.toString());
}
if (filterArray.size() > 0) {
keywordssearcher.setModel(new DefaultComboBoxModel(filterArray.toArray()));
keywordssearcher.setSelectedItem(enteredText);
keywordssearcher.showPopup();
} else {
keywordssearcher.hidePopup();
}
}
Here my keywordssearcher(jcombobox) is editable and the entered value can be added directly into the database.
use this as a reference and modify the code

how to add different JComboBox items in a Column of a JTable in Swing

I want to add JComboBox inside a JTable (3,3) on column 1. But in the column 1 , each row will have its own set of ComboBox element.
When I tried to use
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(comboBox_Custom));
Each row is being set to same set of ComboBox Values.
But I want each row ComboBox has different items.
example on java2s.com looks like as works and correctly, then for example (I harcoded JComboBoxes for quick example, and add/change for todays Swing)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.*;
public class EachRowEditorExample extends JFrame {
private static final long serialVersionUID = 1L;
public EachRowEditorExample() {
super("EachRow Editor Example");
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
System.out.println(info.getName());
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (UnsupportedLookAndFeelException e) {
// handle exception
} catch (ClassNotFoundException e) {
// handle exception
} catch (InstantiationException e) {
// handle exception
} catch (IllegalAccessException e) {
// handle exception
}
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{{"Name", "MyName"}, {"Gender", "Male"}, {"Color", "Fruit"}}, new Object[]{"Column1", "Column2"});
JTable table = new JTable(dm);
table.setRowHeight(20);
JComboBox comboBox = new JComboBox();
comboBox.addItem("Male");
comboBox.addItem("Female");
comboBox.addComponentListener(new ComponentAdapter() {
#Override
public void componentShown(ComponentEvent e) {
final JComponent c = (JComponent) e.getSource();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
c.requestFocus();
System.out.println(c);
if (c instanceof JComboBox) {
System.out.println("a");
}
}
});
}
});
JComboBox comboBox1 = new JComboBox();
comboBox1.addItem("Name");
comboBox1.addItem("MyName");
comboBox1.addComponentListener(new ComponentAdapter() {
#Override
public void componentShown(ComponentEvent e) {
final JComponent c = (JComponent) e.getSource();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
c.requestFocus();
System.out.println(c);
if (c instanceof JComboBox) {
System.out.println("a");
}
}
});
}
});
JComboBox comboBox2 = new JComboBox();
comboBox2.addItem("Banana");
comboBox2.addItem("Apple");
comboBox2.addComponentListener(new ComponentAdapter() {
#Override
public void componentShown(ComponentEvent e) {
final JComponent c = (JComponent) e.getSource();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
c.requestFocus();
System.out.println(c);
if (c instanceof JComboBox) {
System.out.println("a");
}
}
});
}
});
EachRowEditor rowEditor = new EachRowEditor(table);
rowEditor.setEditorAt(0, new DefaultCellEditor(comboBox1));
rowEditor.setEditorAt(1, new DefaultCellEditor(comboBox));
rowEditor.setEditorAt(2, new DefaultCellEditor(comboBox2));
table.getColumn("Column2").setCellEditor(rowEditor);
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll, BorderLayout.CENTER);
setPreferredSize(new Dimension(400, 120));
setLocation(150, 100);
pack();
setVisible(true);
}
public static void main(String[] args) {
EachRowEditorExample frame = new EachRowEditorExample();
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
just add EachRowEditor Class
package com.atos.table.classes;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
public class PartCustomerWindow2 {
public static final Object[][] DATA = { { 1, 2,3, 4,false }, { 5, 6,7, 8 ,true},{ 9, 10,11, 12,true }, { 13, 14,15, 16,true } };
public static final String[] COL_NAMES = { "One", "Two", "Three", "Four",MyTableModel1.SELECT };
JButton but = new JButton("Add");
private JComboBox jcomboBox = null;
private JTextField jTextField = null;
static Object[][] rowData = null;
private JTable table=null;
static JFrame frame = null;
HashMap mp = null;
static int count = 0;
String content = null;
public JTextField getjTextField() {
if(jTextField == null)
{
jTextField = new FMORestrictedTextField(FMORestrictedTextField.JUST_ALPHANUMERIC, 8);
}
mp = new HashMap();
mp.put("arif",2);
mp.put("8",6);
mp.put("12",10);
mp.put("14",16);
mp.put("pk1",22);
mp.put("pk3",23);
jTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if(count == 0)
content = jTextField.getText();
// System.out.println(content);
if(mp.containsKey(content))
{
JFrame parent = new JFrame();
JOptionPane.showMessageDialog(parent, "Already Assigned");
}
}
});
return jTextField;
}
public void setjTextField(JTextField jTextField) {
this.jTextField = jTextField;
}
public JComboBox getJcomboBox() {
if(jcomboBox == null)
{
jcomboBox = new JComboBox();
}
return jcomboBox;
}
public void setJcomboBox(JComboBox jcomboBox) {
this.jcomboBox = jcomboBox;
}
private void createAndShowGui(PartCustomerWindow2 ob)
{
/*rowData = new Object[DATA.length][];
for (int i = 0; i < rowData.length; i++) {
rowData[i] = new Object[DATA[i].length + 1];
for (int j = 0; j < DATA[i].length; j++) {
rowData[i][j] = DATA[i][j];
}
rowData[i][DATA[i].length] = Boolean.TRUE;
if(i == 2 || i ==3)
rowData[i][DATA[i].length] = Boolean.FALSE;
}*/
MyTableModel3 tableModel = new MyTableModel3(DATA, COL_NAMES, "My Table", ob);
table = new JTable(tableModel);
//table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
/*table.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
table.getSelectionModel().clearSelection();
}
});*/
TableColumnModel cm = table.getColumnModel();
/*cm.getColumn(2).setCellEditor(new DefaultCellEditor(
new JComboBox(new DefaultComboBoxModel(new String[] {
"Yes",
"No",
"Maybe"
}))));*/
/* String ar1[]= {"aa","aaa","aaaa"};
ob.getJcomboBox().setModel(new DefaultComboBoxModel(ar1));*/
cm.getColumn(2).setCellEditor(new DefaultCellEditor(
ob.getJcomboBox()));
cm.getColumn(3).setCellEditor(new DefaultCellEditor(
ob.getjTextField()));
JScrollPane scrollPane = new JScrollPane();
/* scrollPane.add("Table",table);
scrollPane.add("Button",but);*/
JFrame frame2 = new JFrame();
/* jcomboBox.setPreferredSize(new Dimension(100,20));
textField.setPreferredSize(new Dimension(100,20));
jcomboBox.setEnabled(false);
textField.setEnabled(false);
*/
JScrollPane scrollPane2 = new JScrollPane(but);
but.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(table.getCellEditor() != null)
table.getCellEditor().stopCellEditing();
// TODO Auto-generated method stub
String[][] ar = new String[table.getRowCount()][5];
for(int i =0;i<table.getRowCount();i++)
{
for(int j=0;j<5;j++)
{
DATA[i][j] = table.getValueAt(i,j);
}
System.out.print(table.getValueAt(i,0)+" ");
System.out.print(table.getValueAt(i,1)+" ");
System.out.print(table.getValueAt(i,2)+" ");
System.out.print(table.getValueAt(i,3)+" ");
System.out.println(table.getValueAt(i,4)+" ");
}
System.out.println("*******************");
/*
for(int i=0;i<DATA.length;i++)
{
System.out.print(DATA[i][0]);
System.out.print(DATA[i][1]);
System.out.print(DATA[i][2]);
System.out.print(DATA[i][3]);
boolean check =(Boolean) DATA[i][4];
System.out.println(check);
}*/
}});
frame = new JFrame("PartCustomerWindow2");
//
//JFrame frame = new JFrame();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(new JScrollPane(table), BorderLayout.NORTH);
contentPane.add(but);
//
//frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* frame.getContentPane().add(scrollPane2);
frame.getContentPane().add(scrollPane3);
frame.getContentPane().add(scrollPane4);*/
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
PartCustomerWindow2 ob = new PartCustomerWindow2();
ob.createAndShowGui(ob);
}
}
#SuppressWarnings("serial")
class MyTableModel3 extends DefaultTableModel {
public static final String SELECT = "select";
String tablename;
PartCustomerWindow2 ob = null;
public MyTableModel3(Object[][] rowData, Object[] columnNames, String tableName,PartCustomerWindow2 ob) {
super(rowData, columnNames);
this.tablename = tableName;
this.ob = ob;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
if (getColumnName(columnIndex).equalsIgnoreCase(SELECT)) {
return Boolean.class;
}
else
return super.getColumnClass(columnIndex);
}
#Override
public boolean isCellEditable(int row, int col) {
JComboBox jb = ob.getJcomboBox();
JTextField jt = ob.getjTextField();
if(((Boolean) getValueAt(row, getColumnCount() - 1)).booleanValue())
{
// jb.setEnabled(false);
jb.removeAllItems();
// System.out.println(jb.getItemCount());
if(row == 0)
{
jb.addItem("arif");
jb.addItem("asif");
jb.addItem("ashik");
jb.addItem("farooq");
jb.addItem("adkh");
}
if(row > 0)
{
jb.addItem("kjhds");
jb.addItem("sdds");
jb.addItem("asdfsdk");
jb.addItem("sdfsdf");
jb.addItem("sdf");
}
/*HashMap mp = new HashMap();
mp.put("arif",2);
mp.put("8",6);
mp.put("12",10);
mp.put("14",16);
mp.put("pk1",22);
mp.put("pk3",23);
*/
/* if(col == 3){
if(mp.containsKey(jt.getText()))
{
System.out.println("Sorry..!! already assigned");
jt.setFocusable(true);
}
jt.setText("");
jt.setEnabled(false);
}*/
}
else
{
// jb.setEnabled(true);
//jt.setEnabled(true);
}
if (col == getColumnCount()-1 ) {
return true;
}
else{
if (getColumnName(4).equalsIgnoreCase(SELECT) && ((Boolean) getValueAt(row, getColumnCount() - 1)).booleanValue())
{
// jb.setEnabled(true);
// jt.setEnabled(true);
return (col == 2 || col == 3);
}
else{
// jb.setEnabled(false);
//jt.setEnabled(false);
return false;
}
}
}
}

Categories