java JComboBox issue - java

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))

Related

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.

JCombobox change another JCombobox values from mysql database

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();
}
});
}
}

Changing Columns in JTable using JRadioButtons doesn't refresh structure

I've removed most of my GUI to keep the code short.
I have a buttongroup of 3 JRadioButtons to select the table schema i want to display in my JTable, which is contained in a JScrollPane
I have tried to use fireTableStructureChanged() andfireTableDataChanged() as well as JTable.repaint() to no avail. Can anyone help me?
Here is a simple example that runs a window with my configuration but does not update the table.
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel();
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
mainPanel.setSize(1260, 630);
mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
coursesBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.setOpaque(true);
tableRadioPanel.setBounds(0, 0, 150, 70);
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(160, 0, 1016, 558);
//table code end
mainPanel.add(tableRadioPanel);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1260, 630);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.getContentPane().add(vicu.getMainPanel());
frame.getContentPane().setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}
In your example, you are not registering an ActionListener to profsBtn or officeSpBtn, you keep registering to coursesBtn
JRadioButton coursesBtn = new JRadioButton("Courses");
//...
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
//...
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
//...
coursesBtn.addActionListener(this);
Once I register the ActionListener to the correct buttons, it works fine
The problem seems to be that the code adds the listener 3 times to a single button, rather than once each to each of the 3 buttons!
..my application is for a very limited scope and can do without a layout manager for my purposes, unless you think this is affecting the table's behaviour?
No, not the table. It was however causing the emptyLabel to be assigned no space in the layout. Here is a robust, resizable version of the GUI.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.util.*;
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel(new BorderLayout(5,5));
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
mainPanel.setBorder(new EmptyBorder(5,5,5,5));
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
//mainPanel.setSize(1260, 630);
//mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
profsBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
officeSpBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollPane.setBounds(160, 0, 1016, 558);
//table code end
JPanel gridConstrain = new JPanel();
gridConstrain.add(tableRadioPanel);
mainPanel.add(gridConstrain, BorderLayout.LINE_START);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("Empty Label");
emptyLabel.setFont(emptyLabel.getFont().deriveFont(80f));
//emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.PAGE_START);
frame.getContentPane().add(vicu.getMainPanel());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Event: " + e);
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}

JTable not rendering JCheckBox or JComboBox in the table in Java Applet

Im having trouble getting my JTable that im using to display either check boxes or combo boxes in my applet.
Here is the code that is not working correctly
String[] options = {"download", "ignore"};
Object[] obj = {new JComboBox(options), ((MetadataList)array.get(1)).getMetadata("Filename").getValue()};
defaultTableModel2.addRow(obj);
The defaultTableModel2 is simply a DefaultTableModel defaultTabelModel2 = new DefaultTableModel() so nothing too dramatic there. The code above is using a JComboBox, but I have also tried using a JCheckBox as well and the same issues were present.
javax.swing.JComboBox[,0,0,0x0,invalid,layout=javax.swing.plaf.basic.BasicComboBoxUI$Handler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.synth.SynthBorder#8380df,flags=320,maximumSize=,minimumSize=,preferredSize=,isEditable=false,lightWeightPopupEnabled=true,maximumRowCount=8,selectedItemReminder=download]
is what appears instead of a JComboBox
Any help would be greatly appreciated!
For example:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
#SuppressWarnings("serial")
public class TableJunk extends JPanel {
enum Day {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}
MyTableModel tableModel = new MyTableModel();
private JTable myTable = new JTable(tableModel);
public TableJunk() {
setLayout(new BorderLayout());
add(new JScrollPane(myTable));
Object[] rowData = {Day.MONDAY, Boolean.TRUE};
tableModel.addRow(rowData );
rowData = new Object[]{Day.TUESDAY, Boolean.TRUE};
tableModel.addRow(rowData );
rowData = new Object[]{Day.WEDNESDAY, Boolean.TRUE};
tableModel.addRow(rowData );
rowData = new Object[]{Day.THURSDAY, Boolean.TRUE};
tableModel.addRow(rowData );
rowData = new Object[]{Day.FRIDAY, Boolean.TRUE};
tableModel.addRow(rowData );
rowData = new Object[]{Day.SATURDAY, Boolean.FALSE};
tableModel.addRow(rowData );
rowData = new Object[]{Day.SUNDAY, Boolean.FALSE};
tableModel.addRow(rowData );
// create the combo box for the column editor
JComboBox<Day> comboBox = new JComboBox<TableJunk.Day>(Day.values());
myTable.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(comboBox));
}
private static void createAndShowGui() {
TableJunk mainPanel = new TableJunk();
JFrame frame = new JFrame("TableJunk");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
private static class MyTableModel extends DefaultTableModel {
private static final String[] COLUMN_NAMES = {"Day", "Work Day"};
public MyTableModel() {
super(COLUMN_NAMES, 0);
}
// this method will allow the check box to be rendered in the 2nd column
public java.lang.Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 0) {
return Day.class;
} else if (columnIndex == 1) {
return Boolean.class;
} else {
return super.getColumnClass(columnIndex);
}
};
}
}

Categories