Get Value from JComboBox - java

I have JComboBox with 2 columns and I have JButton. When I click the JButton, I need to get the result of the JComboBox selected value from first column and seconds column separately...
How do I this?
Also: how do I set the header of that JComboBox ?
The Code:
public class Combo extends JFrame implements ActionListener{
private JComboBox combo = new JComboBox();
private JButton button = new JButton();
public Combo() {
setLayout(new FlowLayout());
combo.setRenderer(new render());
add(combo);
combo.addItem(new String[] {"1","bbb"});
combo.addItem(new String[] {"2","ff"});
combo.addItem(new String[] {"3","gg"});
combo.addItem(new String[] {"4","ee"});
add(button);
button.addActionListener(this);
pack();
}
public static void main(String[]args){
new Combo().setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button){
System.out.println(combo.getSelectedItem());
}
}
}
class render extends JPanel implements ListCellRenderer{
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private JLabel label3 = new JLabel();
private JLabel label4 = new JLabel();
private JLabel label5 = new JLabel();
public render() {
setLayout(new GridLayout(2,5));
add(label1);
add(label2);
}
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String[] values = (String[]) value;
label1.setText(values[0]);
label2.setText(values[1]);
if(index ==0){
label1.setForeground(Color.red);
label2.setForeground(Color.red);
}else{
label1.setForeground(Color.white);
label2.setForeground(Color.white);
}
return this;
}
}
Thanks.

Your items are arrays of strings, so you can print the selected item as follows:
System.out.println(Arrays.toString((String[])combo.getSelectedItem()));
EDIT:
String[] selectedItem = (String[])combo.getSelectedItem();
for (int i = 0; i < selectedItem.length; i++){
System.out.println(String.format("item %s = %s", i, selectedItem[i]));
}
Or shortly if all you need is the first item - (String[])combo.getSelectedItem())[0].

To display the first value of the selected element, you could use:
System.out.println(((String[])combo.getSelectedItem())[0]);

I think this could be easier than the previous answers:
(String) comboBox.getSelectedItem();

Related

JScrollPane "stretching" out the panel that I add to it

