JCombobox change another JCombobox values from mysql database - java

I use this code to display combobox in the search result in the database.
But I wanted a second combobox to show me a subcategory of the first.
How can I do this?
Thanks for help.
private void FillComboTipoEmpresas2(){
try{
String sql="select * from tiposempresa";
pst=(PreparedStatement) conexao.prepareStatement(sql);
rs=pst.executeQuery();
while(rs.next()){
String tiposempresa = rs.getString("descTipoEmpresa");
jComboBoxTipoEmpresas2.addItem(tiposempresa);
}
rs.close();
pst.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
private void jComboBoxTipoEmpresasPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
String tmp = (String) jComboBoxTipoEmpresas.getSelectedItem();
String sql = "select * from tiposempresa where descTipoEmpresa=?";
try{
pst=(PreparedStatement) conexao.prepareStatement(sql);
pst.setString(1, tmp);
rs=pst.executeQuery();
if(rs.next()){
String add2 = rs.getString("idTiposEmpresa");
jTTipoEmpresa.setText(add2);
}
rs.close();
pst.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
If someone doesnt understand the question I try to explain better.
Thanks again

jComboBoxTipoEmpresas2.addItem(tiposempresa);
I need a second JComboBox who list only the subcategory of the first Jcombobox...
It looks like you are just adding a new item. You first need to remove all the existing items from the model outside of the loop that adds new items to the model.
comboBox.removeAllItem();
Or the other approach is to create a new model and replace the existing model. Here is an example that show how this is done with hardcoded models:
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();
}
});
}
}

Related

SQL statement to JTable

