Hello Again,
Yet another road block in my destination to completing my program. I wanted to create a MultiColumn Combobox and needed to store my Database values into an array so I get get them into the Combobox. I'm having trouble getting this code to work properly. It seems that the the combobox wont accept the variable items maybe because it is outside the scope? I tried to move the code around to get it to work but it don't.
here is the code.
package pms;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class Test3 extends JFrame {
public static void main(String[] args) {
new Test3();
}
public Test3() {
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.setBackground(Color.gray);
DBConnection db = new DBConnection();
try {
Connection conn = DriverManager.getConnection(db.connUrl);
Statement sql = conn.createStatement();
ResultSet rs = sql.executeQuery("SELECT * FROM Referrals ORDER BY Referral_Text");
while (rs.next()) {
Item[] items = {
new Item(rs.getString(2), rs.getString(2)),};
}
JComboBox jcb = new JComboBox(items);
//Close connections.
rs.close();
sql.close();
conn.close();
} catch (SQLException e) {
e.getStackTrace();
}
jcb.setPreferredSize(new Dimension(24, 24));
jcb.setRenderer(new ItemRenderer());
c.add(jcb, BorderLayout.NORTH);
setSize(200, 100);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
// The items to display in the combobox...
class Item {
String itemName = "";
String itemValue = "";
public Item(String name, String value) {
itemName = name;
itemValue = value;
}
}
// The combobox's renderer...
class ItemRenderer extends JPanel implements ListCellRenderer {
private JLabel nameLabel = new JLabel(" ");
private JLabel valueLabel = new JLabel(" ");
public ItemRenderer() {
setOpaque(true);
setLayout(new GridLayout(1, 2));
add(nameLabel);
add(valueLabel);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
nameLabel.setText(((Item) value).itemName);
valueLabel.setText(((Item) value).itemValue);
if (isSelected) {
setBackground(Color.black);
nameLabel.setForeground(Color.white);
valueLabel.setForeground(Color.white);
} else {
setBackground(Color.white);
nameLabel.setForeground(Color.black);
valueLabel.setForeground(Color.black);
}
return this;
}
}
}
Thanks!