List of Values in Java Swing Form - java

How can I display an LoV in a Java Swing form as shown in Oracle Forms?
I have data concerning user identifiers and user names. And I want to display the user names in LoV, but if a user selects a name corresponding to a user, its identifier should be returned.
EDIT 1:
Here is the form code that I've used to display 'Lov'
import db.DBHelper;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class LovForm extends JDialog implements ActionListener {
private Connection conn;
private DBHelper db;
private JList list;
private DefaultListModel model;
private UserDetail userDetail;
private JButton btnOk;
public LovForm(Connection c, UserDetail u) {
this.conn = c;
this.userDetail = u;
initComponents();
}
private void initComponents() {
db = new DBHelper(this.conn);
btnOk = new JButton("Ok");
btnOk.addActionListener(this);
Container c = this.getContentPane();
c.setLayout(new FlowLayout());
model = new DefaultListModel();
try {
ResultSet rs = db.getAllAppUsers();
if (rs != null) {
while (rs.next()) {
String name = rs.getString("NAME");
model.addElement(name);
}
list = new JList(model);
}
} catch (Exception e) {
list = new JList();
}
list.setPreferredSize(new Dimension(150, 250));
JScrollPane listScroller = new JScrollPane(list);
JLabel lbl = new JLabel("Select an application user");
c.add(lbl);
c.add(listScroller);
c.add(btnOk);
this.setTitle("List of Users");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(new Dimension(200, 250));
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setModal(true);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e
) {
if (e.getSource() == btnOk) {
String selectedItem = (String) list.getSelectedValue();
userDetail.setUserName(selectedItem);
this.dispose();
}
}
}