I'd like to show all data out of a sqlite3 database inside of a JTable.
My result statement function looks like this:
public void getCustomerData()
{
Connection c = null;
Statement stmt = null;
ResultSet rs = null;
String ArrStrResult[][] = null;;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:database.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
rs = stmt.executeQuery( "SELECT * FROM kunden");
ResultSetMetaData metadata = rs.getMetaData();
int numberOfColumns = metadata.getColumnCount();
while(rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String vorname = rs.getString("vorname");
String gebdatum = rs.getString("gebdatum");
String strasse = rs.getString("strasse");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "VORNAME = " + vorname );
System.out.println( "Geb.-Datum = " + gebdatum );
System.out.println( "Straße = " + strasse );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
}
}
In my MainWindow - class I'd like to have the result of the sql statement inside of a JTable which looks like this:
private void updateCustomerTable()
{
// Tabellengrundgerüst erstellen
tableCustomer = new JTable();
tableCustomer.setEnabled(false);
tableCustomer.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tableCustomer.setModel(new DefaultTableModel(
new Object[][] {,
},
new String[] {
"Name:", "Vorname:", "Kd.-Nr.:", "Geb.-Datum:", "Stra\u00DFe:", "PLZ:", "Stadt:", "Email:", "Telefon:", "Handy:", "Termin:", "Bemerkung:"
}
));
scrollPaneCustomer.setViewportView(tableCustomer);
What is the best way to get all values of the sql statement inside the JTable?
I'll leave you with an example that shows how you can fill the table. It's all wrapped in one MCVE, things like the Person class and the PersonModel class should exist as top-level classes.
Look at the readData method and see it as the method you have that reads the data. It should return the data as a list that can be set as the data container of the table model. In this case the PersonModel stores the data in a generic List<Person>. The readData method in this example is lazy in that it returns a simple Arrays.asList which returns a List<> wrapper around an array (i.e. it's fixed size). You will probably want to return an ArrayList from your data-reading method if you want to add/remove rows from the UI.
You can find more details on this way of working in #camickr's article he already posted as a comment, here.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.AbstractTableModel;
public class JTableFillExample {
private static class Person {
int id;
String firstName;
String surName;
Date birthDate;
String address;
public Person( int id, String firstName, String surName, Date birthDate, String address ) {
this.id = id;
this.firstName = firstName;
this.surName = surName;
this.birthDate = birthDate;
this.address = address;
}
}
#SuppressWarnings("serial")
private static class PersonModel extends AbstractTableModel {
private List<Person> dataContainer;
private static String[] columnNames = {
"ID",
"First Name",
"Surname",
"Birth Date",
"Address"
};
public PersonModel() {
dataContainer = new ArrayList<>();
}
#SuppressWarnings("unused")
public PersonModel(List<Person> dataContainer) {
this.dataContainer = dataContainer;
}
public void setDataContainer(List<Person> dataContainer) {
this.dataContainer = dataContainer;
fireTableDataChanged();
}
#Override
public int getRowCount() {
return dataContainer.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person p = dataContainer.get(rowIndex);
switch(columnIndex) {
case 0: return p.id;
case 1: return p.firstName;
case 2: return p.surName;
case 3: return p.birthDate;
case 4: return p.address;
default: return null;
}
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0: return Integer.class;
case 3: return Date.class;
default: return String.class;
}
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Person p = dataContainer.get(rowIndex);
switch(columnIndex) {
case 0: p.id = (Integer) aValue; break;
case 1: p.firstName = (String) aValue; break;
case 2: p.surName = (String) aValue; break;
case 3: p.birthDate = (Date) aValue; break;
case 4: p.address = (String) aValue; break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
}
private static Component createTable() {
return new JTable( new PersonModel() );
}
protected static JFrame createFrame() {
JPanel p = new JPanel( );
p.setLayout( new BorderLayout( ) );
p.add( new JScrollPane( createTable( ) ), BorderLayout.CENTER );
p.setPreferredSize( new Dimension( 400, 100 ) );
JFrame f = new JFrame( );
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setContentPane( p );
f.pack( );
return f;
}
private static List<Person> readData() {
return Arrays.asList (
new Person( 1, "Tom", "T", new GregorianCalendar(1975,7,15).getTime(), "Somewhere in Ghent City"),
new Person( 2, "Jack", "N", new GregorianCalendar(1951,5,13).getTime(), "Somewhere in the States"),
new Person( 3, "Madonna", "H", new GregorianCalendar(1960,1,19).getTime(), "Somewhere in the States as well")
);
}
private static void readDataAndFillTable(JTable tbl) {
((PersonModel) tbl.getModel()).setDataContainer(readData());
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = createFrame();
f.setVisible(true);
final JTable tbl = (JTable) ((JScrollPane) f.getContentPane().getComponent(0)).getViewport().getView();
Timer t = new Timer(1000, new ActionListener() { // fill the table after a second
#Override
public void actionPerformed(ActionEvent e) {
readDataAndFillTable(tbl);
}
});
t.setRepeats(false);
t.start();
}
});
}
}
The way that I have done this previously is for student details, in the code below I have created a table for each class in my sql database. There are two methods below, one getting all of the details from the database and one filling the data into a JTable, I have got my connection in another method too.
public void alldet(){
JFrame frame = new JFrame("All Details");
JPanel panel = new JPanel(new MigLayout());
JButton back = new JButton("Back");
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Name");
model.addColumn("Surname");
model.addColumn("Gender");
model.addColumn("Target");
model.addColumn("Grade");
model.addColumn("Class");
JTable table = new JTable(model);
JTable table2 = new JTable(model);
JTable table3 = new JTable(model);
filldata(table, "details");
filldata(table2, "details2");
filldata(table3, "details3");
table.setPreferredScrollableViewportSize(new Dimension(519, 350));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
panel.add(back, "dock south");
frame.add(panel);
frame.setSize(519,405);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setResizable(true);
panel.repaint();
frame.setVisible(true);
back.addActionListener((ActionEvent e) -> {
frame.hide();
});
}
public void filldata(JTable table, String type){
try
{
Connection conn = Connect();
if(!Main.teachclass.equals("All")){
Query = "SELECT name,surname,gender,target,grades,class FROM "+type+" WHERE class = ?";
statement = conn.prepareStatement(Query);
statement.setString(1, Main.teachclass);
}else{
Query = "SELECT name,surname,gender,target,grades,class FROM "+type;
statement = conn.prepareStatement(Query);
}
ResultSet res = statement.executeQuery();
int columns = res.getMetaData().getColumnCount();
while(res.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = res.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(res.getRow() - 1, row);
}
res.close();
statement.close();
conn.close();
}
catch(SQLException e)
{
}

How to create a multi-layer JComboBox

I'm creating a simulator using Java Swing. I used JComboBox to display units of utilities such as "KW, KL, KM" etc to measure Power, Water and distance. It's simple to add bunch of items to a JComboBox. User select a unit and the JFrame will save the selection when a "save" button is clicked.
JComboBox comboBox = new JComboBox();
for(ValueUnits u: ValueUnits.values()){
comboBox.addItem(u.returnUnits());
}
comboBox.setSelectedIndex(-1);
unitColumn.setCellEditor(new DefaultCellEditor(comboBox));
Now I want to create an multi-layer JComboBox (perhaps JMenu?). The function of such should behave as a multi-layer JMenu. When the JComboBox is clicked, it will show the first layer - category such as "Electricity, Water, Distance...", Then when mouse hover over Electricity, a list of Electricity units such as "KW, MW, W ..." will show. These collections are fetched from Enumerations. I wonder what's the most correct way to create such component.
Thank you so much world!
Maybe use 2 combo boxes? That is you select a value in the first and the units are displayed in the second:
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();
}
});
}
}
Use It...
public class ComboLayer extends javax.swing.JPanel {
String Category1 = null;
String Category2 = null;
String Category3 = null;
Hashtable<String, String> hsItems;
public ComboLayer() {
this.hsItems = new Hashtable<>();
hsItems.put("Main", "Power,Water,Distance");
hsItems.put("Power", "KW,MW,W");
hsItems.put("Water", "ML,L,KL");
hsItems.put("Distance", "CM,M,KM");
initComponents();
String[] item = hsItems.get("Main").split(",");
for (String i : item) {
cmbItem.addItem(i);
}
cmbItem.addItem("Back");
cmbItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String selectText = null;
selectText = (String) cmbItem.getSelectedItem();
Enumeration enmKeys = hsItems.keys();
while (enmKeys.hasMoreElements()) {
String sKey = (String) enmKeys.nextElement();
if (selectText.equalsIgnoreCase("back")) {
if (hsItems.get(sKey).contains(cmbItem.getItemAt(0).toString())) {
Enumeration enumkeysBack = hsItems.keys();
while (enumkeysBack.hasMoreElements()) {
String sKeyBack = (String) enumkeysBack.nextElement();
if (hsItems.get(sKeyBack).contains(sKey)) {
String[] item = hsItems.get(sKeyBack).split(",");
cmbItem.removeAllItems();
for (String i : item) {
cmbItem.addItem(i);
}
if (!sKeyBack.equalsIgnoreCase("Main")) {
cmbItem.addItem("Back");
}
break;
}
}
}
} else if (sKey.contains(selectText)) {
String[] item = hsItems.get(sKey).split(",");
cmbItem.removeAllItems();
for (String i : item) {
cmbItem.addItem(i);
}
if (!sKey.equalsIgnoreCase("Main")) {
cmbItem.addItem("Back");
}
break;
}
}
}
});
}
public static void main(String... arg) {
ComboLayer cmbLyr = new ComboLayer();
JDialog dg = new JDialog();
dg.add(cmbLyr);
dg.setVisible(true);
}
Here's a combo with the effect of a custom popup of JMenu's. The actual popup is hidden, and a second popup is displayed when appropriate.
Upon selection of a JMenuItem, the combo is populated with just that one item, displayed in breadcrumb format.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
public class JMenuComboBoxDemo implements Runnable
{
private Map<String, String[]> menuData;
private JComboBox<String> combo;
private AbstractButton arrowButton;
private JPopupMenu popupMenu;
private List<String> flattenedData;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new JMenuComboBoxDemo());
}
public JMenuComboBoxDemo()
{
menuData = new HashMap<String, String[]>();
menuData.put("Colors", new String[]{"Black", "Blue"});
menuData.put("Flavors", new String[]{"Lemon", "Lime"});
popupMenu = new JPopupMenu();
popupMenu.setBorder(new MatteBorder(1, 1, 1, 1, Color.DARK_GRAY));
List<String> categories = new ArrayList<String>(menuData.keySet());
Collections.sort(categories);
// copy of the menuData, flattened into a List
flattenedData = new ArrayList<String>();
for (String category : categories)
{
JMenu menu = new JMenu(category);
for (String itemName : menuData.get(category))
{
menu.add(createMenuItem(itemName));
flattenedData.add(category + " > " + itemName);
}
popupMenu.add(menu);
}
combo = new JComboBox<String>();
combo.setPrototypeDisplayValue("12345678901234567890");
combo.setUI(new EmptyComboBoxUI());
for (Component comp : combo.getComponents())
{
if (comp instanceof AbstractButton)
{
arrowButton = (AbstractButton) comp;
}
}
arrowButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
setPopupVisible(! popupMenu.isVisible());
}
});
combo.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
setPopupVisible(! popupMenu.isVisible());
}
});
}
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = frame.getContentPane();
c.setLayout(new FlowLayout());
c.add(new JLabel("Options"));
c.add(combo);
frame.setSize(300, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
/*
* Toggle the visibility of the custom popup.
*/
private void setPopupVisible(boolean visible)
{
if (visible)
{
popupMenu.show(combo, 0, combo.getSize().height);
}
else
{
popupMenu.setVisible(false);
}
}
/*
* Create a JMenuItem whose listener will display
* the item in the combo.
*/
private JMenuItem createMenuItem(final String name)
{
JMenuItem item = new JMenuItem(name);
item.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
setComboSelection(name);
}
});
return item;
}
/*
* Search for the given name in the flattened list of menu items.
* If found, add that item to the combo and select it.
*/
private void setComboSelection(String name)
{
Vector<String> items = new Vector<String>();
for (String item : flattenedData)
{
/*
* We're cheating here: if two items have the same name
* (Fruit->Orange and Color->Orange, for example)
* the wrong one may get selected. This should be more sophisticated
* (left as an exercise to the reader)
*/
if (item.endsWith(name))
{
items.add(item);
break;
}
}
combo.setModel(new DefaultComboBoxModel<String>(items));
if (items.size() == 1)
{
combo.setSelectedIndex(0);
}
}
/*
* Prevents the default popup from being displayed
*/
class EmptyComboBoxUI extends MetalComboBoxUI
{
#Override
protected ComboPopup createPopup()
{
BasicComboPopup thePopup = (BasicComboPopup) super.createPopup();
thePopup.setPreferredSize(new Dimension(0,0)); // oh, the horror!
return thePopup;
}
}
}