I have to make a scrollable list where I can add a panel with 3 labels many times.
I kind of made it work but the first panels are stretched and occupy all the area of the JScrollPane and I can't figure out how to fix this, I tried changing layouts many times but still didn't manage to fix it.
I want the added panel to occupy a fixed size but I can't figure this out. Example in this picture:
https://i.stack.imgur.com/LNznP.png
The one on the left is the one that I get and the one on the right (edited) is how I want it to work.
This is my first day of Swing so the code is very likely a mess, sorry in advance.
Here is the code:
public class MainWindow extends JFrame implements ActionListener{
private JPanel viewportPanel;
private JButton addButton,remButton;
private JScrollPane scrollPane;
private int counter = 0;
private JLabel dateLabel,dateLabel_1,dateLabel_2;
public MainWindow(boolean run) {
//BUTTONS
addButton = new JButton("Add");
addButton.setLocation(521, 11);
addButton.setSize(101, 100);
addButton.addActionListener(this);
remButton = new JButton("Remove");
remButton.setLocation(521, 122);
remButton.setSize(101, 100);
remButton.addActionListener(this);
//SCROLLPANE
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 11, 501, 211);
add(scrollPane);
//PANELS
viewportPanel = new JPanel(new GridLayout(0,1));
scrollPane.setViewportView(viewportPanel);
//FRAME
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 273);
setResizable(false);
//setIconImage(new ImageIcon("epic.png").getImage());
setLayout(null);
if(run) setVisible(true);
add(addButton);
add(remButton);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addButton) {
//LABELS
dateLabel = new JLabel("DATE");
dateLabel.setFont(new Font("Tahoma", Font.BOLD, 28));
dateLabel.setSize(500,500);
dateLabel_1 = new JLabel("LABEL1");
dateLabel_1.setFont(new Font("Tahoma", Font.BOLD, 22));
dateLabel_1.setBounds(10, 45, 481, 30);
dateLabel_2 = new JLabel("LABEL2");
dateLabel_2.setFont(new Font("Tahoma", Font.ITALIC, 22));
dateLabel_2.setBounds(10, 45, 481, 30);
//PANEL WITH ALL THE STUFF
JPanel componentPanel = new JPanel();
componentPanel.setLayout(new GridLayout(3, 1));
componentPanel.setMaximumSize(new Dimension(50,50));
componentPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
componentPanel.setBackground(Color.gray);
componentPanel.add(dateLabel);
componentPanel.add(dateLabel_1);
componentPanel.add(dateLabel_2);
viewportPanel.add(componentPanel); //add panel with labels to viewportpanel
counter++;
}
if(e.getSource() == remButton) {
Component[] componentList = viewportPanel.getComponents();
int lastElement = (componentList.length);
viewportPanel.remove(--lastElement);
--counter;
}
viewportPanel.revalidate();
viewportPanel.repaint();
}
}
Some help would be amazing!
First off, never do this:
setLayout(null);
Next, if you want things compressed at the top of a container, then use a layout that does this. such as a BorderLayout with the compressed items placed into a JPanel (perhaps one that uses a GridLayout) that is placed BorderLayout.PAGE_START
Actually, it looks as if your best solution is to us a JList, one that uses a custom renderer that places your time JLabel and two text JLabels into a JPanel and displays this in the list. So let's explore that.
First create a class to hold the data that is displayed by the JList, which looks to be a date and two lines of text:
public class ListItem {
private LocalDate date;
private String text1;
private String text2;
public ListItem(LocalDate date, String text1, String text2) {
super();
this.date = date;
this.text1 = text1;
this.text2 = text2;
}
public LocalDate getDate() {
return date;
}
public String getText1() {
return text1;
}
public String getText2() {
return text2;
}
}
Then let's create a renderer that a JList can use to display the above information in a JPanel. This is more complicated and requires that the class create a JPanel that places the labels where we want them, perhaps using a GridLayout with 1 column and 3 rows, plus some gaps between the rows: setLayout(new GridLayout(3, 1, 2 * gap, 2 * gap));. The class must implement the ListCellRenderer<T> interface which has one method: public Component getListCellRendererComponent(...). Java will pass in the paramters into this method, including a ListItem value, and we will use that value to fill in the JLabels that we add into this JPanel. Edited to highlight selected items.
import java.awt.*;
import java.time.format.DateTimeFormatter;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class ListItemRenderer extends JPanel implements ListCellRenderer<ListItem> {
private static final Color LIGHT_BLUE = new Color(204, 255, 255);
private static final Color REDDISH_GREY = new Color(205, 126, 121);
private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
private static final int GAP = 2;
private Border emptyBorder = BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP);
private Border blackBorder = BorderFactory.createLineBorder(Color.BLACK);
private Border redBorder = BorderFactory.createLineBorder(REDDISH_GREY, 2);
private JLabel dateLabel = new JLabel();
private JLabel text1Label = new JLabel();
private JLabel text2Label = new JLabel();
public ListItemRenderer() {
dateLabel.setFont(dateLabel.getFont().deriveFont(Font.BOLD, 14f));
text1Label.setFont(text1Label.getFont().deriveFont(Font.BOLD));
text2Label.setFont(text1Label.getFont().deriveFont(Font.ITALIC));
int gap = 2;
setLayout(new GridLayout(0, 1, 2 * gap, 2 * gap));
setBorder(BorderFactory.createCompoundBorder(emptyBorder, blackBorder));
add(dateLabel);
add(text1Label);
add(text2Label);
}
#Override
public Component getListCellRendererComponent(JList<? extends ListItem> list, ListItem value, int index,
boolean isSelected, boolean cellHasFocus) {
if (value != null) {
String dateText = dateFormatter.format(value.getDate());
dateLabel.setText(dateText);
text1Label.setText(value.getText1());
text2Label.setText(value.getText2());
} else {
dateLabel.setText("");
text1Label.setText("");
text2Label.setText("");
}
if (isSelected ) {
setBackground(LIGHT_BLUE);
setBorder(BorderFactory.createCompoundBorder(emptyBorder, redBorder));
} else {
setBackground(null);
setBorder(BorderFactory.createCompoundBorder(emptyBorder, blackBorder));
}
return this;
}
}
And now the main program that puts this all together, edited to show removing items:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class MainPanel extends JPanel {
DefaultListModel<ListItem> listModel = new DefaultListModel<>();
private JList<ListItem> jList = new JList<>(listModel);
private JScrollPane scrollPane = new JScrollPane(jList);
private JButton addButton = new JButton("Add");
private JButton removeButton = new JButton("Remove");
public MainPanel() {
jList.setPrototypeCellValue(new ListItem(LocalDate.now(),
"This is text 1 for testing. This is text 1 for testing. This is text 1 for testing",
"This is text 2 for testing. This is text 2 for testing. This is text 2 for testing"));
jList.setVisibleRowCount(4);
jList.setCellRenderer(new ListItemRenderer());
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 3, 3));
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
addButton.setMnemonic(KeyEvent.VK_A);
removeButton.setMnemonic(KeyEvent.VK_R);
addButton.addActionListener(e -> addEvent());
removeButton.addActionListener(e -> removeEvent());
JPanel rightPanel = new JPanel();
rightPanel.add(buttonPanel);
int gap = 5;
setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
setLayout(new BorderLayout());
add(scrollPane);
add(rightPanel, BorderLayout.LINE_END);
}
private void removeEvent() {
int[] selectedIndices = jList.getSelectedIndices();
for (int i = selectedIndices.length - 1; i >= 0; i--) {
listModel.remove(selectedIndices[i]);
}
}
private void addEvent() {
// this adds random stuff to the JList
String text1 = "Some random text: " + randomText();
String text2 = "Some random text: " + randomText();
listModel.addElement(new ListItem(LocalDate.now(), text1, text2));
// TODO: change this so that it adds *real* data to the JList
}
private String randomText() {
Random random = new Random();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 2 + random.nextInt(3); i++) {
for (int j = 0; j < 3 + random.nextInt(5); j++) {
char c = (char) ('a' + random.nextInt('z' - 'a'));
builder.append(c);
}
builder.append(" ");
}
return builder.toString();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Output would look like:

DefaultListModel and jList1.setModel not working [duplicate]

I'm trying to create a simple program to manage Employees. When trying to add a new employee I can't seem to get the employee to be displayed on the Jlist.
The main frame...
public class EmployeeFrame extends JFrame implements ActionListener {
// The buttons to display
private JButton addButton;
private JButton editButton;
private JButton deleteButton;
private JButton saveButton;
// The underlying list of employees, and the GUI object to display them
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public static final String SAVE_FILE = "employees.txt";
/**
* Creates and displays a new EmployeeFrame. The program exits when the
* window is closed.
*/
public EmployeeFrame() {
// Basic window features
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Try to make it look like a native application -- using try/multi-catch
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
// Initialise an empty list model, a JList to display it, and a scroll
// pane to contain the list
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
// Initialise all buttons and add the current class as an action
// listener to all
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
editButton = new JButton("Edit Employee");
editButton.addActionListener(this);
deleteButton = new JButton("Delete Employee");
deleteButton.addActionListener(this);
saveButton = new JButton("Save Employee List");
saveButton.addActionListener(this);
// Lay out the buttons in a line
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(editButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(deleteButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(saveButton);
// Lay out the window
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
// Determine which button was pushed
Object source = event.getSource();
// Here's what to do with the delete button
if (source == deleteButton) {
Employee selection = employeeList.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
}
}
if (source == addButton) {
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
frame.setVisible(true);
}
}
public static void main(String[] args) {
new EmployeeFrame().setVisible(true);
}
}
The dialogue that adds the employee...
public class AddEmployeeDialog extends JDialog implements ActionListener {
// Common fields
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JDatePicker startDatePicker;
// Fields that depend on the employee type
private JTextField rateField;
private JTextField hoursField;
private JTextField salaryField;
// Buttons
private JButton okButton;
private JButton cancelButton;
// The employee frame -- used to position the dialog and to access the
// employee list
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
// Basic initialisation
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
// Common fields
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
startDatePicker = new JDateComponentFactory().createJDatePicker();
// Fields only for hourly workers
rateField = new JTextField(10);
hoursField = new JTextField(5);
// Field only for salaried worker
salaryField = new JTextField(10);
// Top line
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
workerBox.add((JPanel) startDatePicker);
// Next lines (names)
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
// Hourly-worker fields
Box hourlyBox = Box.createHorizontalBox();
hourlyBox.setBorder(new TitledBorder("Hourly worker information"));
hourlyBox.add(new JLabel("Rate"));
hourlyBox.add(rateField);
hourlyBox.add(Box.createHorizontalStrut(10));
hourlyBox.add(new JLabel("Hours"));
hourlyBox.add(hoursField);
// Salaried-worker fields
Box salariedBox = Box.createHorizontalBox();
salariedBox.setBorder(new TitledBorder("Salaried worker information"));
salariedBox.add(new JLabel("Salary"));
salariedBox.add(salaryField);
// Ensure that only the appropriate fields are enabled, depending on the
// worker type chosen
workerType.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent arg0) {
String type = (String) workerType.getSelectedItem();
salaryField.setEnabled("Salaried".equals(type));
rateField.setEnabled("Hourly".equals(type));
hoursField.setEnabled("Hourly".equals(type));
}
});
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
// Bottom row of GUI: buttons
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(hourlyBox);
getContentPane().add(salariedBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
// Convert the value from the date picker into a LocalDate
GregorianCalendar startDateValue = (GregorianCalendar) startDatePicker.getModel().getValue();
LocalDate startDate = startDateValue.toZonedDateTime().toLocalDate();
// Work out which button was pressed
Object source = event.getSource();
if (source == cancelButton) {
// Just close the window
dispose();
}
if (source == okButton) {
// Determine if the employee is hourly or salaried
if (workerType.getSelectedItem().toString() == "Salaried") {
// Create new salaried employee
if (salaryField.getText().matches("[0-9]+")) {
Employee employee = new SalariedEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(salaryField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
else {
// Create new hourly employee
if (rateField.getText().matches("[0-9]+") && hoursField.getText().matches("[0-9]+")) {
Employee employee = new HourlyEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(rateField.getText()),
Integer.parseInt(hoursField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
}
This is what I'm using to add the employee
employeeFrame.getListModel().addElement(employee);
I think this is the right method but it doesn't seem to work. Any help will really be appreciated.
Two problems,
The first:
bad: if (workerType.getSelectedItem().toString() == "Salaried") {. Use equals(...) or equalsIgnoreCase(...). Understand that == checks for reference equality which is most definitely not what you're interested in. You want functional equality which is what the methods test for.
So: if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
The second:
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
You're passing in a new EmployeeFrame object meaning you're updating the list model for the wrong EmployeeFrame. Instead pass in the visualized EmployeeFrame.
Change it to:
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
My program that I created to shrink your code but still allow it to be runnable and to demonstrate your problem:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class EmployeeFrame extends JFrame implements ActionListener {
private JButton addButton;
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public EmployeeFrame() {
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == addButton) {
// !! AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
frame.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EmployeeFrame().setVisible(true);
}
});
}
}
#SuppressWarnings("serial")
class AddEmployeeDialog extends JDialog implements ActionListener {
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JButton okButton;
private JButton cancelButton;
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == okButton) {
System.out.println("here");
System.out.println(workerType.getSelectedItem());
if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
Employee employee = new Employee("Salaried", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
} else {
Employee employee = new Employee("Hourly", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
class Employee {
private static final String[] EMPLOYEE_TYPES = { "Salaried", "Hourly" };
private String givenName;
private String familyName;
private String type;
public Employee(String type, String givenName, String familyName) {
this.type = type;
this.givenName = givenName;
this.familyName = familyName;
}
public static String[] getEmployeeTypes() {
return EMPLOYEE_TYPES;
}
public String getGivenName() {
return givenName;
}
public String getFamilyName() {
return familyName;
}
public String getType() {
return type;
}
#Override
public String toString() {
return String.format("Employee: %s, %s %s", type, givenName, familyName);
}
}

JList not updating when adding element to DefaultListModel

I'm trying to create a simple program to manage Employees. When trying to add a new employee I can't seem to get the employee to be displayed on the Jlist.
The main frame...
public class EmployeeFrame extends JFrame implements ActionListener {
// The buttons to display
private JButton addButton;
private JButton editButton;
private JButton deleteButton;
private JButton saveButton;
// The underlying list of employees, and the GUI object to display them
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public static final String SAVE_FILE = "employees.txt";
/**
* Creates and displays a new EmployeeFrame. The program exits when the
* window is closed.
*/
public EmployeeFrame() {
// Basic window features
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Try to make it look like a native application -- using try/multi-catch
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
// Initialise an empty list model, a JList to display it, and a scroll
// pane to contain the list
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
// Initialise all buttons and add the current class as an action
// listener to all
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
editButton = new JButton("Edit Employee");
editButton.addActionListener(this);
deleteButton = new JButton("Delete Employee");
deleteButton.addActionListener(this);
saveButton = new JButton("Save Employee List");
saveButton.addActionListener(this);
// Lay out the buttons in a line
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(editButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(deleteButton);
topBox.add(Box.createHorizontalStrut(10));
topBox.add(saveButton);
// Lay out the window
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
// Determine which button was pushed
Object source = event.getSource();
// Here's what to do with the delete button
if (source == deleteButton) {
Employee selection = employeeList.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
}
}
if (source == addButton) {
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
frame.setVisible(true);
}
}
public static void main(String[] args) {
new EmployeeFrame().setVisible(true);
}
}
The dialogue that adds the employee...
public class AddEmployeeDialog extends JDialog implements ActionListener {
// Common fields
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JDatePicker startDatePicker;
// Fields that depend on the employee type
private JTextField rateField;
private JTextField hoursField;
private JTextField salaryField;
// Buttons
private JButton okButton;
private JButton cancelButton;
// The employee frame -- used to position the dialog and to access the
// employee list
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
// Basic initialisation
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
// Common fields
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
startDatePicker = new JDateComponentFactory().createJDatePicker();
// Fields only for hourly workers
rateField = new JTextField(10);
hoursField = new JTextField(5);
// Field only for salaried worker
salaryField = new JTextField(10);
// Top line
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
workerBox.add((JPanel) startDatePicker);
// Next lines (names)
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
// Hourly-worker fields
Box hourlyBox = Box.createHorizontalBox();
hourlyBox.setBorder(new TitledBorder("Hourly worker information"));
hourlyBox.add(new JLabel("Rate"));
hourlyBox.add(rateField);
hourlyBox.add(Box.createHorizontalStrut(10));
hourlyBox.add(new JLabel("Hours"));
hourlyBox.add(hoursField);
// Salaried-worker fields
Box salariedBox = Box.createHorizontalBox();
salariedBox.setBorder(new TitledBorder("Salaried worker information"));
salariedBox.add(new JLabel("Salary"));
salariedBox.add(salaryField);
// Ensure that only the appropriate fields are enabled, depending on the
// worker type chosen
workerType.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent arg0) {
String type = (String) workerType.getSelectedItem();
salaryField.setEnabled("Salaried".equals(type));
rateField.setEnabled("Hourly".equals(type));
hoursField.setEnabled("Hourly".equals(type));
}
});
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
// Bottom row of GUI: buttons
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(hourlyBox);
getContentPane().add(salariedBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
// Convert the value from the date picker into a LocalDate
GregorianCalendar startDateValue = (GregorianCalendar) startDatePicker.getModel().getValue();
LocalDate startDate = startDateValue.toZonedDateTime().toLocalDate();
// Work out which button was pressed
Object source = event.getSource();
if (source == cancelButton) {
// Just close the window
dispose();
}
if (source == okButton) {
// Determine if the employee is hourly or salaried
if (workerType.getSelectedItem().toString() == "Salaried") {
// Create new salaried employee
if (salaryField.getText().matches("[0-9]+")) {
Employee employee = new SalariedEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(salaryField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
else {
// Create new hourly employee
if (rateField.getText().matches("[0-9]+") && hoursField.getText().matches("[0-9]+")) {
Employee employee = new HourlyEmployee(givenNameField.getText(),
familyNameField.getText(),
startDate,
Double.parseDouble(rateField.getText()),
Integer.parseInt(hoursField.getText()));
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
}
This is what I'm using to add the employee
employeeFrame.getListModel().addElement(employee);
I think this is the right method but it doesn't seem to work. Any help will really be appreciated.
Two problems,
The first:
bad: if (workerType.getSelectedItem().toString() == "Salaried") {. Use equals(...) or equalsIgnoreCase(...). Understand that == checks for reference equality which is most definitely not what you're interested in. You want functional equality which is what the methods test for.
So: if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
The second:
AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
You're passing in a new EmployeeFrame object meaning you're updating the list model for the wrong EmployeeFrame. Instead pass in the visualized EmployeeFrame.
Change it to:
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
My program that I created to shrink your code but still allow it to be runnable and to demonstrate your problem:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
#SuppressWarnings("serial")
public class EmployeeFrame extends JFrame implements ActionListener {
private JButton addButton;
private DefaultListModel<Employee> listModel;
private JList<Employee> employeeList;
public EmployeeFrame() {
super("Employee Manager");
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
listModel = new DefaultListModel<>();
employeeList = new JList<>(listModel);
JScrollPane employeeScroll = new JScrollPane(employeeList);
employeeScroll.setBorder(new TitledBorder("Employee List"));
addButton = new JButton("Add Employee");
addButton.addActionListener(this);
Box topBox = Box.createHorizontalBox();
topBox.add(addButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topBox, BorderLayout.NORTH);
getContentPane().add(employeeScroll, BorderLayout.CENTER);
pack();
}
public DefaultListModel<Employee> getListModel() {
return this.listModel;
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == addButton) {
// !! AddEmployeeDialog frame = new AddEmployeeDialog(new EmployeeFrame());
AddEmployeeDialog frame = new AddEmployeeDialog(EmployeeFrame.this);
frame.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EmployeeFrame().setVisible(true);
}
});
}
}
#SuppressWarnings("serial")
class AddEmployeeDialog extends JDialog implements ActionListener {
private JComboBox<String> workerType;
private JTextField givenNameField;
private JTextField familyNameField;
private JButton okButton;
private JButton cancelButton;
private EmployeeFrame employeeFrame;
public AddEmployeeDialog(final EmployeeFrame frame) {
super(frame, "Add Employee", true);
setLocationRelativeTo(employeeFrame);
this.employeeFrame = frame;
workerType = new JComboBox<String>(Employee.getEmployeeTypes());
givenNameField = new JTextField(20);
familyNameField = new JTextField(20);
Box workerBox = Box.createHorizontalBox();
workerBox.add(new JLabel("Worker type"));
workerBox.add(workerType);
workerBox.add(new JLabel("Start date"));
Box givenNameBox = Box.createHorizontalBox();
givenNameBox.add(new JLabel("Given name "));
givenNameBox.add(givenNameField);
Box familyNameBox = Box.createHorizontalBox();
familyNameBox.add(new JLabel("Family name"));
familyNameBox.add(familyNameField);
workerType.setSelectedItem(null);
// Create buttons and add the current class as an ActionListener
okButton = new JButton("OK");
okButton.addActionListener(this);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
Box bottomBox = Box.createHorizontalBox();
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(okButton);
bottomBox.add(Box.createHorizontalGlue());
bottomBox.add(cancelButton);
bottomBox.add(Box.createHorizontalGlue());
// Lay out the GUI
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
getContentPane().add(workerBox);
getContentPane().add(givenNameBox);
getContentPane().add(familyNameBox);
getContentPane().add(Box.createVerticalStrut(10));
getContentPane().add(bottomBox);
pack();
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == okButton) {
System.out.println("here");
System.out.println(workerType.getSelectedItem());
if ("Salaried".equalsIgnoreCase(workerType.getSelectedItem().toString())) {
Employee employee = new Employee("Salaried", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
} else {
Employee employee = new Employee("Hourly", givenNameField.getText(), familyNameField.getText());
employeeFrame.getListModel().addElement(employee);
}
}
dispose();
}
}
class Employee {
private static final String[] EMPLOYEE_TYPES = { "Salaried", "Hourly" };
private String givenName;
private String familyName;
private String type;
public Employee(String type, String givenName, String familyName) {
this.type = type;
this.givenName = givenName;
this.familyName = familyName;
}
public static String[] getEmployeeTypes() {
return EMPLOYEE_TYPES;
}
public String getGivenName() {
return givenName;
}
public String getFamilyName() {
return familyName;
}
public String getType() {
return type;
}
#Override
public String toString() {
return String.format("Employee: %s, %s %s", type, givenName, familyName);
}
}

Trouble Updating AbstractTableModel from another Class

I'm trying to update a JTable that pulls in data from an ArrayList. I have two frames in my program. The first frame is a JTable (AbstractTableModel) that displays the contents of the ArrayList. I click the "New" button on that frame to bring up the second window, which lets me add to the aforementioned ArrayList. When I click my "Save" button, the second window closes and the first is supposed to refresh with the new row. I don't have any syntactical errors in my code, and it looks conceptually right. I think the first place to start troubleshooting would be in the NoteCntl class. I'm under the impression that getNoteTableUI() should update the view with the new data when it's called, but I'm stumped as to what's going on. I'm new to the concept of Model View Controller, but I'd like to follow that as closely as possible.
Here is the Controller class:
public class NoteCntl {
private NoteTableModel theNoteTableModel = new NoteTableModel();;
private NoteTableUI theNoteTableUI;
private NoteDetailUI theNoteDetailUI;
public NoteCntl(){
theNoteTableUI = new NoteTableUI(this);
}
public NoteTableModel getNoteTableModel(){
return theNoteTableModel;
}
public void getNoteDetailUI(Note theNote){
if (theNoteDetailUI == null || theNote == null){
theNoteDetailUI = new NoteDetailUI(this,theNote);
}
else{
theNoteDetailUI.setVisible(true);
}
}
public NoteTableUI getNoteTableUI(){
theNoteTableModel.fireTableDataChanged(); //why doesn't this do anything?
theNoteTableUI.setVisible(true);
return theNoteTableUI;
}
public void deleteNote(int noteToDelete){
theNoteTableModel.removeRow(noteToDelete);
}
}
The First UI (Table):
public class NoteTableUI extends JFrame{
NoteTableModel noteModel;
NoteCntl theNoteCntl;
JPanel buttonPanel;
JPanel tablePanel;
JTable theNoteTable;
JScrollPane theScrollPane;
JButton backButton;
JButton deleteButton;
JButton editButton;
JButton newButton;
public NoteTableUI(NoteCntl theParentNoteCntl){
theNoteCntl = theParentNoteCntl;
this.initComponents();
this.setSize(400, 500);
this.setLocationRelativeTo(null);
this.setTitle("NoteTableUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
buttonPanel = new JPanel();
tablePanel = new JPanel();
backButton = new JButton("Back");
newButton = new JButton("New");
newButton.addActionListener(new newButtonListener());
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new deleteButtonListener());
noteModel = theNoteCntl.getNoteTableModel();
theNoteTable = new JTable(theNoteCntl.getNoteTableModel());
theScrollPane = new JScrollPane(theNoteTable);
theNoteTable.setFillsViewportHeight(true);
tablePanel.add(theScrollPane);
buttonPanel.add(backButton);
buttonPanel.add(deleteButton);
buttonPanel.add(editButton);
buttonPanel.add(newButton);
this.getContentPane().add(buttonPanel, BorderLayout.NORTH);
this.getContentPane().add(tablePanel, BorderLayout.CENTER);
}
public class deleteButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int selectedRow = theNoteTable.getSelectedRow();
if (selectedRow == -1){
System.out.println("No row selected");
}
else{
noteModel.removeRow(selectedRow);
}
revalidate();
repaint();
}
}
public class newButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
NoteTableUI.this.setVisible(false);
NoteTableUI.this.theNoteCntl.getNoteDetailUI(null);
/*
NoteDetailCntl theNoteDetailCntl = new NoteDetailCntl();
lastRow++;
long newRow = lastRow;
noteModel.addRow(newRow, 0, "", "");
revalidate();
repaint();
*/
}
}
The 2nd UI (Detail editor)
public class NoteDetailUI extends JFrame{
private final int FRAME_WIDTH = 700;
private final int FRAME_HEIGHT = 500;
private final int FIELD_WIDTH = 10;
JButton saveButton;
JButton backButton;
JTextField idField;
JTextField dateField;
JTextField nameField;
JTextField descriptionField;
JTextArea noteDetail;
JLabel idLabel;
JLabel dateLabel;
JLabel nameLabel;
JLabel descriptionLabel;
JPanel buttonPanel;
JPanel textFieldPanel;
JPanel textAreaPanel;
JPanel mainPanel;
NoteTableModel theNoteTableModel;
NoteDetailCntl theNoteDetailCntl;
NoteCntl theNoteCntl;
Note theCurrentNote;
public NoteDetailUI(){
this.initComponents();
this.setSize(FRAME_WIDTH,FRAME_HEIGHT);
this.setLocationRelativeTo(null);
this.setTitle("NoteDetailUI");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public NoteDetailUI(NoteCntl parentNoteCntl, Note theSelectedNote){
theNoteCntl = parentNoteCntl;
theCurrentNote = theSelectedNote;
this.initComponents();
this.setSize(400,500);
this.setLocationRelativeTo(null);
this.setTitle("Note");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void initComponents(){
saveButton = new JButton("Save");
saveButton.addActionListener(new saveButtonListener());
backButton = new JButton("Back");
backButton.addActionListener(new backButtonListener());
idField = new JTextField(FIELD_WIDTH);
theNoteTableModel = new NoteTableModel();
idField.setText("10");
idField.setEditable(false);
dateField = new JTextField(FIELD_WIDTH);
dateField.setText("20131108");
nameField = new JTextField(FIELD_WIDTH);
nameField.setText("Untitled");
descriptionField = new JTextField(FIELD_WIDTH);
descriptionField.setText("not described");
idLabel = new JLabel("ID");
dateLabel = new JLabel("Date");
nameLabel = new JLabel("Name");
descriptionLabel = new JLabel("Description");
noteDetail = new JTextArea(25,60);
buttonPanel = new JPanel();
textFieldPanel = new JPanel();
textAreaPanel = new JPanel();
mainPanel = new JPanel(new BorderLayout());
buttonPanel.add(backButton);
buttonPanel.add(saveButton);
textFieldPanel.add(idLabel);
textFieldPanel.add(idField);
textFieldPanel.add(dateLabel);
textFieldPanel.add(dateField);
textFieldPanel.add(nameLabel);
textFieldPanel.add(nameField);
textFieldPanel.add(descriptionLabel);
textFieldPanel.add(descriptionField);
textAreaPanel.add(noteDetail);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(textFieldPanel, BorderLayout.NORTH);
mainPanel.add(textAreaPanel, BorderLayout.CENTER);
add(mainPanel);
}
public ArrayList<String> getNoteDetails(){
ArrayList<String> newData = new ArrayList<String>();
newData.add(idField.getText());
newData.add(dateField.getText());
newData.add(nameField.getText());
newData.add(descriptionField.getText());
return newData;
}
public class saveButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
/*
* Access the noteTableData array in NoteTableModel
* Add the newData fields in order
*/
if(theCurrentNote == null){
int newNoteNumber = Integer.parseInt(NoteDetailUI.this.idField.getText());
int newNoteDate = Integer.parseInt(NoteDetailUI.this.dateField.getText());
String newNoteName = NoteDetailUI.this.nameField.getText();
String newNoteDescription = NoteDetailUI.this.descriptionField.getText();
NoteDetailUI.this.theCurrentNote = new EssayNote(newNoteNumber,newNoteDate,newNoteName,newNoteDescription);
NoteDetailUI.this.setVisible(false);
NoteDetailUI.this.dispose();
NoteDetailUI.this.theNoteCntl.getNoteTableUI();
}
else{
//if it's a current Note
}
//Refresh the JTable
}
}
public class backButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
}
}
Thanks for all the help. I can provide the other classes if you want to just run the program and see what's happening, but I suspect it's either a problem with the fireTableDataChanged() call in the controller class or a problem with updating the contents of the ArrayList in the SaveButtonListener.

Prevent JComboBox rendering on update JLabel

I'm doing an application that play a video and in a JLabel i'm showing timecode of video. Also have a JCombobox that allows to change subtitles of the video.
That JCombobox has a ListCellRenderer that change default output of each item of combobox.
Problem is that each time the JLabel change its value the JCombobox is rendered again.
I think this is a waste of resources there is some way of change that behavior?.
There is the code relative to the JComboBox. The JLabel is modified by a swing.Timer each second.
JComboBox comboBox = new JComboBox<>();
comboBox.setEditable(false);
DefaultComboBoxModel<File> defaultComboBox = new DefaultComboBoxModel<>();
for (File f : Player.capitulo.getFicheros()) {
if (f.getAbsolutePath().endsWith(".srt")) {
System.out.println(f.getAbsolutePath());
defaultComboBox.addElement(f);
}
}
comboBox.setModel(defaultComboBox);
comboBox.setRenderer(new ListRenderer());
public class ListRenderer implements ListCellRenderer<File> {
protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
#Override
public Component getListCellRendererComponent(JList<? extends File> list,
File value, int index, boolean isSelected, boolean cellHasFocus) {
JLabel renderer = new JLabel();
// JLabel renderer = (JLabel) defaultRenderer
// .getListCellRendererComponent(list, value, index, isSelected,
// cellHasFocus);
if (value != null) {
Path p = value.toPath();
System.out.println(p.getParent());
String language = value.getName().trim().replace(".srt", "");
language = language.substring(language.lastIndexOf(".") + 1,
language.length());
// System.out.println(language.length());
if (language.length() == 3) {
renderer.setText(language);
} else {
renderer.setText("Subtitulo " + (index + 1));
}
}
return renderer;
}
}
UPDATED: Here is an example that reproduce the problem
Ok, here is SSCCE code. Doing the example i noticed that when JLabel es in the same line of JCombobox reproduce the same problem but when is in other line doesn't happen.
public class Example extends JFrame {
private JPanel contentPane;
private JLabel lblNewLabel;
private JComboBox<String> comboBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Example frame = new Example();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Example() {
initGUI();
}
private void initGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 428, 362);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblNewLabel = new JLabel("New label");
contentPane.add(lblNewLabel, BorderLayout.WEST);
Timer t = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Random r = new Random();
lblNewLabel.setText(String.valueOf(r.nextInt()));
}
});
t.start();
comboBox = new JComboBox<>();
comboBox.setRenderer(new ListCellRenderer<String>() {
#Override
public Component getListCellRendererComponent(
JList<? extends String> list, String value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel label = new JLabel("");
System.out.println("Pass");
return label;
}
});
contentPane.add(comboBox, BorderLayout.CENTER);
}
}

Categories