I would add a wrapper class for the User, which contains its name and its id.
Do not forget to override the toString() method of the User (that method will be used when rendering the list).
While populating the list, create User objects, and therefore you will have access to both its name and its id.
See code bellow:
private void initComponents() {
// your code....
try {
ResultSet rs = db.getAllAppUsers();
if (rs != null) {
while (rs.next()) {
String name = rs.getString("NAME");
int id = rs.getInt("ID");
model.addElement(new User(name, id));
}
list = new JList(model);
}
} catch (Exception e) {
list = new JList();
}
// your code...
}
#Override
public void actionPerformed(ActionEvent e
) {
if (e.getSource() == btnOk) {
User selectedItem = (User) list.getSelectedValue();
userDetail.setUserName(selectedItem.getName());
int id = selectedItem.getId();
this.dispose();
}
}
public class User {
private String name;
private Integer id;
public User(String name, Integer id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Integer getId() {
return id;
}
#Override
public String toString() {
return name;
}
}

You could use a JComboBox.
You would create a custom Object to store both pieces of data. Then you would create a custom renderer to display whatever data you want in the combo box. Your processing code would then use the other property.
Check out Combo Box With Custom Renderer for an example of the rendering code you would use. This renderer is more complete than most rendering code you will find in the forum because it will still support selection of the item from the combo box using the keyboard.
I see you updated your question to show you are using a JList. Well the answer is still the same. You need a custom renderer for your JList. You can base your renderer off the example from the above link except you would extend the DefaultListCellRenderer.

Related

JList using HashMap key (String) as its display?

I've been self studying Java for a couple months and have run into a challenge. I'm making a contact list application. I chose to use HashMap<String, Contact> as my storage for the contacts. The challenge I'm running into is the my unfamiliarity with Swing. I'm trying for the first time to use JList. I have got JList to work with a normal array of strings but now I want to use the Key value from the HashMap for the JList display.
I have read elsewhere that a custom ListModel will do, but I have failed to find anything concrete. The oracle document How to Use Lists uses the DefaultListModel in its examples. I have read using AbstractListModel or ListModel are steps in the right direction. There are three main classes so far:
Class Contact
public class Contact {
private String name;
private String phoneNumber;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Class Book
import java.util.HashMap;
import java.util.Map;
public class Book {
private Map<String, Contact> addressbook = new HashMap<String, Contact>();
public Map<String, Contact> getAddressbook() {
return addressbook;
}
public void setAddressbook(Map<String, Contact> addressbook) {
this.addressbook = addressbook;
}
}
Class UserInterface
This is where I'm having difficulty creating a custom list model that takes the String keys from my HashMap located in class Book.
import java.awt.BorderLayout;
public class UserInterface extends JPanel implements ActionListener {
private static final long serialVersionUID = 2161244209167568887L;
// Contact list display
JList contactList;
// Menu bar and accompanying menu items
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem newContactMenuButton;
private JMenuItem exitAppMenuButton;
// Buttons
private JButton newContactButton;
private JButton openContactButton;
private JButton deleteContactButton;
// Panels to place components into
private JPanel mainPanel;
private JPanel buttonPanel;
// For message dialogs
private JFrame messageDialog;
public UserInterface() {
// Add the JList
contactList = new JList(new ContactListModel()); // ??
// Creating the menu bar and its items
// Adding ActionListeners to the menu buttons
menuBar = new JMenuBar();
menu = new JMenu("File");
newContactMenuButton = new JMenuItem("New Contact");
exitAppMenuButton= new JMenuItem("Exit");
newContactMenuButton.addActionListener(this);
exitAppMenuButton.addActionListener(this);
menu.add(newContactMenuButton);
menu.add(exitAppMenuButton);
menuBar.add(menu);
// Creating the Buttons
// Adding ActionListeners to the buttons
newContactButton = new JButton("New Contact");
openContactButton = new JButton("Open Contact");
deleteContactButton = new JButton("Delete Contact");
newContactButton.addActionListener(this);
openContactButton.addActionListener(this);
deleteContactButton.addActionListener(this);
// Creating the Panels with Grid Layouts
mainPanel = new JPanel(new GridLayout());
buttonPanel = new JPanel(new GridLayout(0, 1));
// Adding components to the Panels
mainPanel.add(contactList);
buttonPanel.add(newContactButton);
buttonPanel.add(openContactButton);
buttonPanel.add(deleteContactButton);
// Adding and aligning the Panels
setBorder(BorderFactory.createEmptyBorder(45, 45, 45, 45));
add(mainPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.EAST);
}
public void CreateAndShowUI() {
JFrame frame = new JFrame("Addressbook Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new UserInterface());
frame.setJMenuBar(this.menuBar);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == newContactButton) {
JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
}
if (e.getSource() == openContactButton) {
JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
}
if (e.getSource() == deleteContactButton) {
if(contactList.isSelectionEmpty()) {
JOptionPane.showMessageDialog(messageDialog, "No contact selected.");
} else if(!contactList.isSelectionEmpty()) {
}
}
if (e.getSource() == newContactMenuButton) {
JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
}
if (e.getSource() == exitAppMenuButton) {
System.exit(0);
}
}
}
final class ContactListModel extends AbstractListModel {
Book book = new Book();
Map<String, Contact> bookList = book.getAddressbook();
public Object getElementAt(int keys) {
keys = // ??
return keys;
}
#Override
public int getSize() {
return bookList.size();
}
}
Any genuine point in the right direction is highly appreciated. In the meantime I'll keep searching.
EDIT: Updated & Answered
Here are the relevant updated code bits. As user carmickr suggested I used DefaultListModel to handle the data from the address book HashMap.
private DefaultListModel<Set<String>> model;
private JList<Set<String>> contactList;
Then inside the UserInterface constructor:
// Create the DefaultListModel object
// Add the JList
model = new DefaultListModel<Set<String>>();
model.addElement(book.AB.keySet());
contactList = new JList<Set<String>>(model);
I'm having difficulty creating a custom list model that takes the String keys from my HashMap located in class Book.
You don't need to create a custom model. You can just add each Contact object to the DefaultListModel. The point of using models is that the model holds all the data and you use methods of the model to access the data.
Then the simplest way to get the JList to work is to implement the toString() method in your Contact object to return the property that you want to see in the JList.
EDIT: Updated & Answered
Here are the relevant updated code bits. As user carmickr suggested I used DefaultListModel to handle the data from the address book HashMap.
private DefaultListModel<Set<String>> model;
private JList<Set<String>> contactList;
Then inside the UserInterface constructor:
// Create the DefaultListModel object
// Add the JList
model = new DefaultListModel<Set<String>>();
model.addElement(book.AB.keySet());
contactList = new JList<Set<String>>(model);

focusGained and focusLost don't work?

I wanted to make a program that allows the user to add to a file, search for, delete and load from a file animals in a zoo and information about them. So far the buttons delete and search don't work, so pay no attention to them. The problem is that focusGained and focusLost don't seem to work. I tried every solution I found so far, but I couldn't fix them. So, all help is appreciated. If you have any ideas about how to write the Search and Delete classes, please suggest!
This is the main program:
package GUI_Try;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class GUI_ZOO extends JFrame{
ArrayList <ANIMAL> animal= new ArrayList<ANIMAL>();
TextField name,ID,country;
Button add = new Button("add"),
save = new Button("save"),
//delete = new Button("delete"),
//search = new Button("search"),
load = new Button("load");
String sName="",sID="",sCountry="";
JPanel pc;
JScrollPane scrPanName;
JTextArea text;
GUI_ZOO(){
super("Zoo \"Sofia\" ");
setBounds(80, 80, 600, 500);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
GUI_DELETE delObj = new GUI_DELETE();
GUI_SEARCH searchObj = new GUI_SEARCH();
GUI_ADD addObj = new GUI_ADD(sName,name,sID,ID,text,animal,sCountry,country);
pc = new JPanel();
pc.setLayout(new FlowLayout());
text = new JTextArea(20,10);
scrPanName = new JScrollPane(text);
name = new TextField("Name",15);
country = new TextField("Country",15);
ID = new TextField("ID",5);
text.setEditable(false);
pc.add(name);
pc.add(ID);
pc.add(country);
pc.add(add);
pc.add(save);
pc.add(load);
pc.add(search);
pc.add(delete);
ID.addActionListener(addObj);
name.addActionListener(addObj);
country.addActionListener(addObj);
add.addActionListener(addObj);
save.addActionListener(new Save());
load.addActionListener(new Load());
delete.addActionListener(delObj);
search.addActionListener(searchObj);
name.addFocusListener(new Focus()) ;
country.addFocusListener(new Focus()) ;
ID.addFocusListener(new Focus()) ;
add("North",pc);
add("Center",scrPanName);
setVisible(true);
}
class Focus implements FocusListener{
public void focusGained (FocusEvent e){
try{
TextField src = (TextField)e.getSource();
if(src.getText().equals("Name") ){
name.setText("");
}
if(src.getText().equals("ID") ){
ID.setText("");
}
if(src.getText().equals("Country") ){
country.setText("");
}
}
catch(ClassCastException ignored){
}
}
public void focusLost (FocusEvent e){
try{
TextField src = (TextField)e.getSource();
if(src.getText().equals("") ){
name.setText("Name");
}
if(src.getText().equals("") ){
ID.setText("ID");
}
if(src.getText().equals("") ){
country.setText("Country");
}
}
catch(ClassCastException ignored){
}
}
}
class Save implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("zoo.dat"));
os.writeObject(animal);
os.close();
}
catch(FileNotFoundException ex){
System.out.println("Can't save the file zoo.dat");
}
catch(IOException ex){}
}
}
class Load implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
ObjectInputStream os = new ObjectInputStream(new FileInputStream("zoo.dat"));
animal = (ArrayList<ANIMAL>) os.readObject();
os.close();
text.setText("");
for(ANIMAL a:animal){
text.append(a.name+"\t"+a.ID+"\t"+a.country+"\n");
}
}
catch(FileNotFoundException ex){
System.out.println("Can't find the file zoo.dat");
}
catch(IOException ex){
ex.printStackTrace();//?
}
catch (ClassNotFoundException e1) {
e1.printStackTrace();//?
}
}
}
public static void main(String arg[]){
new GUI_ZOO();
}
}
I divided the program, so the class GUI_ADD would be here:
package GUI_Try;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class GUI_ADD implements ActionListener{
String sNamel;
TextField namel;
String sIDl;
TextField IDl;
String sCountryl;
TextField countryl;
JTextArea textl;
ArrayList <ANIMAL> animall;
public GUI_ADD(String sName,TextField name,String sNumber,TextField ID,
JTextArea text,ArrayList <ANIMAL> animal,String sCountry,TextField country){
sNamel = sName;
sCountryl = sCountry;
IDl = ID;
namel = name;
sIDl = sNumber;
countryl = country;
textl = text;
animall = animal;
}
public void actionPerformed(ActionEvent e){
sNamel=namel.getText();
sIDl=IDl.getText();
sCountryl=countryl.getText();
if((sNamel.length()==0)||(sNamel=="Name")){
JOptionPane.showMessageDialog(null, "Type a name, please.");
return;
}
if(sIDl.length()==0){
JOptionPane.showMessageDialog(null, "Type an ID, please.");
return;
}
if(sCountryl.length()==0){
JOptionPane.showMessageDialog(null, "Type a country of origin, please.");
return;
}
animall.add(new ANIMAL(sNamel,sIDl,sCountryl));
textl.append(sNamel+"\t"+sIDl+"\t"+sCountryl+"\n");
namel.setText("");
IDl.setText("");
countryl.setText("");
}
}
And this is the interface:
package GUI_Try;
import java.io.*;
class ANIMAL implements Serializable {
String name, ID, country;
public ANIMAL(String name, String ID, String country){
this.name = name;
this.ID = ID;
this.country = country;
}
}
You donot need to implements FocusListener in both classes. Its redundant here.
public class GUI_ZOO extends JFrame implements FocusListener{
class Focus implements FocusListener{
And the reason for FocusGained and FocusLost did not work:
TextField name,ID,country;
You have used java.awt.TextField,
JTextField src = (JTextField)e.getSource();
But you are trying to get source from JTextField. In your program you donot have any JTextField's right!.
Change it to:
TextField src = (TextField)e.getSource();
Your problem (one of many) is mixing AWT and Swing components.
You create name, ID, and country as TextField, and then try to cast them as JTextField in your Focus listener. But, you protect against a ClassCastException, by suppressing it, so you don't even see evidence of this problem anymore.
try {
JTextField src = (JTextField) e.getSource();
// ... omitted
} catch(ClassCastException ignored) {
// No-op
}
You want (need) to use JTextField and JButton Swing objects, not the AWT objects, in your Swing program.
An additional problem with your focusLost method. If the the JTextField that loses focus is blank, you will overwrite your name, ID and country text fields ... not just the blank ones!

Register JPanel in radioButtonActionPerfomed

Can I catch the panel name from ActionListener?
Here is some code:
void models (int paneNum, int tabNum, String eQuery, String str, String title) throws SQLException {
intoModels[paneNum] = new JPanel();
intoModels[paneNum].setBackground(c);
intoModels[paneNum].setLayout(new GridLayout(6, 2));
ResultSet rs = DataBase.setConnection().executeQuery(eQuery);
ButtonGroup modelRadioGroup = new ButtonGroup();
while (rs.next()) {
JRadioButton radio = new JRadioButton(rs.getString(str));
radio.addActionListener(new radioButtonActionPerformed());
modelRadioGroup.add(radio);
intoModels[paneNum].add(radio);
}
intoModels[paneNum].setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
panelsTab[tabNum].add(intoModels[paneNum]);
}
And a listener code:
public class radioButtonActionPerformed implements ActionListener {
public void actionPerformed(ActionEvent e){
System.out.println("Selected radio: " + e.getActionCommand());
selectedModel = e.getActionCommand();
}
}
The interface:
I can get selected radio, but I can't register from which panel. So I need to register the panel and save selected to the array on indexes 0 and 1 for the first and second panel.
Have you tried component.getParent() method to get the parent.
public void actionPerformed(ActionEvent e) {
Object src=e.getSource();
if(src instanceof JRadioButton){
Container parent=((JRadioButton)src).getParent();
if(parent instanceof JPanel){
System.out.println(parent.getName());
}
}
}

Java code needs to restrict the user input

I got a serious problem on my code.
I got a swing JDBC code which I need to fill a table of names, addresses and an ID for the person, different than the table's ID. I created a swing input code for it, however, I wish it NOT to include the ID number's possibility - therefore, to make the swing have nothing else but the name and address being able to be set by the used, and not to show the ID at all.
Is there a possibility for it?
The creation of new partner, which has the name, address and the IdentityNumber strings, all private and their getters and setters public.
{
protected final String FRAME_TITLE = "Vehicle Repository";
private DatabaseHandler dbHandler;
private JTabbedPane tabbedPane;
private JTable partnerTable;
private JpaControlledTableModel<Partner> partnerTableModel;
#Override
public void onCreate() {
setDefaults(FRAME_TITLE);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
dbHandler = new DatabaseHandler();
dbHandler.open();
tabbedPane = new JTabbedPane();
partnerTableModel = new AsyncFullQueryingTableModel<>(dbHandler.getPartnerJpaController(), dbHandler.getEntityClassesToControllersMap());
parterTable = new JTable(partnerTableModel);
tabbedPane.addTab("Partners", new JScrollPane(parterTable));
getContentPane().add(tabbedPane, BorderLayout.CENTER);
}
#Override
public JMenuBar createJMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Data");
menuBar.add(menu);
JMenuItem menuItem;
menuItem = new JMenuItem(newPartnerAction);
menu.add(menuItem);
return menuBar;
}
private Action newPartnerAction = new AbstractAction("New parnter") {
#Override
public void actionPerformed(ActionEvent e) {
Partner partner = new Partner();
EntityEditorDialog<Partner> editorDialog = EntityEditorDialogFactory.createEditorDialog(partner, dbHandler.getPartnerJpaController());
editorDialog.setVisible(true);
if (partner.getId() != null) {
partnerTableModel.refresh();
}
}
};
private String getString(String message) {
return JOptionPane.showInputDialog(rootPane, message, "Data input", JOptionPane.QUESTION_MESSAGE);
}
private Partner getPartner(String message) {
Object[] partners = dbHandler.getPartnerJpaController().findEntities().toArray();
if (partners.length == 0) {
return null;
} else {
return (Partner) JOptionPane.showInputDialog(rootPane, message, "Data input", JOptionPane.QUESTION_MESSAGE, null, partners, partners[0]);
}
}
#Override
public void dispose() {
dbHandler.close();
super.dispose();
}
}
};
and not to show the ID at all
You can remove a column from display in the JTable:
table.removeColumn( table.getColumn(...) );