How can I use filter between comboboxes in java?

I have two tables in my database as semester table and course table.There are semesterId,courseId,courseName and Sdepartment(department name)in semester table.Course table has courseId and courseName.
I have two comboboxes my jframe.First one is for select a department.Second one is select course.I want to select course as to selected department.
How can i call course name in combobox when i select a department?
Here my code;
public void coursename(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
//Query query= session.createQuery("select a.courseName,e.semesterId from Semester e inner join e.course as a");
Query query= session.createQuery("FROM Senior.entity.Semester S ");
//for (Iterator it = query.iterate(); it.hasNext();) {
//Object row[] = (Object[]) it.next();
//combocourse.addItem(new CourseItem((String)row[0], (int)row[1]));
//}
List <Semester>re= query.list();
if (re.size() > 0){
Iterator iterate= re.iterator();
final Semester resultAccount= (Semester)iterate.next();
combocourse.removeAllItems();
for(Semester inv:re){
combocourse.addItem(new CourseItem(inv.getSemesterId(),inv.getSCourse()));
}
}
session.close();
}
public void depart(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query= session.createQuery("FROM Senior.entity.Semester f ");
List <Semester>results= query.list();
if (results.size() > 0){
Iterator iterate= results.iterator();
final Semester resultAccount= (Semester)iterate.next();
combodepart.removeAllItems();
for(Semester inv:results){
combodepart.addItem(new DepartItem(inv.getSemesterId(),inv.getSDepartment()));
// combodepart.addActionListener(combocourse);
/*
#Override
public void actionPerformed(ActionEvent e) {
JComboBox combocourse;
combocourse = (JComboBox) e.getSource();
// Object selected = combocourse.getSelectedItem();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Query query= session.createQuery("FROM Senior.entity.Semester f ");
List <Semester>results= query.list();
if (results.size() > 0){
Iterator iterate= results.iterator();
final Semester resultAccount= (Semester)iterate.next();
combodepart.removeAllItems();
for(Semester inv:results){
combodepart.addItem(new DepartItem(inv.getSemesterId(),inv.getSDepartment()));
}
});
*/
}
}
session.close();
}
One way is to reset the model of the course combo box every time you select an item from the department combo box.
Something like:
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();
}
});
}
}
How to convert this example to database?
In the ActionListener you query the database to get the courses for the selected department and then you create the model.