JComboBox show value

Need help with JComboBox component. I've load data from MySQL database and write this data into combo. I use four combo boxes with ItemListener. When one combo box change all children combo boxes reload data from database. First and two works fine but third and four don't show value normal, but good value is there. Only I don't show it. When I select empty field in combo box after then I see good result.
Source code:
public class Vyhladat extends Okno {
private static final long serialVersionUID = 1L;
JComboBox nominalBOX,statBOX,podpisBOX,tlacDoskaBOX;
Font sherif = new Font("Sherif",Font.BOLD,20);
Font normal = new Font("Sherif",Font.PLAIN,20);
JFrame uh = new JFrame();
private String adresa="jdbc:mysql://localhost:3306/jarodb";
private String meno="JKARAK";
private String heslo="bankovka";
String nominal,stat,podpis,tlacDoska,statH;
private String nominalSQL = "SELECT DISTINCT(nominal) FROM prehlad";
private String statSQL = "SELECT DISTINCT(concat(stat,'/',seria)) FROM prehlad WHERE nominal=? ORDER BY stat";
private String podpisSQL = "SELECT DISTINCT(podpis) FROM prehlad WHERE nominal=? AND stat=? ";
private String tlacDoskaSQL = "SELECT DISTINCT(doska) FROM prehlad WHERE nominal=? AND stat=? AND podpis=? ";
Vector nominalV=new Vector();
Vector statV=new Vector();
Vector podpisV=new Vector();
Vector tlacDoskaV=new Vector();
Vyhladat()
{
vlozPopis(nominalLAB,"NOMIN\u00C1L EUROBANKOVKY: ",0,0,sherif);
vlozPopis(statLAB,"\u0160T\u00C1T/S\u00C9RIA:",0,1,sherif);
vlozPopis(podpisLAB,"PODPIS:",0,2,sherif);
vlozPopis(tlacDoskaLAB,"TLA\u010COV\u00C1 DOSKA:",0,3,sherif);
gbc.gridx=1;
gbc.gridy=0;
nacitajVyber(nominalSQL,nominalBOX,nominalV,false,false,false);
nominalBOX = new JComboBox(nominalV);
nominalBOX.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
nominal = (String)nominalBOX.getSelectedItem();
if(nominal!=" ")
{
nacitajVyber(statSQL,statBOX,statV,true,false,false);
}
else{
statBOX.removeAllItems();
podpisBOX.removeAllItems();
tlacDoskaBOX.removeAllItems();
}
}
});
nominalBOX.setPrototypeDisplayValue("500");
nominalBOX.setFont(normal);
nominalBOX.setSelectedIndex(0);
nominalBOX.setToolTipText("Vyber z mo\u017Enost\u00ED nomin\u00E1lu bankoviek 5,10,20,50.");
add(nominalBOX,gbc);
gbc.gridx=1;
gbc.gridy=1;
statV.add(" ");
statBOX= new JComboBox(statV);
statBOX.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
stat = (String)statBOX.getSelectedItem();
if(stat!=null)
{
String [] statM= stat.split("/");
statH = statM[0];
}
if(stat!=" " & stat!=null)
{
nacitajVyber(podpisSQL,podpisBOX,podpisV,false,true,false);
}
else{
podpisBOX.removeAllItems();
tlacDoskaBOX.removeAllItems();
}
}
});
statBOX.setPrototypeDisplayValue("Portugalsko/E");
statBOX.setFont(normal);
statBOX.setSelectedIndex(0);
statBOX.setToolTipText("Vyber z mo\u017Enost\u00ED \u0161t\u00E1t/s\u00E9riu.");
add(statBOX,gbc);
gbc.gridx=1;
gbc.gridy=2;
podpisV.add(" ");
podpisBOX = new JComboBox(podpisV);
podpisBOX.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
podpis = (String)podpisBOX.getSelectedItem();
if(podpis!=" " & podpis!=null)
{
nacitajVyber(tlacDoskaSQL,tlacDoskaBOX,tlacDoskaV,false,false,true);
}
else{
tlacDoskaBOX.removeAllItems();
}
}
});
podpisBOX.setPrototypeDisplayValue("Jean-Claude Trichet ");
podpisBOX.setFont(normal);
podpisBOX.setSelectedIndex(0);
podpisBOX.setToolTipText("Vyber z mo\u017Enost\u00ED troch podpisov.");
add(podpisBOX,gbc);
gbc.gridx=1;
gbc.gridy=3;
tlacDoskaV.add(" ");
tlacDoskaBOX = new JComboBox(tlacDoskaV);
tlacDoskaBOX.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
tlacDoska = (String)tlacDoskaBOX.getSelectedItem();
if((nominal!=" " & nominal!=null) & (statH!=" " & statH!=null) & (podpis!=" " & podpis!=null) & (tlacDoska!=" " & tlacDoska!=null))
{
zobraz.setEnabled(true);
}
}
});
tlacDoskaBOX.setPrototypeDisplayValue("E010");
tlacDoskaBOX.setFont(normal);
tlacDoskaBOX.setSelectedIndex(0);
tlacDoskaBOX.setToolTipText("Vyber z mo\u017Enost\u00ED tla\u010Dov\u00FDch dosiek.");
add(tlacDoskaBOX,gbc);
}
private void nacitajVyber(String sqlDotaz, JComboBox chr,Vector v,
boolean jedna,boolean dva, boolean tri)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(adresa,meno,heslo);
PreparedStatement stmt = conn.prepareStatement(sqlDotaz);
if(jedna==true)
{
chr.removeAllItems();
stmt.setString(1, nominal);
}
if(dva==true)
{
chr.removeAllItems();
stmt.setString(1, nominal);
stmt.setString(2, statH);
}
if(tri==true)
{
chr.removeAllItems();
stmt.setString(1, nominal);
stmt.setString(2, statH);
stmt.setString(3, podpis);
}
ResultSet rs = stmt.executeQuery();
v.addElement(" ");
while (rs.next())
{v.addElement(rs.getString(1).trim());
System.out.println(rs.getString(1));}
validate();
rs.close();
stmt.close();
conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(uh,e.toString(),
"Chyba pripojenia",
JOptionPane.ERROR_MESSAGE);
}
}
}
JComboBox doesn't know somehow then underlaying Vector is changed, have to reinitialize this array for JComboBox on the fly, but this is wrong way,
for any changes on the runtime to use XxxComboBoxModel for storing Items for JComboBox
for JDBC or FileIO there could be Concurency issue, Swing JComponents required to all updates (in this case JComboBox and its XxxComboBoxModel) must be done on EDT
invoke Database event from the Runnable#Thread or SwingWorker, redirect this (potentionally) hard and long running task to the Workers Thread, otherwise Swing GUi will be freeze or unresponsive (for mouse and key events) untill JDBC ended
SwingWorkers methods publish(), process() and done() quite good quaranteed that all output wil be done on EDT
for example
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JFrame implements ActionListener, ItemListener {
private static final long serialVersionUID = 1L;
private JComboBox mainComboBox;
private JComboBox subComboBox;
private Hashtable<Object, Object> subItems = new Hashtable<Object, Object>();
public ComboBoxTwo() {
String[] items = {"Select Item", "Color", "Shape", "Fruit"};
mainComboBox = new JComboBox(items);
mainComboBox.addActionListener(this);
mainComboBox.addItemListener(this);
//prevent action events from being fired when the up/down arrow keys are used
//mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
getContentPane().add(mainComboBox, BorderLayout.WEST);
subComboBox = new JComboBox();// Create sub combo box with multiple models
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
subComboBox.addItemListener(this);
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);
// mainComboBox.setSelectedIndex(1);
}
#Override
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));
}
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if (e.getSource() == mainComboBox) {
if (mainComboBox.getSelectedIndex() != 0) {
FirstDialog firstDialog = new FirstDialog(ComboBoxTwo.this,
mainComboBox.getSelectedItem().toString(), "Please wait, Searching for ..... ");
}
}
}
}
private class FirstDialog extends JDialog { //sipmle simulation of JDBC events, by using Swing Timer
private static final long serialVersionUID = 1L;
FirstDialog(final Frame parent, String winTitle, String msgString) {
super(parent, winTitle);
setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
JLabel myLabel = new JLabel(msgString);
JButton bNext = new JButton("Stop Processes");
add(myLabel, BorderLayout.CENTER);
add(bNext, BorderLayout.SOUTH);
bNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
t.setRepeats(false);
t.start();
setLocationRelativeTo(parent);
setSize(new Dimension(400, 100));
setVisible(true);
}
}
public static void main(String[] args) {
JFrame frame = new ComboBoxTwo();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The GUI probably can't redraw properly. You are doing all of your hard work on the Event Dispatch Thread. This thread calls your itemStateChanged. But this thread is also responsible for redrawing the GUI. You are stopping it from doing that, because you are making it do your hard work in the database.
Instead, you can use a different thread to do your hard work.
public void itemStateChanged(ItemEvent e)
{
new Thread(new Runnable() {
public void run() {
.... your code...
}
}).start();
}
Or take a look at SwingWorker, which does this in a nicer way.
Also, itemStateChanged could be called twice for each selection - this might be causing you problems. Use "e.getStateChange()" to check what TYPE of event you just received. You should receive a selected and an unselected (from the old item).

Categories