Auto suggested combobox in JFrame

I use the following code for retrieve the data into combobox. How to change Jcombobox into Auto suggested combobox . It means when I press A the words which are start with A that will show in the items field in combobox.
public void combo(){
try{
GCS.GContnStr();
TmpFlxTSt= GCS.GCotnStr.createStatement();
String select = "Select StudName from studentmaster";
TmpFlxTRs = TmpFlxTSt.executeQuery(select);
while(TmpFlxTRs.next())
{
String TmpOb1=TmpFlxTRs.getString("StudName");
TmpOb1.toString();
cbx.addItem(TmpOb1);
cbx.setMaximumRowCount(1);
}
Try to use Combobox component from package org.jdesktop.swingx.autocomplete, maven repository here
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.plaf.basic.*;
class Test
{
private JComboBox_ cb = null;
public Test() {
JFrame fr=new JFrame("TEST ComboBox");
JPanel p = new JPanel();
p.setLayout( new BorderLayout() );
String[] ss = new String[]
{ "112","1123","1124","1134",
"first",
"second",
"third",
"third 1 before",
"third 2",
"third 1 after",
"third quarter",
"fourth",
"fourth and more",
"fourth and more and more"
};
fr.getContentPane().add(p);
cb = new JComboBox_(ss);
p.add("South",cb);
p.add("Center",new JButton("test combo box"));
fr.pack();
fr.show();
}
public static void main( String[] args ) {
Test test=new Test();
}
}
class JComboBox_ extends JComboBox {
public int caretPos=0;
public JTextField tf=null;
public JComboBox_(final Object items[]) {
super(items);
this.setEditor(new BasicComboBoxEditor());
this.setEditable(true);
}
public void setSelectedIndex(int ind) {
super.setSelectedIndex(ind);
tf.setText(getItemAt(ind).toString());
tf.setSelectionEnd(caretPos+tf.getText().length());
tf.moveCaretPosition(caretPos);
// tf.setSelectionStart(caretPos);
}
public void setEditor(ComboBoxEditor anEditor) {
super.setEditor(anEditor);
if (anEditor.getEditorComponent() instanceof JTextField) {
tf=(JTextField)anEditor.getEditorComponent();
tf.addKeyListener(new KeyAdapter()
{
public void keyReleased( KeyEvent ev )
{
char key=ev.getKeyChar();
if (! (Character.isLetterOrDigit(key)||Character.isSpaceChar(key) )) return;
String s = tf.getText();
caretPos=tf.getCaretPosition();
String text="";
try {
text=tf.getText(0,caretPos);
}
catch (Exception ex) {
ex.printStackTrace();
}
int n=getItemCount();
for (int i=0; i<n; i++) {
int ind=((String)getItemAt(i)).indexOf(text);
if (ind==0) {
setSelectedIndex(i);
return;
}
}
}
} );
}
}
}

java JComboBox issue

I was trying to have two Jcomboxes, where second Jcombox should changes its values according to the change in the first one.
I tried but could not succeed,Any help is appreciated. Thanks
This is what I have tried so Far:
public class SharedDataBetweenComboBoxSample {
static private String selectedString(ItemSelectable is) {
Object selected[] = is.getSelectedObjects();
return ((selected.length == 0) ? "null" : (String)selected[0]);
}
public static void main(String args[]) {
final String labels[] = { "A", "B", "C" };
final String labelsA[] = { "A", "AA", "AAA" };
final String labelsB[] = { "B", "BB", "BBB" };
final String labelsC[] = { "C", "CC", "CCC" };
final JFrame frame = new JFrame("Shared Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JComboBox comboBox1 = new JComboBox();
comboBox1.addItem(labels);
comboBox1.setSelectedItem(null);
final JComboBox comboBox2 = new JComboBox();
// comboBox2.setEditable(true);
panel.add(comboBox1);
panel.add(comboBox2);
frame.add(panel,BorderLayout.NORTH);
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
System.out.println((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");
System.out.println("Item: " + itemEvent.getItem());
ItemSelectable is = itemEvent.getItemSelectable();
System.out.println(", Selected: " + selectedString(is));
if (selectedString(is) == "B") {
comboBox2.addItem(labelsB);
// frame.add(comboBox1, BorderLayout.CENTER);
} else if (selectedString(is) == "A") {
comboBox2.addItem(labelsA);
// frame.add(comboBox1, BorderLayout.CENTER);
} else if (selectedString(is) == "C") {
comboBox2.addItem(labelsC);
// frame.add(comboBox1, BorderLayout.CENTER);
} else {
comboBox2.setSelectedItem(null);
// frame.add(comboBox1, BorderLayout.CENTER);
}
}
};
comboBox1.addItemListener(itemListener);
frame.setSize(300,200);
frame.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JFrame implements ActionListener
{
private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable subItems = new Hashtable();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox( items );
mainComboBox.addActionListener( this );
getContentPane().add( mainComboBox, BorderLayout.WEST );
// Create sub combo box with multiple models
subComboBox = new JComboBox();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
getContentPane().add( subComboBox, BorderLayout.EAST );
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 ) );
}
}
public static void main(String[] args)
{
JFrame frame = new ComboBoxTwo();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
not really sure what your problem is as you don't say. Maybe the issue is
comboBox2.addItem(labelsB);
this is adding an array as a single item in the list, perfectly acceptable assuming it is right, however i'm guessing you want to iterate through the array and add each one as separate items. You may want to remove items on deselection.
I assume you are trying from multiple selections on the first list (based on your selectedString operation), if not your code is miles out? If you are you do not want an if/else construct, just multiple ifs
Also, don't use (selectedString(is)=="A"), you might get lucky, but you should use `"A".equals(selectedString(is))

Categories