Calendar in JComboBox

Hi!,
i have written a JCalendar class. i m using this class to get date input from the user. I have plugged this into a combo box using custom Renderer. But the problem is the mouse events on the calendar displayed in the dropdown box of combo box, are not received by the calendar.
I know the renderer is just to paint the component. how can i enable the calendar to receive mouse events???
thanks in advance.
shahid

The drop down of a JComboBox is actually a real working JList component, which is why the renderer is a ListCellRenderer. What you want to write is a custom UI based off of ComboBoxUI which drops down something other than a JList.
You might even just want to not use JComboBox as a base, because the ListCellRenderer might not be appropriate, and get/setSelectedItem, ComboBoxModel, items lists, etc that are part of a ComboBox really don';t apply to a calendar control.

Similar Messages

  • JTable with JComboBox

    Hi friends,
    I am adding JComboBox in JTable its working properly
    But data is not adding dynamically to JComboBox
    I am Sending my Code plz give me reply
    I am Struggleing from 1 week on wards
    package com.dnt.autopopulation;
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.table.JTableHeader;
    import javax.swing.table.TableColumn;
    import java.awt.event.*;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.event.TableModelEvent;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Locale;
    import java.text.SimpleDateFormat;
    import java.util.Vector;
    import javax.swing.border.*;
    import com.dnt.eaip.Connectmagr;
    import com.dnt.eaip.*;
    import com.dnt.util.*;
    import javax.swing.plaf.ButtonUI;
    import com.dnt.admin.EndStartDateCheck;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumnModel;
    public class AutoPopRollBack extends JPanel {
    boolean selection = false;
    public static final int HAND_CURSOR = 12;
    Cursor cursor = new Cursor(HAND_CURSOR);
    int selectedRow = -1;
    ImageIcon headertop1 = new ImageIcon("./images/k2topbar.gif");
    JLabel HeaderLabe = new JLabel(headertop1);
    Border border1 = new EtchedBorder(EtchedBorder.RAISED, Color.white, Color.blue);
    Border border2 = BorderFactory.createBevelBorder(BevelBorder.RAISED,
    new Color(154, 254, 211), new Color(108, 178, 148),
    new Color(37, 60, 50), new Color(53, 87, 72));
    DefaultTableModel dm = new DefaultTableModel();
    Vector searchlist = new Vector();
    Vector rows = new Vector();
    Vector returnList;
    Connectmagr objConnectmagr = new Connectmagr();
    JFrame frame = new JFrame();
    JLabel headlab = new JLabel();
    JCalendarComboBox EndDateTxt;
    JLabel HawbLab = new JLabel();
    JTextField HawbTxt = new JTextField();
    JLabel AgentLab = new JLabel();
    JLabel StartDateLab = new JLabel();
    JCalendarComboBox StartDateTxt;
    JComboBox AgentLBox = new JComboBox();
    JLabel EnddateLab = new JLabel();
    JPanel ReviewJobsPane = new JPanel();
    JButton SearchBtn = new JButton();
    ButtonUI ui = new com.sun.java.swing.plaf.motif.MotifButtonUI();
    ArrayList AgentList = new ArrayList();
    JComboBox DocTypeLBox = new JComboBox();
    JLabel doctypelab = new JLabel();
    JPanel displayPanel = new JPanel();
    ButtonGroup group1;
    JRadioButton rb;
    JTable table;
    public ArrayList jobList = new ArrayList();
    public AutoPopRollBack(JFrame frame, ArrayList agentArrayList) {
    this.frame = frame;
    this.AgentList = agentArrayList;
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    public void jbInit() throws Exception {
    Calendar cal = Calendar.getInstance();
    Locale loc = new Locale("");
    SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
    EndDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    StartDateTxt = new JCalendarComboBox(cal, loc, dateformat);
    HeaderLabe.setBackground(new Color(250, 233, 216));
    HeaderLabe.setBounds(new Rectangle(0, 0, 830, 33));
    this.setLayout(null);
    this.setBackground(SystemColor.control);
    headlab.setBackground(new Color(250, 233, 216));
    headlab.setFont(new java.awt.Font("Verdana", 1, 12));
    headlab.setForeground(Color.blue);
    headlab.setHorizontalAlignment(SwingConstants.CENTER);
    headlab.setText(" :: Auto Population Rollback");
    headlab.setBounds(new Rectangle(39, 2, 247, 25));
    EndDateTxt.setBounds(new Rectangle(474, 36, 116, 18));
    EndDateTxt.setBackground(Color.white);
    EndDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EndDateTxt.setForeground(Color.blue);
    EndDateTxt.setBorder(null);
    HawbLab.setFont(new java.awt.Font("Dialog", 0, 13));
    HawbLab.setForeground(Color.blue);
    HawbLab.setHorizontalAlignment(SwingConstants.RIGHT);
    HawbLab.setText("Job No/Airway Bill No:");
    HawbLab.setBounds(new Rectangle(326, 14, 146, 18));
    HawbTxt.setBounds(new Rectangle(474, 14, 125, 18));
    HawbTxt.setText("");
    HawbTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    HawbTxt.setForeground(Color.blue);
    HawbTxt.setBorder(border1);
    AgentLab.setFont(new java.awt.Font("Dialog", 0, 13));
    AgentLab.setForeground(Color.blue);
    AgentLab.setHorizontalAlignment(SwingConstants.RIGHT);
    AgentLab.setText("<html>Agent:<font size=\'4\' color=\"#993333\">*</font></html>");
    AgentLab.setBounds(new Rectangle(31, 14, 97, 18));
    StartDateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    StartDateLab.setForeground(Color.blue);
    StartDateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    StartDateLab.setText("Start Date:");
    StartDateLab.setBounds(new Rectangle(23, 36, 105, 18));
    StartDateTxt.setBounds(new Rectangle(129, 36, 116, 18));
    StartDateTxt.setBackground(Color.white);
    StartDateTxt.setFont(new java.awt.Font("Times New Roman", 1, 10));
    StartDateTxt.setForeground(Color.blue);
    StartDateTxt.setBorder(null);
    AgentLBox.setBackground(Color.white);
    AgentLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    AgentLBox.setForeground(Color.blue);
    AgentLBox.setBounds(new Rectangle(129, 14, 178, 18));
    AgentLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    EnddateLab.setFont(new java.awt.Font("Dialog", 0, 13));
    EnddateLab.setForeground(Color.blue);
    EnddateLab.setHorizontalAlignment(SwingConstants.RIGHT);
    EnddateLab.setText("End Date:");
    EnddateLab.setBounds(new Rectangle(391, 36, 81, 18));
    ReviewJobsPane.setBackground(new Color(240, 233, 216));
    ReviewJobsPane.setBorder(BorderFactory.createLineBorder(Color.black));
    ReviewJobsPane.setBounds(new Rectangle(69, 47, 705, 96));
    ReviewJobsPane.setLayout(null);
    SearchBtn.setUI(ui);
    SearchBtn.setCursor(cursor);
    SearchBtn.setBackground(new Color(76, 125, 104));
    SearchBtn.setBounds(new Rectangle(377, 153, 89, 19));
    SearchBtn.setFont(new java.awt.Font("Tahoma", 1, 10));
    SearchBtn.setForeground(Color.white);
    SearchBtn.setBorder(border2);
    SearchBtn.setOpaque(true);
    SearchBtn.setFocusPainted(false);
    SearchBtn.setText("Search");
    SearchBtn.addActionListener(new AutoPopRollBack_SearchBtn_actionAdapter(this));
    for (int i = 0; i < AgentList.size(); i++)
    AgentLBox.addItem( (String) AgentList.get(i));
    DocTypeLBox.setFont(new java.awt.Font("Verdana", 0, 13));
    DocTypeLBox.setForeground(Color.blue);
    DocTypeLBox.setMinimumSize(new Dimension(22, 19));
    DocTypeLBox.setBounds(new Rectangle(129, 58, 179, 18));
    DocTypeLBox.setFont(new java.awt.Font("Times New Roman", 1, 10));
    DocTypeLBox.addItem("New Jobs");
    DocTypeLBox.addItem("Draft jobs");
    DocTypeLBox.addItem("Finished jobs");
    doctypelab.setBounds(new Rectangle(7, 58, 121, 18));
    doctypelab.setText("<html>Document Type:<font size=\'4\' color=\"#993333\">*</font></html>");
    doctypelab.setHorizontalAlignment(SwingConstants.RIGHT);
    doctypelab.setForeground(Color.blue);
    doctypelab.setFont(new java.awt.Font("Dialog", 0, 13));
    displayPanel.setBorder(BorderFactory.createLineBorder(Color.black));
    displayPanel.setBounds(new Rectangle(69, 182, 705, 315));
    this.add(headlab, null);
    this.add(HeaderLabe, null);
    this.add(ReviewJobsPane, null);
    ReviewJobsPane.add(HawbLab, null);
    ReviewJobsPane.add(AgentLab, null);
    ReviewJobsPane.add(AgentLBox, null);
    ReviewJobsPane.add(StartDateLab, null);
    ReviewJobsPane.add(StartDateTxt, null);
    ReviewJobsPane.add(HawbTxt, null);
    ReviewJobsPane.add(EnddateLab, null);
    ReviewJobsPane.add(EndDateTxt, null);
    ReviewJobsPane.add(DocTypeLBox, null);
    ReviewJobsPane.add(doctypelab, null);
    this.add(SearchBtn, null);
    this.add(displayPanel, null);
    //this.add(scrollPaneView, null);
    // scrollPaneView.getViewport().add(displayPanel, null);
    this.setVisible(true);
    void FieldEditable(boolean str) {
    StartDateTxt.setEnabled(str);
    EndDateTxt.setEnabled(str);
    public static void main(String args[]) {
    JFrame frame = new JFrame();
    ArrayList agentlist = new ArrayList();
    agentlist.add(0, "BF0651");
    agentlist.add(1, "PF0010");
    AutoPopRollBack objAutoPopRollBack = new AutoPopRollBack(frame, agentlist);
    frame.getContentPane().add(objAutoPopRollBack);
    frame.setBounds(new Rectangle(0, 0, 820, 593));
    frame.setVisible(true);
    void SearchBtn_actionPerformed(ActionEvent e) {
    displayPanel.setVisible(false);
    Vector data=new Vector();
    rows.removeAllElements();
    boolean flag = true;
    String che = new EndStartDateCheck().crossCheck(StartDateTxt.getCalendar(), EndDateTxt.getCalendar());
    try {
    if(HawbTxt.getText().equalsIgnoreCase("")){
    if (StartDateTxt._spinner.getText().equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(this, "Please Select Start Date",
    "Warning", JOptionPane.WARNING_MESSAGE);
    flag = false;
    else if (!che.equalsIgnoreCase("")) {
    JOptionPane.showMessageDialog(frame, che, "Message Window", JOptionPane.INFORMATION_MESSAGE);
    flag = false;
    }else{
    FieldEditable(true);
    if (flag) {
    try {
    displayPanel.removeAll();
    } catch (Exception ex) {
    rows.removeAllElements();
    data.removeAllElements();
    SearchBtn.setEnabled(true);
    searchlist.add(0, AgentLBox.getSelectedItem().toString().trim());
    if (!HawbTxt.getText().trim().equalsIgnoreCase(""))
    searchlist.add(1, HawbTxt.getText().toString().trim());
    else
    searchlist.add(1, "");
    searchlist.add(2, new Integer(DocTypeLBox.getSelectedIndex() + 1));
    String startDate = new ConvertDate().convertddMM_To_MMdd(StartDateTxt._spinner.getText());
    String endDate = new ConvertDate().convertddMM_To_MMdd(EndDateTxt._spinner.getText());
    Vector columns = new Vector();
    columns.add(0, "");
    columns.add(1, "JOB No");
    columns.add(2, "Status");
    columns.add(3, "Current Form Type");
    columns.add(4, "New Form Type");
    System.out.println("Before calling Data Base");
    jobList = objConnectmagr.AutoRollBackSearch(searchlist, startDate, endDate, "AutoPopRollBack");
    if (jobList.size() > 0) {
    for (int i = 0; i < jobList.size(); i++) {
    ArrayList temp = new ArrayList();
    temp = (ArrayList) jobList.get(i);
    Vector col = new Vector();
    col.add(0, new Boolean(false));
    col.add(1, temp.get(0).toString().trim());
    col.add(2, temp.get(1).toString().trim());
    col.add(3, temp.get(2).toString().trim());
    Vector tempstr=new Vector();
    String [] tem=temp.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    col.add(4, new JComboBox(tempstr));
    data.add(col);
    dm.setDataVector(data, columns);
    table = new JTable(dm) {
    public void tableChanged(TableModelEvent e) {
    super.tableChanged(e);
    public boolean isCellEditable(int rowIndex, int vColIndex) {
    return true;
    JScrollPane scroll = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    table.setColumnSelectionAllowed(false);
    table.setRowSelectionAllowed(false);
    table.setCellSelectionEnabled(false);
    table.setBackground(SystemColor.inactiveCaptionText);
    table.setRowHeight(20);
    JTableHeader head = table.getTableHeader();
    head.setSize(850, 75);
    table.setTableHeader(head);
    table.getTableHeader().setFont(new Font("Verdana", Font.BOLD, 11));
    table.getTableHeader().setBackground(new Color(130, 170, 150));
    table.getTableHeader().setForeground(Color.BLUE);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    table.setFont(new java.awt.Font("MS Sans Serif", 0, 13));
    table.setForeground(new Color(125, 25, 0));
    TableColumn col = table.getColumnModel().getColumn(0);
    col.setMinWidth(75);
    col.setMaxWidth(75);
    TableColumn col1 = table.getColumnModel().getColumn(1);
    col1.setMinWidth(150);
    col1.setMaxWidth(150);
    TableColumn col2 = table.getColumnModel().getColumn(2);
    col2.setMinWidth(150);
    col2.setMaxWidth(150);
    TableColumn col3 = table.getColumnModel().getColumn(3);
    col3.setMinWidth(150);
    col3.setMaxWidth(150);
    TableColumn col4 = table.getColumnModel().getColumn(4);
    col4.setMinWidth(160);
    col4.setMaxWidth(160);
    TableColumn tc = table.getColumnModel().getColumn(0);
    tc.setCellEditor(table.getDefaultEditor(Boolean.class));
    tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
    tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener()));
    Vector tempstr=new Vector();
    for(int j=0;j<jobList.size();j++){
    ArrayList temlist=(ArrayList)jobList.get(j);
    String [] tem=temlist.get(3).toString().trim().split("\\|");
    tempstr.removeAllElements();
    for(int k=0;k<tem.length;k++)
    tempstr.add(k,tem[k]);
    JComboBox portTypesCombo = new JComboBox(tempstr);
    col4.setCellEditor(new DefaultCellEditor(portTypesCombo));
    col4 = table.getColumnModel().getColumn(4);
    col4.setCellEditor(new MyComboBoxEditor(tempstr));
    // If the cell should appear like a combobox in its
    // non-editing state, also set the combobox renderer
    col4.setCellRenderer(new MyComboBoxRenderer(tempstr));
    System.out.println(tempstr);
    displayPanel.setLayout(new BorderLayout());
    displayPanel.add(table.getTableHeader(), BorderLayout.PAGE_START);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    table.setEditingColumn(0);
    int column = 0;
    if (e.getClickCount() == 1) {
    Point p = e.getPoint();
    selectedRow = table.rowAtPoint(p);
    column = table.columnAtPoint(p);
    System.out.println(table.isCellEditable(selectedRow, column));
    if (column != 0) {
    selectedRow = -1;
    returnList = new Vector();
    returnList = (Vector) rows.get(selectedRow);
    else if (column == 0) {
    table.revalidate();
    table.repaint();
    scroll.getViewport().add(table);
    displayPanel.add(scroll, BorderLayout.CENTER);
    displayPanel.setVisible(true);
    else {
    JOptionPane.showMessageDialog(this, "No Data Available");
    } catch (Exception e1) {
    e1.printStackTrace();
    class MyItemListener implements ItemListener {
    public void itemStateChanged(ItemEvent e) {
    Object source = e.getSource();
    if (source instanceof AbstractButton == false)return;
    boolean checked = e.getStateChange() == ItemEvent.SELECTED;
    for (int x = 0, y = table.getRowCount(); x < y; x++) {
    table.setValueAt(new Boolean(checked), x, 0);
    class AutoPopRollBack_SearchBtn_actionAdapter implements java.awt.event.ActionListener {
    AutoPopRollBack adaptee;
    AutoPopRollBack_SearchBtn_actionAdapter(AutoPopRollBack adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.SearchBtn_actionPerformed(e);
    class RadioButtonRenderer implements TableCellRenderer {
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (value == null)return null;
    return (Component) value;
    class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
    private JRadioButton button;
    public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row,
    int column) {
    if (value == null)return null;
    button = (JRadioButton) value;
    button.addItemListener(this);
    return (Component) value;
    public Object getCellEditorValue() {
    button.removeItemListener(this);
    return button;
    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    class CheckCellRenderer extends JCheckBox implements TableCellRenderer {
    protected static Border m_noFocusBorder;
    public CheckCellRenderer() {
    super();
    m_noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(m_noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (value instanceof Boolean) {
    Boolean b = (Boolean) value;
    setSelected(b.booleanValue());
    setBackground(isSelected && !hasFocus ?
    table.getSelectionBackground() : table.getBackground());
    setForeground(isSelected && !hasFocus ?
    table.getSelectionForeground() : table.getForeground());
    setFont(table.getFont());
    setBorder(hasFocus ? UIManager.getBorder(
    "Table.focusCellHighlightBorder") : m_noFocusBorder);
    return this;
    class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener {
    protected CheckBoxHeader rendererComponent;
    protected int column;
    protected boolean mousePressed = false;
    public CheckBoxHeader(ItemListener itemListener) {
    rendererComponent = this;
    rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (table != null) {
    JTableHeader header = table.getTableHeader();
    if (header != null) {
    rendererComponent.setForeground(header.getForeground());
    rendererComponent.setBackground(header.getBackground());
    rendererComponent.setFont(new java.awt.Font("Verdana", 1, 10));
    header.addMouseListener(rendererComponent);
    setColumn(column);
    rendererComponent.setText("Select All");
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    return rendererComponent;
    protected void setColumn(int column) {
    this.column = column;
    public int getColumn() {
    return column;
    protected void handleClickEvent(MouseEvent e) {
    if (mousePressed) {
    mousePressed = false;
    JTableHeader header = (JTableHeader) (e.getSource());
    JTable tableView = header.getTable();
    TableColumnModel columnModel = tableView.getColumnModel();
    int viewColumn = columnModel.getColumnIndexAtX(e.getX());
    int column = tableView.convertColumnIndexToModel(viewColumn);
    if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
    doClick();
    public void mouseClicked(MouseEvent e) {
    handleClickEvent(e);
    ( (JTableHeader) e.getSource()).repaint();
    public void mousePressed(MouseEvent e) {
    mousePressed = true;
    public void mouseReleased(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public MyComboBoxRenderer(Vector items) {
    super(items);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    super.setBackground(table.getSelectionBackground());
    else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    // Select the current value
    setSelectedItem(value);
    return this;
    class MyComboBoxEditor extends DefaultCellEditor {
    public MyComboBoxEditor(Vector items) {
    super(new JComboBox(items));
    and Bringing data from data base by using this method
    if (i == 0) sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and ISSUEDATE BETWEEN '" + startDate + "' and '" + endDate + "'";
    else sqlString = "SELECT * FROM FLIGHTSEARCH WHERE AGENT_CODE='" + agentCode + "' and JOB_NO='" + JobNo + "%'";
    st = con.createStatement();
    System.out.println("---new jobs search-->" + sqlString);
    rs = st.executeQuery(sqlString);
    while (rs.next()) {
    retVector = new ArrayList();
    retVector.add(0, rs.getString("JOBNO"));
    retVector.add(1, "New Job");
    retVector.add(2, rs.getString("DOC_TYPE"));
    String temp="";
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    temp="K8I|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K2")){
    temp="K8E";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8I")){
    // temp="K1|K8T";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8T")){
    temp="K1|K8I";
    }else if(retVector.get(2).toString().trim().equalsIgnoreCase("K8E")){
    temp="K2";
    retVector.add(3,temp);
    retVector.add(3, rs.getString("AGENT_CODE"));
    retVectorlist.add(retVector);
    i am sending data To ComboBox like this
    if(retVector.get(2).toString().trim().equalsIgnoreCase("K1")){
    K8I and K8T
    if K2 adding k8E and for other types as mentioned above
    But for ComboBoxes it is showing same Items not changing
    Please any body can help to me
    Thanks and Regards
    Ravichandra

    If you want further help post a Short, Self Contained, Compilable and Executable, Example Program ([url http://homepage1.nifty.com/algafield/sscce.html]SSCCE) that demonstrates the problem.
    And don't forget to use [url http://forum.java.sun.com/help.jspa?sec=formatting]code formatting when posting code.

  • Setting default value for a jcombobox based on the value not the index

    I am trying to set the default value for my combobox to the current year. One way I thought of doing it was to get the index of the value representing the current year and then use setSelectedInex to make it the default. Any ideas?
    The relevent section of code is below.
    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    int year = gregorianCalendar.get(Calendar.YEAR);
    String currentyear = year + "";
    int startyears = 2000;
    int numyears = 25;
    JComboBox endyearcombobox = new JComboBox();
    endyearcombobox.setBorder( BorderFactory.createLineBorder(Color.DARK_GRAY));
    endyearcombobox.setFont(standardfont);
    endyearcombobox.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent event ) {
    endyearcombobox = ( JComboBox )event.getSource();
    endyear = endyearcombobox.getSelectedItem();
    boolean same = endyear.equals(oldItem);
    oldItem = endyear;
    String[] endyearlist = new String[numyears];
    for(int i = startyears; i < startyears+numyears; i++){
    String item = new Integer(i).toString();
    endyearcombobox.addItem(item);
    Thanks
    Ged

    Thanks mate,
    That was what I was looking for. I still had a little more manipulation to do, but sent me on the right track and have got it working now. I don't know why I didn't think of it in the first place.
    Ged

  • Need image to update with JComboBox selection

    hello, i have code here that loads an image from a JFileChooser dialog when "Add Image" is clicked, the images name and path is stored in a JComboBox, and the image name is displayed. As more images are added to the JComboBox, I would like to be able to have the picture displayed in concurrence with whatever image is selected from the comboBox. For instance, if Jessica.jpg is selected in the JComboBox, i need Jessica.jpg to be loaded into imagePanel. Here is the code. The problem lies within the JComboBox's "itemStateChanged" I believe... This is what must be used (i think) to update the pictures in the imagePanel when the combobox is manipulated....
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.border.*;
    import java.awt.image.BufferedImage;
    public class MyDialog extends JDialog implements ActionListener, WindowListener, ItemListener
         ReminderClass dataRec;
         ReminderClass originalDataRec;
         Image im;
         MediaTracker mt;
         Toolkit tk;
         JFileChooser imageDialog;
         File f;
         String[] comboBoxList;
         String fileName;
         String filePathName;
         DataManager dataManager;
         JPanel mainPanel1;
         JPanel mainPanel2;
         JPanel mainPanel3;
         JPanel buttonPanel;
         JPanel radioPanel;
         MyImageJPanel imagePanel;
         JScrollPane scrollPane1;
         JScrollPane scrollPane2;
         JRadioButton pendingButton;
         JRadioButton documentationButton;
         JRadioButton completedButton;
         JRadioButton failedButton;
         JRadioButton cancelledButton;
         ButtonGroup radioGroup;
         JComboBox imageComboBox;
         JComboBox category;
         JTextArea description;
         JTextArea message;
         JLabel descriptionLabel;
         JLabel messageLabel;
         JLabel fileNameLabel;
         JLabel categoryLabel;
         JLabel selectedFile;
         GregorianCalendar dueDateTime;
         GregorianCalendar reminderInterval;
         GregorianCalendar terminatedDateTime;
         JButton saveCont;
         JButton cancel;
         JButton addImage;
         JButton saveExit;
         JLabel dueDate;
         JLabel intervalDate;
         JLabel terminatedDate;
         JTextField dueDateField;
         JTextField intervalDateField;
         JTextField terminatedDateField;
         int choice;
         int newIndex;
         public MyDialog(DataManager aDataManager)
         {//add new Reminder to list d-box
              Container cp;
              dataManager = aDataManager;
              dataRec = new ReminderClass();
              imageComboBox = new JComboBox();
              imagePanel = new MyImageJPanel();
              imagePanel.setPreferredSize(new Dimension(40, 40));
              imageComboBox.addItemListener(this);
              mainPanel1 = new JPanel(new BorderLayout());
              mainPanel2 = new JPanel(new BorderLayout());
              mainPanel3 = new JPanel(new GridLayout(7,2));
              radioPanel = new JPanel(new GridLayout(5,1));
              buttonPanel = new JPanel(new FlowLayout());
              saveCont = new JButton ("Save & Continue");
              saveExit = new JButton ("Save & Exit");
              addImage = new JButton ("Add Image(s)");
              cancel = new JButton ("Cancel");
              description = new JTextArea("         ");
              description.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane1 = new JScrollPane(description);
              message = new JTextArea("          ");
              scrollPane2 = new JScrollPane(message);
              comboBoxList = CategoryConversion.categories;
              category = new JComboBox(comboBoxList);
              category.setSelectedIndex(0);
              message.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane2 = new JScrollPane(message);
              descriptionLabel = new JLabel("Description: ");
              messageLabel = new JLabel("Message: ");
              selectedFile = new JLabel("Selected File(s): ");
              fileNameLabel = new JLabel();
              categoryLabel = new JLabel("Category: ");
              dueDate = new JLabel("Due date: ");
              intervalDate = new JLabel ("Interval date: ");
              terminatedDate = new JLabel ("Terminated date: ");
              dueDateField = new JTextField("   ");
              intervalDateField = new JTextField("   ");
              terminatedDateField = new JTextField("   ");
              pendingButton = new JRadioButton("Pending?");
              documentationButton = new JRadioButton("Documentation?");
              completedButton = new JRadioButton("Completed?");
              failedButton = new JRadioButton("Failed?");
              cancelledButton = new JRadioButton("Cancelled?");
              radioGroup = new ButtonGroup();
              radioGroup.add(pendingButton);
              radioGroup.add(documentationButton);
              radioGroup.add(completedButton);
              radioGroup.add(failedButton);
              radioGroup.add(cancelledButton);
              radioPanel.add(pendingButton);
              radioPanel.add(documentationButton);
              radioPanel.add(completedButton);
              radioPanel.add(failedButton);
              radioPanel.add(cancelledButton);
              pendingButton.addActionListener(this);
              pendingButton.setActionCommand("PENDING");
              documentationButton.addActionListener(this);
              documentationButton.setActionCommand("DOCUMENTATION");
              completedButton.addActionListener(this);
              completedButton.setActionCommand("COMPLETED");
              failedButton.addActionListener(this);
              failedButton.setActionCommand("FAILED");
              cancelledButton.addActionListener(this);
              cancelledButton.setActionCommand("CANCELLED");
              add(mainPanel1);
              mainPanel1.add(mainPanel2, BorderLayout.CENTER);
              mainPanel3.add(descriptionLabel);
              mainPanel3.add(scrollPane1);
              mainPanel3.add(messageLabel);
              mainPanel3.add(scrollPane2);
              mainPanel3.add(selectedFile);
              mainPanel3.add(imageComboBox);
              mainPanel3.add(categoryLabel);
              mainPanel3.add(category);
              mainPanel3.add(dueDate);
              mainPanel3.add(dueDateField);
              mainPanel3.add(intervalDate);
              mainPanel3.add(intervalDateField);
              mainPanel3.add(terminatedDate);
              mainPanel3.add(terminatedDateField);
              mainPanel2.add(radioPanel, BorderLayout.EAST);
              mainPanel2.add(mainPanel3, BorderLayout.WEST);
              buttonPanel.add(addImage);
              buttonPanel.add(saveCont);
              buttonPanel.add(saveExit);
              buttonPanel.add(cancel);
              mainPanel1.add(buttonPanel, BorderLayout.SOUTH);
              mainPanel2.add(imagePanel, BorderLayout.CENTER);
              saveCont.setActionCommand("SAVECONT");
              saveCont.addActionListener(this);
              saveExit.setActionCommand("SAVEEXIT");
              saveExit.addActionListener(this);
              cancel.setActionCommand("CANCEL");
              cancel.addActionListener(this);
              addImage.setActionCommand("ADDIMAGE");
              addImage.addActionListener(this);
              category.addItemListener(this);
              addWindowListener(this);
              description.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.DESCRIPTION_FIELD));
              message.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.MESSAGE_FIELD));
              //dueDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.DUE_DATE_TIME_FIELD));
              //intervalDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.REMINDER_INTERVAL_FIELD));
              //terminatedDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.TERMINATED_DATE_TIME_FIELD));
              cp = getContentPane();
              cp.add(mainPanel1);     
              originalDataRec = (ReminderClass)dataRec.clone();
              setupMainFrameAdd();
         public MyDialog(int index, DataManager aDataManager, ReminderClass newDataRec)
         {//edit an existing reminder dialog
              Container cp;
              dataManager = aDataManager;
              index = newIndex;
              dataRec = newDataRec;
              imageComboBox = new JComboBox();
              imagePanel = new MyImageJPanel();
              imagePanel.setPreferredSize(new Dimension(40, 40));
              imageComboBox.addItemListener(this);
              mainPanel1 = new JPanel(new BorderLayout());
              mainPanel2 = new JPanel(new BorderLayout());
              mainPanel3 = new JPanel(new GridLayout(7,2));
              radioPanel = new JPanel(new GridLayout(5,1));
              buttonPanel = new JPanel(new FlowLayout());
              saveCont = new JButton ("Save & Continue");
              saveExit = new JButton ("Save & Exit");
              addImage = new JButton ("Add Image(s)");
              cancel = new JButton ("Cancel");
              description = new JTextArea("         ");
              description.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane1 = new JScrollPane(description);
              message = new JTextArea("          ");
              scrollPane2 = new JScrollPane(message);
              comboBoxList = CategoryConversion.categories;
              category = new JComboBox(comboBoxList);
              category.setSelectedIndex(0);
              dataRec.populateComboBox(imageComboBox);
              message.setBorder(BorderFactory.createLineBorder(Color.black));
              scrollPane2 = new JScrollPane(message);
              descriptionLabel = new JLabel("Description: ");
              messageLabel = new JLabel("Message: ");
              selectedFile = new JLabel("Selected File(s): ");
              fileNameLabel = new JLabel();
              categoryLabel = new JLabel("Category: ");
              dueDate = new JLabel("Due date: ");
              intervalDate = new JLabel ("Interval date: ");
              terminatedDate = new JLabel ("Terminated date: ");
              dueDateField = new JTextField("   ");
              intervalDateField = new JTextField("   ");
              terminatedDateField = new JTextField("   ");
              pendingButton = new JRadioButton("Pending?");
              documentationButton = new JRadioButton("Documentation?");
              completedButton = new JRadioButton("Completed?");
              failedButton = new JRadioButton("Failed?");
              cancelledButton = new JRadioButton("Cancelled?");
              radioGroup = new ButtonGroup();
              radioGroup.add(pendingButton);
              radioGroup.add(documentationButton);
              radioGroup.add(completedButton);
              radioGroup.add(failedButton);
              radioGroup.add(cancelledButton);
              radioPanel.add(pendingButton);
              radioPanel.add(documentationButton);
              radioPanel.add(completedButton);
              radioPanel.add(failedButton);
              radioPanel.add(cancelledButton);
              pendingButton.addActionListener(this);
              pendingButton.setActionCommand("PENDING");
              documentationButton.addActionListener(this);
              documentationButton.setActionCommand("DOCUMENTATION");
              completedButton.addActionListener(this);
              completedButton.setActionCommand("COMPLETED");
              failedButton.addActionListener(this);
              failedButton.setActionCommand("FAILED");
              cancelledButton.addActionListener(this);
              cancelledButton.setActionCommand("CANCELLED");
              add(mainPanel1);
              mainPanel1.add(mainPanel2, BorderLayout.CENTER);
              mainPanel3.add(descriptionLabel);
              mainPanel3.add(scrollPane1);
              mainPanel3.add(messageLabel);
              mainPanel3.add(scrollPane2);
              mainPanel3.add(selectedFile);
              mainPanel3.add(imageComboBox);
              mainPanel3.add(categoryLabel);
              mainPanel3.add(category);
              mainPanel3.add(dueDate);
              mainPanel3.add(dueDateField);
              mainPanel3.add(intervalDate);
              mainPanel3.add(intervalDateField);
              mainPanel3.add(terminatedDate);
              mainPanel3.add(terminatedDateField);
              mainPanel2.add(radioPanel, BorderLayout.EAST);
              mainPanel2.add(mainPanel3, BorderLayout.WEST);
              buttonPanel.add(addImage);
              buttonPanel.add(saveCont);
              buttonPanel.add(saveExit);
              buttonPanel.add(cancel);
              mainPanel1.add(buttonPanel, BorderLayout.SOUTH);
              mainPanel2.add(imagePanel, BorderLayout.CENTER);
              fillInData(dataRec);
              saveCont.setActionCommand("SAVECONT2");
              saveCont.addActionListener(this);
              saveExit.setActionCommand("SAVEEXIT2");
              saveExit.addActionListener(this);
              cancel.setActionCommand("CANCEL2");
              cancel.addActionListener(this);
              addImage.setActionCommand("ADDIMAGE");
              addImage.addActionListener(this);
              category.addItemListener(this);
              addWindowListener(this);
              description.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.DESCRIPTION_FIELD));
              message.setInputVerifier(new MyTextAreaVerifier(dataRec, ReminderClass.MESSAGE_FIELD));
              //dueDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.DUE_DATE_TIME_FIELD));
              //intervalDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.REMINDER_INTERVAL_FIELD));
              //terminatedDateField.setInputVerifier(new MyDateAreaVerifier(dataRec, ReminderClass.TERMINATED_DATE_TIME_FIELD));
              cp = getContentPane();
              cp.add(mainPanel1);     
              originalDataRec = (ReminderClass)dataRec.clone();
              setupMainFrameEdit();
         void setupMainFrameAdd()
              tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setSize(d.width/3, d.height/4);
              setLocation(d.width/3, d.height/3);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setTitle("Reminder Add New");
              setVisible(true);
         }//end of setupMainFrame
         void setupMainFrameEdit()
              tk = Toolkit.getDefaultToolkit();
              Dimension d = tk.getScreenSize();
              setSize(d.width/3, d.height/4);
              setLocation(d.width/3, d.height/3);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setTitle("Edit Existing Reminder");
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              JOptionPane optionPane;
              String temp = new String();
              if (e.getActionCommand().equals("CANCEL"))
                   if(dataRec.compareTo(originalDataRec) != 0)
                        choice = JOptionPane.showConfirmDialog(this, "Are you sure you wish to exit without first saving data?","Are you sure you wish to\n" + "exit without first saving data?", JOptionPane.YES_NO_OPTION);
                        if(choice == JOptionPane.YES_OPTION)
                             dispose();
                        else
                             for (int n = 0; n<imageComboBox.getItemCount(); n++)
                                  dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                             dataRec.setCategory(category.getSelectedIndex());
                             dataManager.add(dataRec);
                             fillInData(dataRec);
                             dispose();
                   else
                        dispose();
              else if (e.getActionCommand().equals("CANCEL2"))
                   if (dataRec.compareTo(originalDataRec) != 0)
                        choice = JOptionPane.showConfirmDialog(this, "Are you sure you wish to\n" + "exit without first saving data?");
                        if (choice == JOptionPane.YES_OPTION)
                             dispose();
                        else
                             this.dispose();
              else if (e.getActionCommand().equals("ADDIMAGE"))
                   filePathName = new String();
                   fileName = new String();
                   imageDialog = new JFileChooser();
                   imageDialog.showOpenDialog(this);
                   f = imageDialog.getSelectedFile();
                   tk = Toolkit.getDefaultToolkit();
                   fileName = f.getName();
                   filePathName = f.getPath();
                   im = tk.getImage(filePathName);
                   try
                        mt = new MediaTracker(this);
                        mt.addImage(im, 432);
                        mt.waitForAll();
                   catch(InterruptedException ie)
                        ie.getStackTrace();
                   imageComboBox.addItem(fileName);
                   dataRec.setImageFileName(fileName);
                   imageComboBox.setSelectedItem(fileName);
                   imagePanel.refreshImage(im , 50, 50);
              else if (e.getActionCommand().equals("SAVECONT"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   temp = dueDateField.getText();
                   fileNameLabel.setText("");
                  dataRec.setCategory(category.getSelectedIndex());
                   dataManager.add((ReminderClass)(dataRec.clone()));
                   dataRec.clearFields();
                   fillInData(dataRec);     
              else if (e.getActionCommand().equals("SAVECONT2"))
                   fileNameLabel.setText("");
                  dataRec.setCategory(category.getSelectedIndex());
                   dataManager.replace(newIndex,(ReminderClass)(dataRec.clone()));
                   dataRec.clearFields();
                   fillInData(dataRec);
              else if (e.getActionCommand().equals("SAVEEXIT"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   dataRec.setCategory(category.getSelectedIndex());
                   dataManager.add(dataRec);
                   fillInData(dataRec);
                   dispose();
                   //save new data to list, and exit back to main prog.
              else if (e.getActionCommand().equals("SAVEEXIT2"))
                   for (int n = 0; n<imageComboBox.getItemCount(); n++)
                        dataRec.addImageToArray((String)imageComboBox.getItemAt(n));
                   dataRec.setCategory(category.getSelectedIndex());
                   dataManager.replace(newIndex, (ReminderClass)(dataRec.clone()));
                   fillInData(dataRec);
                   dispose();
              else if (e.getActionCommand().equals("PENDING"))
                   dataRec.setStatus("Pending");
              else if (e.getActionCommand().equals("DOCUMENTATION"))
                   dataRec.setStatus("Documentation");
              else if (e.getActionCommand().equals("COMPLETED"))
                   dataRec.setStatus("Completed");
              else if (e.getActionCommand().equals("FAILED"))
                   dataRec.setStatus("Failed");
              else if (e.getActionCommand().equals("CANCELLED"))
                   dataRec.setStatus("Cancelled");
         public void itemStateChanged(ItemEvent e)
               JComboBox cb = (JComboBox)e.getSource();
               int categorySelection;
               if(cb == category)
                 categorySelection = cb.getSelectedIndex();
               if (cb == imageComboBox)
                       tk = Toolkit.getDefaultToolkit();
                        fileName = dataRec.getImageFileName();
                        filePathName = f.getPath();
                        im = tk.getImage(filePathName);
                        try
                             mt = new MediaTracker(this);
                             mt.waitForAll();
                             mt.addImage(im, 432);
                             imagePanel.refreshImage(im , 50, 50);
                        catch(InterruptedException ie)
                        ie.getStackTrace();
         public void fillInData(ReminderClass d)
              fileNameLabel.setText(d.getImageFileName());
              description.setText(d.getDescription());
              message.setText(d.getMessage());
              category.setSelectedIndex(d.getCategory());
         public void windowOpened(WindowEvent e)
              //no action to take
         public void windowClosing(WindowEvent e)
              JOptionPane j = new JOptionPane("Are you sure you wish to exit \n" + "without saving data first?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);;
         public void windowClosed(WindowEvent e)
    //          no action to take
         public void windowIconified(WindowEvent e)
    //          no action to take
         public void windowDeiconified(WindowEvent e)
    //          no action to take
         public void windowActivated(WindowEvent e)
    //          no action to take
         public void windowDeactivated(WindowEvent e)
    //          no action to take
    }Here is the main "ReminderClass" with all methods and accessors/mutators....
    import java.util.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    //search for Java Thumb Wheel under Google.
    public class ReminderClass extends Object implements Cloneable, Comparable
          private int category;
          private String description;
          private String message;
          private GregorianCalendar dueDateTime;
         private GregorianCalendar reminderInterval;
          private GregorianCalendar terminatedDateTime;
          private int displayStyle;
          private int compareKey;
          private String status;
          String[] imagePathArray;
          String[] imageArray;
          String imageFileName;
          int numImages;
          public final static int CATEGORY_FIELD = 1;
          public final static int DESCRIPTION_FIELD = 2;
          public final static int MESSAGE_FIELD = 3;
          public final static int DUE_DATE_TIME_FIELD = 4;
          public final static int REMINDER_INTERVAL_FIELD =5;
          public final static int TERMINATED_DATE_TIME_FIELD = 6;
          public final static int DISPLAY_STYLE_FIELD = 7;
          public final static int COMPARE_KEY_FIELD = 8;
          public final static int STATUS_FIELD = 9;
          static boolean showDescription = false;
          static boolean showDate = false;
          static boolean showCategory = false;
          static boolean showMessage = false;
          static boolean showDueDateTime = false;
          static boolean showReminderInterval = false;
          static boolean showTerminatedDateTime = false;
          static boolean showImageName = false;
          static boolean showStatus = false;
          //******************REMINDER CLASS DEFAULT CONSTRUCTOR***************
          ReminderClass()
               numImages = 0;
               imageArray = new String[20];
               imagePathArray = new String[20];
               imageFileName = "";
               category = -1;
               description = "";
               message = "";
               dueDateTime = new GregorianCalendar();
               reminderInterval = new GregorianCalendar();
               terminatedDateTime = new GregorianCalendar();
               displayStyle = -1;
               compareKey = -1;
         //     *****************REMINDER CLASS INITIALIZER CONSTRUCTOR*************
          ReminderClass(int initCategory, String initDescription, GregorianCalendar initDueDateTime, String[] initImagePathArray, String[] initImageArray, String initImageFileName,
                    GregorianCalendar initReminderInterval, GregorianCalendar initTerminatedDateTime, String initMessage, String initStatus,
                     int initCompareKey, int initDisplayStyle)
               imagePathArray = new String[20];
               imageArray = new String[20];
               for (int n = 0; n<initImageArray.length; n++)
                    imageArray[n] = initImageArray[n];
               for (int n = 0; n<initImagePathArray.length; n++)
                    imagePathArray[n] = initImagePathArray[n];
                    imageFileName = initImageFileName;
                     category = initCategory;
                     description = initDescription;
                     dueDateTime = (GregorianCalendar)initDueDateTime.clone();
                     reminderInterval = (GregorianCalendar)initReminderInterval.clone();
                     terminatedDateTime = (GregorianCalendar)initTerminatedDateTime.clone();
                     message = initMessage;
                     status = initStatus;
                     compareKey = initCompareKey;
                     displayStyle = initDisplayStyle;
               //*********************LOAD DATA FROM FILE WITH CONSTRUCTOR*****************************
            public ReminderClass(DataInputStream dataInStream) throws IOException
                           imageFileName = dataInStream.readUTF();
                       category = dataInStream.readInt();
                       description = dataInStream.readUTF();
                       message = dataInStream.readUTF();
                       dueDateTime = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt());
                       reminderInterval = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt()); 
                       terminatedDateTime = new GregorianCalendar(dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt(), dataInStream.readInt());
                       displayStyle = dataInStream.readInt();
                       compareKey = dataInStream.readInt();
                       status = dataInStream.readUTF();
             //********************SAVE DATA TO FILE***************************
             public void write(DataOutputStream dataOutStream) throws IOException
                       dataOutStream.writeUTF(imageFileName);
                       dataOutStream.writeInt(category);
                       dataOutStream.writeUTF(description);
                       dataOutStream.writeUTF(message);
                       dataOutStream.writeInt(dueDateTime.get(Calendar.YEAR));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.MONTH));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.HOUR));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.MINUTE));
                       dataOutStream.writeInt(dueDateTime.get(Calendar.SECOND));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.YEAR));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.MONTH));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.HOUR));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.MINUTE));
                       dataOutStream.writeInt(reminderInterval.get(Calendar.SECOND));         
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.YEAR));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.MONTH));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.DAY_OF_MONTH));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.HOUR));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.MINUTE));
                       dataOutStream.writeInt(terminatedDateTime.get(Calendar.SECOND));        
                       dataOutStream.writeInt(displayStyle);
                       dataOutStream.writeInt(compareKey);
                       //dataOutStream.writeUTF(status);
             public void clearFields()
                   numImages = 0;
                   imageFileName = "";
                   category = -1;
                    description = "";
                    message = "";
                    dueDateTime = new GregorianCalendar();
                    reminderInterval = new GregorianCalendar();
                    terminatedDateTime = new GregorianCalendar();
                    displayStyle = -1;
                    status = "";
                    compareKey = -1;
               //************* OVERRIDE clone METHOD***********************
               public Object clone() 
                         ReminderClass c = new ReminderClass();
                         try
                              c = ((ReminderClass)super.clone());
                              c.setImageArray(imageArray);
                              c.setImagePathArray(imagePathArray);
                              c.imageFileName = (String)imageFileName;
                              c.category = (int)category;
                              c.description = (String)description;
                              c.message = (String)message;
                              c.status = (String)status;
                              c.compareKey = (int)compareKey;
                              c.displayStyle = (int)displayStyle;
                              c.dueDateTime = (GregorianCalendar)(dueDateTime.clone());
                              c.reminderInterval = (GregorianCalendar)(reminderInterval.clone());
                              c.terminatedDateTime = (GregorianCalendar)(terminatedDateTime.clone());
                         catch (CloneNotSupportedException e)
                              System.out.println("Fatal Error: " + e.getMessage());
                              System.exit(1);
                         return c;
          //**************** OVERRIDE toString METHOD*************************
          public String toString()
               String s = new String();
               s =  description;
              if (showCategory)
                    s = s + "," + CategoryConversion.categories[category];
              if (showImageName)
                   s = s + "," + "'" + imageFileName + "'";
              if (showMessage)
                    s = s + "," + message;
              if (showStatus)
                   s = s + "," + status;
              if (showDueDateTime)
                    s = s + ", " + dueDateTime.get(Calendar.MONTH);
                    s = s + "/" + dueDateTime.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" + dueDateTime.get(Calendar.YEAR);
                    s = s + "  " + dueDateTime.get(Calendar.HOUR);
                    s = s + ":" + dueDateTime.get(Calendar.MINUTE);
                    s = s + ":" + dueDateTime.get(Calendar.SECOND);
              if (showReminderInterval)
                    s = s + ", " + reminderInterval.get(Calendar.MONTH);
                    s = s + "/" + reminderInterval.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" + reminderInterval.get(Calendar.YEAR);
                    s = s + "  " + reminderInterval.get(Calendar.HOUR);
                    s = s + ":" + reminderInterval.get(Calendar.MINUTE);
                    s = s + ":" + reminderInterval.get(Calendar.SECOND);
              if (showTerminatedDateTime)
                    s = s + ", " + terminatedDateTime.get(Calendar.MONTH);
                    s = s + "/" + terminatedDateTime.get(Calendar.DAY_OF_MONTH);
                    s = s + "/" +terminatedDateTime.get(Calendar.YEAR);
                    s = s + "  " + terminatedDateTime.get(Calendar.HOUR);
                    s = s + ":" + terminatedDateTime.get(Calendar.MINUTE);
                    s = s + ":" + terminatedDateTime.get(Calendar.SECOND);
               return s;
          //******************COMPARE TO OBJECT*********************************
          public int compareTo(Object r)
               ReminderClass x;
               x = (ReminderClass)r;
               if (
                   (x.getCategory() == this.category)
               && (x.getDescription().equals(this.description))
               && (x.getMessage().equals(this.message))
               && (x.getImageFileName().equals(this.imageFileName))
               && (x.getDueDateTime().equals(this.dueDateTime))
               && (x.getReminderInterval().equals(this.reminderInterval))
               && (x.getTerminatedDateTime().equals(this.terminatedDateTime))
              return 0;
               else     
              return 1;
          //*************** ACCESSORS AND MUTATORS INCLUDING DISPLAY STYLE*******
          public void setDisplayStyle(int newDisplayStyle)
               displayStyle = newDisplayStyle;
          public int getDisplayStyle()
               return displayStyle;
          public int getCompareKey()
               return compareKey;
          public void setCompareKey(int newCompareKey)
               compareKey = newCompareKey;
          public int getCategory()
               return category;
          public void setImageFileName(String newFileName)
               imageFileName = newFileName;
          public String getImageFileName()
               return imageFileName;
          public void setCategory(int newCategory)
               category = newCategory;
          public String getDescription()
               return description;
          public void setDescription(String newDescription)
               description = newDescription;
          public void setImageArray(String[] array)
               imageArray = new String[20];
               for (int n = 0; n<array.length; n++)
                    imageArray[n] = array[n];
          public void setImagePathArray(String[] array)
               imagePathArray = new String[20];
               for (int n = 0; n<array.length; n++)
                    imagePathArray[n] = array[n];
          public String getImagePathArray(int index)
               return imagePathArray[index];
          public void populateComboBox(JComboBox jcb)
               for (int n = 0; n<numImages; n++)
                     jcb.addItem(imageArray[n]);
          public void addImageToArray(String s)
               imageArray[numImages] = s;
               numImages++;
          public String getMessage()
               return message;
          public void setMessage(String newMessage)
               message = newMessage;     
          public GregorianCalendar getDueDateTime()
               return dueDateTime;
          public void setDueDateTime(int newYear, int newMonth, int newDay, int newHours, int newMins,
                    int newSecs)
              dueDateTime = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);           
          public GregorianCalendar getReminderInterval()
               return reminderInterval;
          public void setReminderInterval(int newYear, int newMonth, int newDay, int newHours, int newMins,
                   int newSecs)
               reminderInterval = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);
          public GregorianCalendar getTerminatedDateTime()
               return terminatedDateTime;
          public void setTerminatedDateTime(int newYear, int newMonth, int newDay, int newHours, int newMins,
                   int newSecs)
              terminatedDateTime = new GregorianCalendar(newYear, newMonth, newDay, newHours, newMins, newSecs);      
          public String getStatus()
               return status;
          public void setStatus(String selection)
               status = selection;
          static public void setShowDate(boolean state)
               showDate = state;
          static public boolean getShowDate()
               return showDate;
          static public void setShowCategory(boolean state)
               showCategory = state;
          static public boolean getShowCategory()
               return showCategory;
          static public void setShowImageName(boolean state)
               showImageName = state;
          stat                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

    You don't really expect us to read through 300 lines of code do you?
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    In the meantime I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html]How to Use Combo Boxes for a working example that does exactly what you want.

  • JComboBox is not visible on JPanel

    I have a class that extends JPanel. Within this class I have added several different components; JLabels, JTextFields, JButtons and a JComboBox.
    All of the added components are visible and working except for the JComboBox. I can see the white background of the box and the popup and its list when I click on the area where the JComboBox is located, but I cannot see the selected text in the box. This seems strange since all the other components surrounding the JComboBox display correctly.
    The background is set to white and the foreground is set to black. It has three options in the popup which are displayed using the foreground color, as it should. When I select an option from the popup, it seems to be working because the next time I display the popup, that selection is highlighted. But the selected text never shows in the box.
    If I create a JComboBox in a JPanel, not an extended class, everything seems to work correctly. I can select from the popup and the selection appears in the box.
    Could you please give me some suggestions as to how to make the selected text in the JComboBox visible?
    Thanks
    Bob

    My layout manager is set to null. I don't think that there is anything obscuring it because the backgroud is visible. The only thing that I can't see it the selected text and the combo box down arrow. I am using VisualCafe to generate this code.
    The extended class is loaded from the following class:
    public class TheSchedule extends javax.swing.JFrame
    using the following code:
         void JButtonGenTimeUnits_actionPerformed(java.awt.event.ActionEvent event)
              JPanelMainPanel.add(new TimeUnitDefinition((Frame)this));
              JPanelMainPanel.repaint();
    The actual code of the TimeUnitDefinition is as follows:
    package com.klawuhn.schedule;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import com.symantec.itools.javax.swing.models.StringComboBoxModel;
    import symantec.itools.awt.util.Calendar;
    import com.symantec.itools.javax.swing.borders.LineBorder;
    public class TimeUnitDefinition extends javax.swing.JPanel {
    private Frame parentFrame = null;
         public TimeUnitDefinition(Frame parentFrame)
         this.parentFrame = parentFrame; // Needed when displaying the calendars
              //{{INIT_CONTROLS
              setAlignmentY(1.0F);
              setAlignmentX(1.0F);
              setOpaque(false);
              setLayout(null);
              setSize(457,283);
              JLabelStartDate.setText("Start Date:");
              add(JLabelStartDate);
              JLabelStartDate.setBounds(12,12,156,24);
              JTextFieldStartDate.setDisabledTextColor(java.awt.Color.white);
              JTextFieldStartDate.setToolTipText("This is the date to start generating time units.");
              JTextFieldStartDate.setEditable(false);
              add(JTextFieldStartDate);
              JTextFieldStartDate.setBackground(java.awt.Color.white);
              JTextFieldStartDate.setBounds(168,12,216,24);
              JButtonCalendar1.setText("-");
              JButtonCalendar1.setActionCommand("-");
              add(JButtonCalendar1);
              JButtonCalendar1.setBounds(384,12,24,24);
              JLabelEndDate.setText("End Date:");
              add(JLabelEndDate);
              JLabelEndDate.setBackground(java.awt.Color.cyan);
              JLabelEndDate.setBounds(12,48,156,24);
              JTextFieldEndDate.setDisabledTextColor(java.awt.Color.white);
              JTextFieldEndDate.setToolTipText("This is the date to start generating time units.");
              JTextFieldEndDate.setEditable(false);
              add(JTextFieldEndDate);
              JTextFieldEndDate.setBackground(java.awt.Color.white);
              JTextFieldEndDate.setBounds(168,48,216,24);
              JButtonCalendar2.setText("-");
              JButtonCalendar2.setActionCommand("-");
              add(JButtonCalendar2);
              JButtonCalendar2.setBounds(384,48,24,24);
              JLabelStartTime.setText("Start Time:");
              add(JLabelStartTime);
              JLabelStartTime.setBounds(12,84,156,24);
              JTextFieldStartTime.setToolTipText("This is the time of day to start generating time units.");
              add(JTextFieldStartTime);
              JTextFieldStartTime.setBounds(168,84,240,24);
              JLabelEndTime.setText("End Time:");
              add(JLabelEndTime);
              JLabelEndTime.setBounds(12,120,156,24);
              JTextFieldEndTime.setToolTipText("This is the time of day to end generating time units.");
              add(JTextFieldEndTime);
              JTextFieldEndTime.setBounds(168,120,240,24);
              JLabelUnitOfMeasure.setText("Unit of Measure:");
              add(JLabelUnitOfMeasure);
              JLabelUnitOfMeasure.setBounds(12,156,156,24);
              JComboBoxUnitOfMeasure.setModel(stringComboBoxModel1);
              JComboBoxUnitOfMeasure.setToolTipText("This is the unit of measure used when generating the time units.");
              add(JComboBoxUnitOfMeasure);
              JComboBoxUnitOfMeasure.setBackground(java.awt.Color.white);
              JComboBoxUnitOfMeasure.setForeground(java.awt.Color.black);
              JComboBoxUnitOfMeasure.setBounds(168,156,240,24);
              JLabelBlockSize.setText("Block Size:");
              add(JLabelBlockSize);
              JLabelBlockSize.setBounds(12,192,156,24);
              JTextFieldBlockSize.setText("45");
              JTextFieldBlockSize.setToolTipText("This is the size of the time unit in Unit of Measures.");
              add(JTextFieldBlockSize);
              JTextFieldBlockSize.setBounds(168,192,240,24);
              JButtonSubmit.setText("Submit");
              JButtonSubmit.setActionCommand("Submit");
              JButtonSubmit.setToolTipText("This button will generate the time units.");
              add(JButtonSubmit);
              JButtonSubmit.setBounds(36,228,108,40);
              JButtonCancel.setText("Cancel");
              JButtonCancel.setActionCommand("Cancel");
              JButtonCancel.setToolTipText("This button will discard any changes.");
              add(JButtonCancel);
              JButtonCancel.setBounds(288,228,108,40);
                   String[] tempString = new String[3];
                   tempString[0] = "Days";
                   tempString[1] = "Hours";
                   tempString[2] = "Minutes";
                   stringComboBoxModel1.setItems(tempString);
              //$$ stringComboBoxModel1.move(0,288);
              JComboBoxUnitOfMeasure.setSelectedIndex(2);
              //{{REGISTER_LISTENERS
              SymAction lSymAction = new SymAction();
              JButtonSubmit.addActionListener(lSymAction);
              JButtonCalendar1.addActionListener(lSymAction);
              JButtonCalendar2.addActionListener(lSymAction);
         //{{DECLARE_CONTROLS
         javax.swing.JLabel JLabelStartDate = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldStartDate = new javax.swing.JTextField();
         javax.swing.JButton JButtonCalendar1 = new javax.swing.JButton();
         javax.swing.JLabel JLabelEndDate = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldEndDate = new javax.swing.JTextField();
         javax.swing.JButton JButtonCalendar2 = new javax.swing.JButton();
         javax.swing.JLabel JLabelStartTime = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldStartTime = new javax.swing.JTextField();
         javax.swing.JLabel JLabelEndTime = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldEndTime = new javax.swing.JTextField();
         javax.swing.JLabel JLabelUnitOfMeasure = new javax.swing.JLabel();
         javax.swing.JComboBox JComboBoxUnitOfMeasure = new javax.swing.JComboBox();
         javax.swing.JLabel JLabelBlockSize = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldBlockSize = new javax.swing.JTextField();
         javax.swing.JButton JButtonSubmit = new javax.swing.JButton();
         javax.swing.JButton JButtonCancel = new javax.swing.JButton();
         com.symantec.itools.javax.swing.models.StringComboBoxModel stringComboBoxModel1 = new com.symantec.itools.javax.swing.models.StringComboBoxModel();
         class SymAction implements java.awt.event.ActionListener
              public void actionPerformed(java.awt.event.ActionEvent event)
                   Object object = event.getSource();
                   if (object == JButtonSubmit)
                        JButtonSubmit_actionPerformed(event);
                   else if (object == JButtonCalendar1)
                        JButtonCalendar1_actionPerformed(event);
                   else if (object == JButtonCalendar2)
                        JButtonCalendar2_actionPerformed(event);
         void JButtonSubmit_actionPerformed(java.awt.event.ActionEvent event)
              System.out.println("See Submit button");
              TimeUnitCreate timeUnitCreate = new TimeUnitCreate(
              JTextFieldStartDate.getText(),
              JTextFieldEndDate.getText(),
              JTextFieldStartTime.getText(),
              JTextFieldEndTime.getText(),
              (String)JComboBoxUnitOfMeasure.getSelectedItem(),
              JTextFieldBlockSize.getText()
              timeUnitCreate.createTimeUnits();
              this.setVisible(false);
    System.out.println("Done creating Time Units.");
    // (new TimeUnitDefinition()).setVisible(true);
         void JButtonCalendar1_actionPerformed(java.awt.event.ActionEvent event)
         CalendarDialog calendarDialog = new CalendarDialog(parentFrame,"Date",true);
         calendarDialog.show();
         JTextFieldStartDate.setText(calendarDialog.getSelectedDate());
         void JButtonCalendar2_actionPerformed(java.awt.event.ActionEvent event)
         CalendarDialog calendarDialog = new CalendarDialog(parentFrame,"Date",true);
         calendarDialog.show();
         JTextFieldEndDate.setText(calendarDialog.getSelectedDate());
    }

  • GUI of a calendar (monthly)

    I tried to built a GUI for a Kalender but i need explanation with comments to understand the code. Can someone help me?
    I work with this code, it is form this forum (post at the end of line):
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    public class MightyMouse1
         static class SimpleCalendar
              extends JPanel
              private static final String[] sDays=
                   new DateFormatSymbols().getWeekdays();
              private static int sStartDay= 0;
              static {
                   for (int i= 0; i< sDays.length; i++)
                        if (sDays.length() <= 0)
                             sStartDay++;
              private static final int[] sMonthDays=
                   {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
              private Calendar mDate;
              private int mCellWidth= 1;
              private int mCellHeight= 1;
              private int mStartDay;
              private int mDaysInMonth;
              public SimpleCalendar()
                   mDate= Calendar.getInstance();
                   addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                             hitTest(e.getPoint());
                             e.consume();
              public void setDate(Date date)
                   mDate.setTime(date);
                   repaint();
              public Date getDate() { return mDate.getTime(); }
              public Dimension getPreferredSize() { return getMinimumSize(); }
              public Dimension getMinimumSize() { return new Dimension(180,180); }
              public void paint(Graphics g)
                   g.clearRect(0, 0, getSize().width, getSize().height);
                   doMonth(g);
              private void hitTest(Point p)
                   int cellX, cellY, dom;
                   cellX= (int) p.x / mCellWidth;
                   cellY= (int) p.y / mCellHeight;
                   if (cellY != 0) { // not the days title bar
                        dom= cellX+1+((cellY-1)*7)-mStartDay;
                        if (dom > 0 && dom <= mDaysInMonth) {
                             mDate.set(Calendar.DAY_OF_MONTH, dom);
                             setDate(mDate.getTime());
              private boolean leapYear(int year)
                   if ((year % 400) == 0)
                        return(true);
                   if ((year > 1582) && ((year % 100) == 0))
                        return(false);
                   if ((year % 4) == 0)
                        return(true);
                   return(false);
              private void drawMonth(Graphics g, int startDay, int days, boolean special)
                   mStartDay= startDay;
                   mDaysInMonth= days;
                   mCellWidth= getSize().width / 7;
                   mCellHeight= getSize().height / 7;
                   int day= mDate.get(Calendar.DAY_OF_MONTH);
                   FontMetrics metrics= g.getFontMetrics();
                   // Draw the days of the week (M, T, W ...) on the top line
                   for (int col= 0, x= 0, y= 0; col < 7; col++) {
                        String s= String.valueOf(sDays[col+sStartDay].charAt(0));
                        // Make (x,y) the top left of the cell
                        x= col * mCellWidth;
                        y= 0;
                        // Make (x,y) the center of the cell
                        x= x + (mCellWidth/2);
                        y= y + (mCellHeight/2);
                        // Move (x,y) to accomodate the text
                        x= x - (metrics.stringWidth(s)/2);
                        y= y + (metrics.getAscent()/2);
                        g.setColor(Color.blue);
                        g.drawString(s, x, y);
                   // Draw the days of the month starting one line down
                   for (int i= 1, row= 1, col= startDay, x= 0, y= 0; i <= days; i++) {
                        if (special && (i == 5))
                             i += 10; // skip 10 days (Oct 5-14) in October, 1582
                        String s= "" + i;
                        // Make (x,y) the top left of the cell
                        x= col * mCellWidth;
                        y= row * mCellHeight;
                        if (i == day) {
                             g.setColor(new Color(255,255,200));
                             g.fillRect(x, y, mCellWidth, mCellHeight);
                        // Make (x,y) the center of the cell
                        x= x + (mCellWidth/2);
                        y= y + (mCellHeight/2);
                        // Move (x,y) to accomodate the text
                        x= x - (metrics.stringWidth(s)/2);
                        y= y + (metrics.getAscent()/2);
                        g.setColor(Color.black);
                        g.drawString(s, x, y);
                        col++;
                        if (col > 6) {
                             col= 0;
                             row++;
              private void doMonth(Graphics g)
                   int month= mDate.get(Calendar.MONTH);
                   int year= mDate.get(Calendar.YEAR);
                   int daysInMonth;
                   int startOfMonth;
                   int y= year - 1;
                   boolean leap= leapYear(year);
                   boolean special= ((year == 1582) && (month == 9));
                   boolean pre= ((year < 1582) || ((year == 1582) && (month <= 9)));
                   if (pre)
                        startOfMonth = 6 + y + (y/4);
                   else
                        startOfMonth = 1 + y + (y/4) - (y/100) + (y/400);
                   if (leap && month == 1)
                        daysInMonth= 29;
                   else
                        daysInMonth= sMonthDays[month];
                   for (int i = 0; i < month; i++)
                        startOfMonth += sMonthDays[i];
                   drawMonth(g, startOfMonth % 7, daysInMonth, special);
         static class FancyCalendar
              extends JPanel
              private static final String[] sMonths=
                   new DateFormatSymbols().getMonths();
              private JComboBox mComboMonths;
              private JComboBox mComboYears;
              private JLabel mLabel;
              private SimpleCalendar mCalendar;
              private int mSelectedMonth;
              private int mSelectedYear;
              private Dimension mMinimumSize;
              private int mFirstYear;
              private int mLastYear;
              private Date mDate;
              private boolean mShowTime;
              public FancyCalendar() { this(-10, 10); }
              public FancyCalendar(int firstYear, int lastYear)
                   mFirstYear= firstYear;
                   mLastYear= lastYear;
                   adjustYears();
                   setLayout(new BorderLayout(2,2));
                   mCalendar= new SimpleCalendar();
                   add(mCalendar, BorderLayout.CENTER);
                   setupCombos();
                   setDate(mCalendar.getDate());
              public void setDate(Date date)
                   mDate= date;
                   mCalendar.setDate(date);
                   Calendar cal= Calendar.getInstance();
                   cal.setTime(date);
                   mSelectedMonth= date.getMonth();
                   mSelectedYear= cal.get(Calendar.YEAR);
                   mComboYears.setSelectedIndex(mSelectedYear-mFirstYear);
                   mComboMonths.setSelectedIndex(mSelectedMonth);
              public Date getDate() { return mDate; }
              public Dimension getPreferredSize() { return getMinimumSize(); }
              public Dimension getMinimumSize() { return mMinimumSize; }
              private void adjustYears()
                   Date today= new Date();
                   if (mFirstYear < 0 && mFirstYear >= -50)
                        mFirstYear= 1900+ today.getYear() +mFirstYear;
                   if (mLastYear > 0 && mLastYear <= 50)
                        mLastYear= 1900+ today.getYear() +mLastYear;
                   if (mFirstYear < 1900)
                        mFirstYear= 1900;
              private void setupCombos()
                   mMinimumSize= new Dimension(170,180);
                   JPanel p= new JPanel();
                   mComboMonths= new JComboBox(sMonths);
                   mComboYears= new JComboBox();
                   p.add(mComboMonths);
                   p.add(mComboYears);
                   add(p, BorderLayout.NORTH);
                   for(int i= mFirstYear; i<= mLastYear; i++)
                        mComboYears.addItem(""+i);
                   mComboMonths.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e)
                             if(mComboMonths.getSelectedIndex() != mSelectedMonth) {
                                  mSelectedMonth= mComboMonths.getSelectedIndex();
                                  Calendar cal= Calendar.getInstance();
                                  cal.setTime(getDate());
                                  cal.set(Calendar.MONTH, mSelectedMonth);
                                  setDate(cal.getTime());
                   mComboYears.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e)
                             int y= mComboYears.getSelectedIndex() +mFirstYear;
                             if((y > 0) && (y != mSelectedYear)) {
                                  mSelectedYear= y;
                                  Calendar cal= Calendar.getInstance();
                                  cal.setTime(getDate());
                                  cal.set(Calendar.YEAR, mSelectedYear);
                                  setDate(cal.getTime());
                                  // If date was feb 29 and new year is not leap,
                                  // then the month will have moved on one, so re-set
                                  // the combo box
                                  mComboMonths.setSelectedIndex(
                                       cal.get(Calendar.MONTH));
    public static void main(String[] argv)
    JFrame frame= new JFrame();
    frame.getContentPane().add(new FancyCalendar());
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    It is from the forum here:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=
    This post:
    [Dukes Earned 470] dchsw
    Posts:449
    Registered: 9/1/98
    Re: Developing a calendar
    Nov 6, 2003 6:37 AM (reply 3 of 6)

    > I tried to built a GUI for a Kalender but i need explanation with comments to understand the code.
    http://java.sun.com/docs/books/tutorial/java/index.html
    http://java.sun.com/docs/books/tutorial/uiswing/
    Let us know if you have a specific question.
    ~

  • Changing value in JcomboBox

    hi, i am new learner in java programming language.
    i trying to develop a Greenwich inn resort reservation system.
    i am adding 2 JCombobox in the JFrame and adding 2 Action listener to the 2 created JCombobox in oder to reset the value in Jcombobox.
    jComboBox1.addActionListener(jcb1);
    jComboBox2.addActionListener(jcb2); i am create a class which call as timemanager to control the time
    public class timemanager {
    int Year;
    int Month;
    int Date;
    Calendar calendar = Calendar.getInstance();
        public timemanager(){
           Date today = new Date();
           Year = (today.getYear() +1900);
           Month = today.getMonth();
           Date = today.getDate();
        public int getmaxday(){
            calendar.set(Year,Month,Date);
            int maxday = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            return maxday;
        }i poiting the object in as timemanager time1 = new timemanager();
    and i am adding the listener command which is
    public ActionListener jcb1=new ActionListener(){
        public void actionPerformed(ActionEvent ae){
            if ((Integer)jComboBox1.getSelectedItem()== (new Date().getYear()+1900)){
             time1.Year = (Integer)jComboBox1.getSelectedItem();
                reservationstartingshowingdate();//method which i call to change the value
             }else{
             time1.Year = (Integer)jComboBox1.getSelectedItem();
             changestartingdatevalue();//method which i call to change the value
        public ActionListener jcb2=new ActionListener(){
        public void actionPerformed(ActionEvent a){
            for(int x =0;x<fullmonth.length;x++){
            if (jComboBox2.getSelectedItem()== fullmonth[x]){
                if (new Date().getMonth()==x){
                    if (time1.Year== (new Date().getYear()+1900)){
                            time1.Month = x;
                         reservationstartingshowingdate(); //method which i call to change the value
                    }else{
                        time1.Month = x;
                        //System.out.println(time1.Month);
                        changestartingdatevalue();
                }else{
                     time1.Month = x;
                     System.out.println(time1.Month);
                     changestartingdatevalue();
        };and my reservationstartingshowingdate() method are
    private void reservationstartingshowingdate() {
                    int date = time1.Date;
                  int month = time1.Month;
                  int year = time1.Year;
                  int maxday = time1.getmaxday();
                  //System.out.println("item count combobox1 ="+jComboBox2.getItemCount());
                  if (jComboBox2.getItemCount()>=0){
                    System.out.println("item count combobox2 ="+jComboBox2.getItemCount());
                      jComboBox2.removeAllItems();
                      jComboBox3.removeAllItems();
                  if(jComboBox1.getItemCount()<=0){
                  for (int x = 0;x<fullyear.length-1;x++){
                        this.jComboBox1.addItem(fullyear[x]);
                  for(int x=month;x<fullmonth.length;x++){
                      System.out.println(x);
                      this.jComboBox2.addItem(fullmonth[x]);
                  System.out.println("finish insert month");
                   for(int x = date;x<=maxday;x++ ){
                         this.jComboBox3.addItem(x);
    //System.out.print(year);
                  this.jComboBox1.setSelectedItem(year);
                }why when i select the same item that with my current year in JCombobox1, Jcombobox2 value will become double? i and calling one time reservationstartingshowingdate() only in jbc1. but why it apper double same data? i am trying to understand the code in action listener. hope you all can explain and solve this problem. thank
    Edited by: yjho on Aug 27, 2010 2:54 AM

    In the future, Swing related questions should be posted in the Swing forum.
    MoreOver, when some other window hides frame, string value in hidden portion of frame get erased.Thats because your painting code is in the actionPerformed() method. Everytime a component is repainted the painting is done from scratch, but of course the code in the actionPerformed() method is not executed.
    You need to do your custom painting by extending JComponent or JPanel. All the actionPerformed method does is tell the component to repaint() itself.
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/14painting/index.html]Custom Painting.

  • Java Calendar Help Needed :)

    Hi,
    I am trying to develop a Java Event Calendar which is able to display the calendar weekly. So the JPanel will be setup with 7 JLists for the days of the week. Buttons will allow switching of the days of the week, months and year.
    Each JList corresponding to the day of the week will have its data obtained from the database using JDBC and loaded upon 're-drawing' of the lists.
    However i am having trouble with the GUI side in understanding how to implement this, i am confident with the JList and database side of things, i have just used a similar example using the Calendar API for monthly displays, however i am unsure how to convert this to a weekly calendar.
    Ideally 7 JLists will always be available in the panel in order M,T,W,T,F,S,S but some will be set to inactive (for example in the first and last weeks of the month).
    If anyone has any suggestions please could you help me out :)
    Sorry if what im trying to do is a bit confusing.
    I've included the code i've been using for the monthly calendar
    THANKS!!
    public class CalendarPanel extends JPanel implements ActionListener {
      private Calendar panelDate;
      private Label monthLabel;
      private Label yearLabel;
      private Panel daysPanel;
      private Vector calendarListeners;
      private static final String days[] = {"S","M","T","W","T","F","S"};
      public CalendarPanel(){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        buildUI();
      public CalendarPanel(Calendar date){
        super(new BorderLayout());
        panelDate = (date != null) ? (Calendar)date.clone() : Calendar.getInstance();
        buildUI();
      public CalendarPanel(Date date){
        super(new BorderLayout());
        panelDate = Calendar.getInstance();
        if(date != null) panelDate.setTime(date);
        buildUI();
      public Calendar getCalendar(){ return panelDate;}
      public void setCalendar(Calendar date){
        if(date != null){
          panelDate = (Calendar)date.clone();
          redrawPanel();
      public void setCalendar(Date date){
        if(date != null){
          panelDate.setTime(date);
          redrawPanel();
      public int getYear(){ return panelDate.get(Calendar.YEAR);}
      public String getMonthName(){
        switch(panelDate.get(Calendar.MONTH)){
        case Calendar.JANUARY: return "January";
        case Calendar.FEBRUARY: return "February";
        case Calendar.MARCH: return "March";
        case Calendar.APRIL: return "April";
        case Calendar.MAY: return "May";
        case Calendar.JUNE: return "June";
        case Calendar.JULY: return "July";
        case Calendar.AUGUST: return "August";
        case Calendar.SEPTEMBER: return "September";
        case Calendar.OCTOBER: return "October";
        case Calendar.NOVEMBER: return "November";
        case Calendar.DECEMBER: return "December";
        case Calendar.UNDECIMBER: return "Undecimber";
        default: return "Unknown";
      private void buildUI(){
        this.add(buildHeaderPanel(), BorderLayout.NORTH);
        daysPanel = new Panel(new GridBagLayout());
        redrawPanel();
        this.add(daysPanel, BorderLayout.CENTER);
      // build the part of the gui that contains the month and year
      // labels with their incrementors / decrementors
      private Panel buildHeaderPanel(){
        monthLabel = new Label(getMonthName(), Label.CENTER);
        yearLabel = new Label(Integer.toString(panelDate.get(Calendar.YEAR)),
                     Label.CENTER);
        GridBagConstraints gbc = new GridBagConstraints();
        Panel headerPanel = new Panel(new GridBagLayout());
        // month label and buttons
        Panel panel = new Panel(new GridBagLayout());
        Button button = new Button("-");
        button.setActionCommand("decrease month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(monthLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase month");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        // year label and buttons
        panel = new Panel(new GridBagLayout());
        button = new Button("-");
        button.setActionCommand("decrease year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.EAST;
        gbc.weightx = 0;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(yearLabel, gbc);
        button = new Button("+");
        button.setActionCommand("increase year");
        button.addActionListener(this);
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(button, gbc);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.weightx = 1;
        headerPanel.add(panel, gbc);
        return headerPanel;
      // redraws the entire panel, including relaying out of
      // the days buttons
      private void redrawPanel(){
        monthLabel.setText(getMonthName());
        yearLabel.setText(Integer.toString(getYear()));
        // redraw days panel
        GridBagConstraints gbc = new GridBagConstraints();
        // clear current days panel
        daysPanel.removeAll();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        // add days of week
        for(int i = 0; i < days.length; i++, gbc.gridx++)
          daysPanel.add(new Label(days, Label.CENTER), gbc);
    gbc.gridx = 0;
    gbc.gridy++;
    // days of month
    Button button; // day buttons
    JTable day = new JTable();
    Calendar today = Calendar.getInstance();
    Calendar cellDay = (Calendar)today.clone();
    int month = panelDate.get(Calendar.MONTH);
    int year = panelDate.get(Calendar.YEAR);
    // start with first of panels month
    cellDay.set(year, month, 1);
    gbc.gridx = cellDay.get(Calendar.DAY_OF_WEEK) - 1;
    while( cellDay.get(Calendar.MONTH) == month ){
    if(gbc.gridx > 6){
         gbc.gridy++;
         gbc.gridx = 0;
    button = new Button(Integer.toString(cellDay.get(Calendar.DATE)));
    button.addActionListener(this);
    if( cellDay.equals(today)){
         button.setForeground(Color.red);
    daysPanel.add(button, gbc);
    gbc.gridx++;
    cellDay.add(Calendar.DAY_OF_MONTH, 1);
    // re validate entire panel
    validate();
    // implementation of ActionListener interface
    // currently no real need to create subclassed action
    // events for calendar. All actions generated by this
    // are action events (generated from the buttons).
    // the action command will be one of the four below
    // or a number (the label of the day button!).
    public void actionPerformed(ActionEvent ae){
    String command = ae.getActionCommand();
    if(command.equals("increase month")){
    panelDate.add(Calendar.MONTH, 1);
    redrawPanel();
    } else if(command.equals("decrease month")){
    panelDate.add(Calendar.MONTH, -1);
    redrawPanel();
    } else if(command.equals("increase year")){
    panelDate.add(Calendar.YEAR, 1);
    redrawPanel();
    } else if(command.equals("decrease year")){
    panelDate.add(Calendar.YEAR, -1);
    redrawPanel();
    notifyCalendarListeners(ae);
    // methods for keeping track of interested listeners
    public void addCalendarActionListener(ActionListener al){
    if(al != null){
    if(calendarListeners == null) calendarListeners = new Vector();
    calendarListeners.addElement(al);
    public void removeCalendarActionListener(ActionListener al){
    if((calendarListeners != null) && (al != null)){
    calendarListeners.removeElement(al);
    private void notifyCalendarListeners(ActionEvent ae){
    if((calendarListeners != null) && (!calendarListeners.isEmpty())){
    java.util.Enumeration e = calendarListeners.elements();
    while(e.hasMoreElements())
         ((ActionListener)e.nextElement()).actionPerformed(ae);

    Hi,
    Sorry for the change of screen name, i'm having trouble with my old account.
    I have now got most of the system working. However I am having trouble working out how to stop the last days of the previous month appearing in the first week of the next month. For example on 'July 2008' , days 29 and 30 of June are present in the first week of July. How can i get rid of this? And also for the last week of the month, how to get rid of the first days of the next month?
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Vector;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.EtchedBorder;
    * @category CalendarSystem
    * @author Daniel Barrett
    public class CalendarSystem extends JPanel implements ActionListener, MouseListener, KeyListener   {
         JPanel events = new JPanel();
         JPanel action = new JPanel();
              //Events Panel
         DateComboBox eventDateChooser = new DateComboBox();
         JTextField ref = new JTextField(10);
         JTextArea eventDetails = new JTextArea();
         JScrollPane scrollingArea = new JScrollPane(eventDetails);
         JTextField dateF = new JTextField(15);
         JTextField timeF = new JTextField(15);
         String[] minutes = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
         String[] hours = {"00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
         JComboBox minsComb = new JComboBox(minutes);
         JComboBox hourComb = new JComboBox(hours);
              //Actions Panel
         JButton delete = new JButton("Delete");
         JButton purge = new JButton("Purge");
         JButton add = new JButton("Add");
         JButton edit = new JButton("Edit");
         JButton mview = new JButton("Month View");
         protected JLabel monthLabel;
         protected JLabel weekLabel;
         protected JLabel lmonday = new JLabel("");
         protected JLabel ltuesday = new JLabel("");
         protected JLabel lwednesday = new JLabel("");
         protected JLabel lthursday = new JLabel("");
         protected JLabel lfriday = new JLabel("");
         protected JLabel lsaturday = new JLabel("");
         protected JLabel lsunday = new JLabel("");
         protected Calendar calendar;
         protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
         protected SimpleDateFormat dayFormat = new SimpleDateFormat("MMM");
         JPanel monthCont = new JPanel();
         JPanel weekCont = new JPanel();
         JPanel yearCont = new JPanel();
         JPanel daysOfWeek = new JPanel();
         JPanel monday = new JPanel();
         JPanel tuesday = new JPanel();
         JPanel wednesday = new JPanel();
         JPanel thursday = new JPanel();
         JPanel friday = new JPanel();
         JPanel saturday = new JPanel();
         JPanel sunday = new JPanel();
         JList mondayEvents = new JList();
         JScrollPane mondayEventsScroll = new JScrollPane(mondayEvents);
         JList tuesdayEvents = new JList();
         JScrollPane tuesdayEventsScroll = new JScrollPane(tuesdayEvents);
         JList wednesdayEvents = new JList();
         JScrollPane wednesdayEventsScroll = new JScrollPane(wednesdayEvents);
         JList thursdayEvents = new JList();
         JScrollPane thursdayEventsScroll = new JScrollPane(thursdayEvents);
         JList fridayEvents = new JList();
         JScrollPane fridayEventsScroll = new JScrollPane(fridayEvents);
         JList saturdayEvents = new JList();
         JScrollPane saturdayEventsScroll = new JScrollPane(saturdayEvents);
         JList sundayEvents = new JList();
         JScrollPane sundayEventsScroll = new JScrollPane(sundayEvents);
         protected Color selectedBackground;
         protected Color selectedForeground;
         protected Color background;
         protected Color foreground;
         public CalendarSystem(){
              setupDays();
              setupHeaders();
              setupEvents();
              setupActions();
              this.calendar = Calendar.getInstance();
              this.calendar.setFirstDayOfWeek(Calendar.SUNDAY);
              this.add(this.monthCont);
              this.add(this.daysOfWeek);
              this.add(this.weekCont);
              this.add(this.events);
              this.add(this.action);
              this.setLayout(new BoxLayout(this,1));
              this.setMaximumSize(new Dimension(400,30));
              this.updateCalendar();
         private void setupActions() {
              this.action.setBorder(BorderFactory.createTitledBorder("Actions"));
              this.action.add(this.add);
              this.action.add(this.edit);
              this.action.add(this.delete);
              this.action.add(this.purge);
              this.action.add(this.mview);
         private void setupEvents() {
              this.events.setBorder(BorderFactory.createTitledBorder("Event Details"));
              this.events.setLayout(new BoxLayout(this.events,1));
              JPanel row1 = new JPanel();
              JPanel row2 = new JPanel();
              JPanel row3 = new JPanel();
              JLabel la = new JLabel("Reference");
              JLabel da = new JLabel("Date");
              JLabel time = new JLabel("Time");
              JLabel det = new JLabel("Details");
              this.ref.setEditable(false);
              this.dateF.setEditable(false);
              this.timeF.setEditable(false);
              this.eventDetails.setEditable(false);
              row1.add(la);
              row1.add(this.ref);
              row1.add(da);
              row1.add(this.dateF);
              row1.add(time);
              row1.add(this.timeF);
              row2.add(det);
              scrollingArea.setPreferredSize(new Dimension(600,50));
              row3.add(this.scrollingArea);
              this.events.add(row1);
              this.events.add(row2);
              this.events.add(row3);
         protected JLabel createUpdateButton(final int field, final int amount, final boolean month) {
             final JLabel label = new JLabel();
             final Border selectedBorder = new EtchedBorder();
             final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
             label.setBorder(unselectedBorder);
             label.setForeground(foreground);
             label.addMouseListener(new MouseAdapter() {
                  public void mouseReleased(MouseEvent e) {
                   calendar.add(field, amount);
                   if(month){
                   updateMCalendar();}
                   else{
                        updateCalendar();
                   public void mouseEntered(MouseEvent e) {
                   label.setBorder(selectedBorder);
                  public void mouseExited(MouseEvent e) {
                   label.setBorder(unselectedBorder);
             return label;
         private void updateMCalendar() {
              this.calendar.set(Calendar.DAY_OF_MONTH, 1);
              updateCalendar();     
         private void setupHeaders() {
              //MONTH CONTROLS
             monthCont.setLayout(new BoxLayout(monthCont, BoxLayout.X_AXIS));
             monthCont.setBackground(background);
             monthCont.setOpaque(true);
             JLabel label;
             label = createUpdateButton(Calendar.YEAR, -1,false);
             label.setText("<<");
             label.setToolTipText("Previous Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             label = createUpdateButton(Calendar.MONTH, -1,true);
             label.setText("< ");
             label.setToolTipText("Previous Month");
             monthCont.add(label);
             monthLabel =new JLabel("", JLabel.CENTER);
             monthLabel.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(monthLabel);
             monthCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label =createUpdateButton(Calendar.MONTH, 1,true);
             label.setText(" >");
             label.setToolTipText("Next Month");
             monthCont.add(label);
             label = createUpdateButton(Calendar.YEAR, 1,false);
             label.setText(">>");
             label.setToolTipText("Next Year");
             monthCont.add(Box.createHorizontalStrut(12));
             monthCont.add(label);
             monthCont.add(Box.createHorizontalStrut(12));
             //WEEK CONTROLS
             weekCont.setLayout(new BoxLayout(weekCont, BoxLayout.X_AXIS));
             weekCont.setBackground(background);
             weekCont.setOpaque(true);
             JLabel label1;
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, -1,false);
             label1.setText("<<");
             label1.setToolTipText("Previous Week");
             weekCont.add(label1);
             weekLabel =new JLabel("", JLabel.CENTER);
             weekLabel.setForeground(foreground);
             JLabel lweek =new JLabel("Week:  ", JLabel.CENTER);
             lweek.setForeground(foreground);
             //monthCont.add(Box.createHorizontalGlue());
             weekCont.add(Box.createHorizontalStrut(12));
             weekCont.add(lweek);
             weekCont.add(weekLabel);
             weekCont.add(Box.createHorizontalStrut(12));
             //monthCont.add(Box.createHorizontalGlue());
             label1 = createUpdateButton(Calendar.WEEK_OF_MONTH, 1,false);
             label1.setText(">>");
             label1.setToolTipText("Next Week");
             weekCont.add(label1);
         public void setupDays(){
              monday.setLayout(new BoxLayout(monday,1));
              tuesday.setLayout(new BoxLayout(tuesday,1));
              wednesday.setLayout(new BoxLayout(wednesday,1));
              thursday.setLayout(new BoxLayout(thursday,1));
              friday.setLayout(new BoxLayout(friday,1));
              saturday.setLayout(new BoxLayout(saturday,1));
              sunday.setLayout(new BoxLayout(sunday,1));
              monday.add(this.lmonday);
              monday.add(this.mondayEventsScroll);
              monday.setBorder(BorderFactory.createTitledBorder("Monday"));
              tuesday.add(this.ltuesday);
              tuesday.add(this.tuesdayEventsScroll);
              tuesday.setBorder(BorderFactory.createTitledBorder("Tuesday"));
              wednesday.add(this.lwednesday);
              wednesday.add(this.wednesdayEventsScroll);
              wednesday.setBorder(BorderFactory.createTitledBorder("Wednesday"));
              thursday.add(this.lthursday);
              thursday.add(this.thursdayEventsScroll);
              thursday.setBorder(BorderFactory.createTitledBorder("Thursday"));
              friday.add(this.lfriday);
              friday.add(this.fridayEventsScroll);
              friday.setBorder(BorderFactory.createTitledBorder("Friday"));
              saturday.add(this.lsaturday);
              saturday.add(this.saturdayEventsScroll);
              saturday.setBorder(BorderFactory.createTitledBorder("Saturday"));
              sunday.add(this.lsunday);
              sunday.add(this.sundayEventsScroll);
              sunday.setBorder(BorderFactory.createTitledBorder("Sunday"));
              this.mondayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.monday.setPreferredSize(new Dimension(145,300));
              this.tuesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.tuesday.setPreferredSize(new Dimension(145,300));
              this.wednesdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.wednesday.setPreferredSize(new Dimension(145,300));
              this.thursdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.thursday.setPreferredSize(new Dimension(145,300));
              this.fridayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.friday.setPreferredSize(new Dimension(145,300));
              this.saturdayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.saturday.setPreferredSize(new Dimension(145,300));
              this.sundayEventsScroll.setPreferredSize(new Dimension(90,200));
              this.sunday.setPreferredSize(new Dimension(145,300));
              daysOfWeek.add(this.sunday);
              daysOfWeek.add(this.monday);
              daysOfWeek.add(this.tuesday);
              daysOfWeek.add(this.wednesday);
              daysOfWeek.add(this.thursday);
              daysOfWeek.add(this.friday);
              daysOfWeek.add(this.saturday);
        private void updateCalendar() {
             monthLabel.setText(monthFormat.format(calendar.getTime()) );
             weekLabel.setText(String.valueOf(this.calendar.get(calendar.WEEK_OF_MONTH)));
             //Blank out / empty strings for first elements that do not start on sunday
             Calendar setupCalendar = (Calendar) calendar.clone();
             setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
           // while(setupCalendar.get(Calendar.DAY_OF_WEEK) < calendar.getActualMaximum(Calendar.DAY_OF_WEEK)) {
                //System.out.println("day of month: " + setupCalendar.get(Calendar.DAY_OF_MONTH));
                //System.out.println("day of week: " + (setupCalendar.get(Calendar.DAY_OF_WEEK)));
                //System.out.println("week of month: " + calendar.get(Calendar.WEEK_OF_MONTH) + "\n");
                  setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.get(Calendar.DAY_OF_WEEK) + 1);
                 setDayLabels(setupCalendar.get(Calendar.DAY_OF_MONTH),setupCalendar.get(Calendar.DAY_OF_WEEK));
        public void setDayLabels(int day, int dayOfWeek){
             if(dayOfWeek == 1){
                  this.lsunday.setText(String.valueOf(day));
             if(dayOfWeek == 2){
                  this.lmonday.setText(String.valueOf(day));
             if(dayOfWeek == 3){
                  this.ltuesday.setText(String.valueOf(day));
             if(dayOfWeek == 4){
                  this.lwednesday.setText(String.valueOf(day));
             if(dayOfWeek == 5){
                  this.lthursday.setText(String.valueOf(day));
             if(dayOfWeek == 6){
                  this.lfriday.setText(String.valueOf(day));
             if(dayOfWeek == 7){
                  this.lsaturday.setText(String.valueOf(day));
         @Override
         public void actionPerformed(ActionEvent arg0) {
         @Override
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyReleased(KeyEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyTyped(KeyEvent arg0) {
              // TODO Auto-generated method stub
         public static void main(String args[]){
              JFrame frame = new JFrame();
              frame.setSize(1100, 670);
              frame.add(new CalendarSystem());
              frame.setVisible(true);
    }Thanks
    Dan

  • How many JComboBox in my panel?

    Hi,
    I'm writing a simple JPanel which contains three JComboBox, one for the day, one for the month and one for the year. It works fine and the constructor is the following:
    public class DatePanel extends JPanel implements ItemListener{
         * The combobox for the day.
        protected JComboBox comboDay = null;
         * The combobox for the month.
        protected JComboBox comboMonth = null;
         * The year.
        protected JComboBox comboYear = null;
         * A flag that indicates if the user has manually changed the date.
        protected boolean dateHasChanged = false;
         * Creates and set up each component of this panel.
        protected void setUpGUI(){
         // get the current date
         Calendar today = Calendar.getInstance();
         // create the components
         this.comboDay = new JComboBox();
         for(int i=1; i<=31; i++)
             this.comboDay.addItem(i);
         this.comboMonth = new JComboBox();
         for(int i=1; i<=12; i++)
             this.comboMonth.addItem(i);
         this.comboYear = new JComboBox();
         int currentYear = today.get(Calendar.YEAR);
         for( int i= (currentYear - 60); i< (currentYear + 5); i++)
             this.comboYear.addItem(i);
         // add the null values
         this.comboDay.addItem("--");
         this.comboMonth.addItem("--");
         this.comboYear.addItem("--");
         this.comboDay.setSelectedItem("--");
         this.comboMonth.setSelectedItem("--");
         this.comboYear.setSelectedItem("--");
         // add the listener
         this.comboDay.addItemListener(this);
         this.comboMonth.addItemListener(this);
         this.comboYear.addItemListener(this);
         // display components
         this.setLayout( new FlowLayout() );
         this.add(this.comboDay);
         this.add(this.comboMonth);
         this.add(this.comboYear);
         * Builds a panel without initializing it with a specific date.
        public DatePanel(){
         super();
         this.setUpGUI();
        }then I've got a subclass of the above panel which adds two comboes, one for the hour and one for minute. This is also working fine, and I've got a flag that says if the above three comboes should appear or not in the panel:
    public class TimePanel extends DatePanel {
         * The comboHour selection combo box.
        protected JComboBox comboHour = null;
         * The comboMinute selection combo box.
        protected JComboBox comboMinute = null;
         * Builds the time panel with the specific comboboxes.
         * @param alsoDates true if also the dates should be visibles
        public TimePanel(boolean alsoDates){
         super();
         this.setUpGUI();
         // shuld the dates be available?
         if( ! alsoDates ){
             this.comboDay.setEnabled(false);
             this.comboMonth.setEnabled(false);
             this.comboYear.setEnabled(false);
             this.remove(this.comboDay);
             this.remove(this.comboMonth);
             this.remove(this.comboYear);
         * Sets up the components.
        @Override
        protected void setUpGUI() {
         super.setUpGUI();
         // add the time components
         this.comboHour = new JComboBox();
         for( int i=0; i<24; i++ )
             this.comboHour.addItem(i);
         this.comboHour.addItemListener(this);
         this.comboMinute = new JComboBox();
         for(int i=0; i<60; i++)
             this.comboMinute.addItem(i);
         this.comboMinute.addItemListener(this);
         this.add(new JLabel("hh:"));
         this.add(this.comboHour);
         this.add(new JLabel("mm:"));
         this.add(this.comboMinute);
        }As you can see, when I pass false to the constructor of the TimePanel, the comboes of the date panel are removed from the layout of the panel itself, thus showing only the hour and minute ones.
    Now I was writing a JUnit test for this, and surprisingly when I run a code like the following:
         TimePanel tp1 = timePanel = new TimePanel(false);
         Component[] components = tp1.getComponents();
         int comboCount = 0;
         // count how many jcombobox there are, since it has been initialized
         // with the time only, it should contain only 2 combobox (hour and minutes)
         for(int i=0;i<components.length; i++ )
             if( components[i] instanceof JComboBox )
              comboCount ++;I found that the number of comboes on my panel are 7[, that is more than the max (5) when all the components are displayed. What is wrong here?
    Thanks,
    Luca

    I found that the problem seems to be in the setUpGui method, that is called from the parent constructor and from the child constructor, thus displaying 7 comboes. But if I remove the call from the child constructor then it seems as the parent comboes are uninitialized and thus I got a nullpointer exception.
    If I modify the constructor of the TimePanel into this:
       public TimePanel(boolean alsoDates){
         this.setUpGUI();
         // shuld the dates be available?
         if( ! alsoDates ){
             this.comboDay.setEnabled(false);
             this.comboMonth.setEnabled(false);
             this.comboYear.setEnabled(false);
             this.remove(this.comboDay);
             this.remove(this.comboMonth);
             this.remove(this.comboYear);
        }and explicity call the super.setupgui into the setupgui method
      protected void setUpGUI() {
         super.setUpGUI();
         // add the time components
         this.comboHour = new JComboBox();
         for( int i=0; i<24; i++ )
             this.comboHour.addItem(i);
         this.comboHour.addItemListener(this);
         this.comboMinute = new JComboBox();
         for(int i=0; i<60; i++)
             this.comboMinute.addItem(i);
         this.comboMinute.addItemListener(this);
         this.add(new JLabel("hh:"));
         this.add(this.comboHour);
         this.add(new JLabel("mm:"));
         this.add(this.comboMinute);
        }I got that the hour and minute comboes are added twice, and moreover the day,month and year are not removed. What is the right way to call the setupgui method to do what I'd like?
    Luca

  • JComboBox doesn't show data...help please

    I have created a JComboBox. I place an array of strings in that jcombobox. I'm sure the data is there, however, it is not shown.
    I traced the problem back to light/heavy weight problems.
    When i use a lightweight JComboBox it doesn't drop down at all.
    This is probably because there's a JLabel under it.
    However, when i mean it an heavyweight object
    (by calling PopupMenu.setLightWeightPopupEnabled(false) )
    the dropdown shows up but it is empty.
    Has anyone had the same problem or something similar?
    help would be appreciated...
    thanx.

    Well here's a code snippet:
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    Calendar cal = Calendar.getInstance();
    Integer[] years = new Integer[21];
    Integer[] months = new Integer[13];
    Integer[] days = new Integer[32];
    for(int i = 0; i < 20; i++)
    years[i] = new Integer(cal.get(Calendar.YEAR) + i);
    startDateYear = new JComboBox(years);
    startDateYear.setMaximumRowCount(3);
    Now here you see how i fillup the JComboBoxes, i've already verified that there actually are objects in the JComboBox so that's not the problem.
    the first line of code is to make the JComboBoxes make a popupmenu that's heavyweight.
    so it should be in front of other lightweighted components (namely a JLabel underneath the JComboBox ) .
    Now i see it drop down, however it shows absolutely no data. It doesn't even show a scrollbar, you can just see gray space outline of where the dropdown menu of the JComboBox should be.
    does this help?

  • Date & Calendar GUI solution

    My GUI must allow users to input date (month, day, year). Does anybody know if there is a utility in swing package which helps to anable this feature?
    I've tried to implement this using 3 JComboBoxes but that looks awkward & doesn't work properly.
    Please, does anybody knows anything about Date & Calendars for GUI

    Look there...
    http://www.toedtercom.de/en/jcalendar.html

  • Need help with Calendar class

    I am writing a class that does the following:
    Uses JComboBoxes so that the user can select Day, Month, and Year. I have the months set up January through December. When I choose a month, I wrote a subclass that gets the chosen month and enters the correct number of days in the Day ComboBox.
    Here is some sample code:
    // This code is in the main class
    monthList.addActionListener(new SelectedMonth());
    // This code is in the SelectedMonth subclass
    selected = monthList.getSelectedIndex();
    switch(selected) {
    case 0: // for January
    dayList.removeAllItems();
    g.set(Calendar.MONTH, selected);
    max = g.getActualMaximum(Calendar.DAY_OF_MONTH);
    for(int i = 1; i <= max; i++) {
    dayList.addItem(new Integer(i));
    This code is repeated for Cases 1 through 11 to cover the other months.
    After Day, Month, and Year are selected, I click an OK button and then want to send the chosen Day, Month, and Year to a database. So, I have another subclass which uses ActionListener and gets the data from the Month, Day, and Year ComboBoxes.
    However, I get runtime errors when retrieving the chosen Day using the following command:
    String fromDay = (String)dayList.getSelectedItem();
    Because the Days were put put into the Day JComboBox in a subclass, this doesn't want to work.
    Does anybody have a solution? Any help would be greatly appreciated.
    If you would like to look at all of my code, leave your e-mail address and I'll let you have a look.

    Hi,
    i got solution for ur problem, here u copy the following code and paste in some editor and try to run to see the results.
    import java.io.*;
    import java.awt.*;
    import java.util.Calendar;
    import java.awt.event.*;
    import javax.swing.*;
    public class CalExample extends JFrame
         private String months[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
         private     JComboBox monthList=new JComboBox(months);
         private     JComboBox dayList=new JComboBox();
         private JButton button=new JButton();
         private int selectedMonth=1;
         private int selectedDay=1;
         public static void main(String[] args)
                        CalExample pe=new CalExample();
         public CalExample()
              JPanel panel=new JPanel();
              panel.setBackground(Color.blue);
              panel.setLayout(null);
              // Month Combo Box related init Stuff
              monthList.setBounds(100,30,100,20);
              monthList.setBackground(Color.white);
              // Day Combo Box related init Stuff
              dayList.setBounds(220,30,100,20);
              dayList.setBackground(Color.white);
              // Output textbox init stuff
              button.setBounds(340,30,100,20);
              button.setText(" Click Me ");
              panel.add(monthList);
              panel.add(dayList);
              panel.add(button);
              getContentPane().add(panel);
              setSize(500,300);
              setVisible(true);
              // Adding Listeners
              monthList.addActionListener
                        new ActionListener()
                                  public void actionPerformed(ActionEvent ae)
                                            selectedMonth=monthList.getSelectedIndex();
                                            showDays(selectedMonth);
              button.addActionListener
                        new ActionListener()
                                  public void actionPerformed(ActionEvent ae)
                                            selectedDay=dayList.getSelectedIndex();
                                       JOptionPane.showMessageDialog(null,"You Selected Month : "+(months[selectedMonth])+",--> Day : "+(selectedDay+1));
              addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent we)
                        System.out.println( " Exiting ...");
                        System.exit(0);
              fillCurrentDate();
         public void showDays(int selectedMonth)
              Calendar cal=Calendar.getInstance();
              cal.set(Calendar.MONTH,selectedMonth);
              int maxDays=cal.getActualMaximum(Calendar.DAY_OF_MONTH);
              dayList.removeAllItems();
              for(int i=1;i<=maxDays;i++)
                   dayList.addItem(String.valueOf(i));
         public void fillCurrentDate()
                   Calendar cal=Calendar.getInstance();
                   showDays(cal.get (Calendar.DAY_OF_MONTH));
    HAPPY CODING...
    regards
    Bandi
    mail : [email protected], [email protected]
    ****************** Think Green, Save Green ***************************

  • Editable JComboBox in JTable focus issue

    Please look at the sample code below.
    I am using a JComboBox as the editor for a column in the table. When a cell in that column is edited and the user presses enter, the cell is no longer in edit mode. However, the focus is now set on the next component in the scrollpane (which is a textfield).
    If I don't add the textfield and the the table is the only component in the scroll pane, then focus correctly remains on the selected cell.
    When the user exits edit mode, I'd like the table to have focus and for the cell to remain selected. How can I achieve this?
    thanks,
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import javax.swing.plaf.basic.*;
    import java.awt.Component;
    import javax.swing.JComboBox;
    import java.util.EventObject;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TableComboBoxTest extends JFrame {
         protected JTable table;
         public TableComboBoxTest() {
              Container pane = getContentPane();
              pane.setLayout(new BorderLayout());
              MyTableModel model = new MyTableModel();
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setSurrendersFocusOnKeystroke(true);
              TableColumnModel tcm = table.getColumnModel();
              TableColumn tc = tcm.getColumn(MyTableModel.GENDER);
              tc.setCellEditor(new MyGenderEditor(new JComboBox()));
              tc.setCellRenderer(new MyGenderRenderer());
              JScrollPane jsp = new JScrollPane(table);
              pane.add(jsp, BorderLayout.CENTER);          
              pane.add(new JTextField("focus goes here"), BorderLayout.SOUTH);
         public static void main(String[] args) {
              TableComboBoxTest frame = new TableComboBoxTest();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(500, 300);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public class MyTableModel extends AbstractTableModel {
              public final static int FIRST_NAME = 0;
              public final static int LAST_NAME = 1;
              public final static int DATE_OF_BIRTH = 2;
              public final static int ACCOUNT_BALANCE = 3;
              public final static int GENDER = 4;
              public final static boolean GENDER_MALE = true;
              public final static boolean GENDER_FEMALE = false;
              public final String[] columnNames = {
                   "First Name", "Last Name", "Date of Birth", "Account Balance", "Gender"
              public Object[][] values = {
                        "Clay", "Ashworth",
                        new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
                        new Float(12345.67), "three"
                        "Jacob", "Ashworth",
                        new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
                        new Float(23456.78), "three1"
                        "Jordan", "Ashworth",
                        new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
                        new Float(34567.89), "three2"
                        "Evelyn", "Kirk",
                        new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
                        new Float(-456.70), "One"
                        "Belle", "Spyres",
                        new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
                        new Float(567.00), "two"
              public int getRowCount() {
                   return values.length;
              public int getColumnCount() {
                   return values[0].length;
              public Object getValueAt(int row, int column) {
                   return values[row][column];
              public void setValueAt(Object aValue, int r, int c) {
                   values[r][c] = aValue;
              public String getColumnName(int column) {
                   return columnNames[column];
              public boolean isCellEditable(int r, int c) {
                   return c == GENDER;
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList()
                   return listBox;
         public class MyGenderRenderer extends DefaultTableCellRenderer{
              public MyGenderRenderer() {
                   super();
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                   JComboBox box = new JComboBox();
                   box.addItem(value);
                   return box;
         public class MyGenderEditor extends DefaultCellEditor  { // implements CaretListener {
              protected EventListenerList listenerList = new EventListenerList();
              protected ChangeEvent changeEvent = new ChangeEvent(this);
              private JTextField comboBoxEditorTField;
              Object newValue;
              JComboBox _cbox;
              public MyGenderEditor(JComboBox cbox) {
                   super(cbox);
                   _cbox = cbox;
                   comboBoxEditorTField = (JTextField)_cbox.getEditor().getEditorComponent();
                   _cbox.addItem("three");
                   _cbox.addItem("three1");
                   _cbox.addItem("three2");
                   _cbox.addItem("One");
                   _cbox.addItem("two");
                   _cbox.setEditable(true);
                   _cbox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                             System.out.println("\nactionPerformed ");
                             fireEditingStopped();
              public void addCellEditorListener(CellEditorListener listener) {
                   listenerList.add(CellEditorListener.class, listener);
              public void removeCellEditorListener(CellEditorListener listener) {
                   listenerList.remove(CellEditorListener.class, listener);
              protected void fireEditingStopped() {
                   System.out.println("fireEditingStopped called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             System.out.println("calling editingStopped on listener....................");                    
                             listener = (CellEditorListener) listeners;
                             listener.editingStopped(changeEvent);
              protected void fireEditingCanceled() {
                   System.out.println("fireEditingCanceled called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             listener = (CellEditorListener) listeners[i];
                             listener.editingCanceled(changeEvent);
              public void cancelCellEditing() {
                   System.out.println("cancelCellEditing called ");
                   fireEditingCanceled();
              public void addNewItemToComboBox() {
                   System.out.println("\naddNewItemToComboBox called ");
                   // tc - start
                   String text = comboBoxEditorTField.getText();
                   System.out.println("text = "+text);                    
                   int index = -1;
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in cbox = "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");                              
                             index = i;
                             _cbox.setSelectedIndex(index);
                             break;
                   if (index == -1)
                        _cbox.addItem(text);
                        int count = _cbox.getItemCount();
                        _cbox.setSelectedIndex(count -1);
              public boolean stopCellEditing() {
                   System.out.println("stopCellEditing called ");
                   fireEditingStopped();
                   _cbox.transferFocus();
                   return true;
              public boolean isCellEditable(EventObject event) {
                   return true;     
              public boolean shouldSelectCell(EventObject event) {
                   return true;
              public Object getCellEditorValue() {
                   System.out.println("- getCellEditorValue called returning val: "+_cbox.getSelectedItem());
                   return _cbox.getSelectedItem();
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   System.out.println("\ngetTableCellEditorComponent "+value);
                   String text = (String)value;               
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in box "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");     
                             _cbox.setSelectedIndex(i);
                             break;
                   return _cbox;

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

  • JComboBox problem (another one)

    I'm using a JComboBox with a LOV.
    1) The combo-box is sized for the largest LOV. Can I have different widths for the drop-down and the combo-box itself? Is the model setting the preferredSize of my JComboBox?
    2) If the first dropdown value is rather short, then when a long selection is chosen, the value is shown truncated with ... after it. If the first dropdown value is as long as the selected one, then the value is displayed correctly.
    Regards,
    Tony Clulow

    Fliz:
    Welcome to the Apple Discussions. Yes I believe it an issue with the Helvetica Neue font. Open Font Book and deactivate the font. Then reactivate it and launch iPhoto. That should fix it.
    Do you Twango?
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.
    I've written an Automator workflow application (requires Tiger), iPhoto dB File Backup, that will copy the selected Library6.iPhoto file from your iPhoto Library folder to the Pictures folder, replacing any previous version of it. It's compatible with iPhoto 08 libraries. You can download it at Toad's Cellar. Be sure to read the Read Me pdf file.

  • Anyone built date/calendar popup??

    I have a third party calendar popup set of classes that I wish to use in a JTable.
    The JTable editor/renderer does not seem to work with this class. (Third party components fault)
    Has anyone developed their own calendar popup that can be used within a JTable to set dates.
    I'm working with JDK1.3, therefore cannot use JFormattedTextField, mores the pity!!!
    Any help/tips appreciated.
    Thanks,
    Rachel

    I did this about a year ago. I used Claude Dugay's JMaskField instead of JFormattedTextField. It's easy to find, but it needs to have some patches for a few quirks. You will probably recognize a lot of the code. I tried to make it handle a variety of Object types (Date, String, Calendar). I also needed an extra value (N/A for example). Here's the main class.import com.bbritta.jmaskfield.JMaskField;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.EtchedBorder;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import javax.swing.plaf.basic.ComboPopup;
    import javax.swing.plaf.ComboBoxUI;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    import javax.swing.plaf.metal.MetalComboBoxUI;
    import com.sun.java.swing.plaf.motif.MotifComboBoxUI;
    import com.sun.java.swing.plaf.windows.WindowsComboBoxUI;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.Vector;
    import java.util.EventListener;
    public class DateComboBox extends JComboBox {
        private final static SimpleDateFormat defaultSDF = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat sdf;
        Class returnClass=null;
        FormattedCalendar fc = new FormattedCalendar(sdf);
        Object alternate=null;
        MyComboBoxEditor mcbe;
        KeyAdapter ka = new KeyAdapter() {
         public void keyReleased(KeyEvent ke) {
             JTextField jtf = (JTextField)ke.getSource();
             switch (ke.getKeyCode()) {
              case KeyEvent.VK_ESCAPE:
                  jtf.setText(fc.toString());
                  break;
              case KeyEvent.VK_ENTER:
                  setValue(jtf.getText());
                  javax.swing.FocusManager.getCurrentManager().focusNextComponent(jtf);
                  break;
        JMaskField jmf = null;
        JTextField editorComponent;
        boolean blockItemStateEvent=false, blockActionEvent=false;
        private DatePopup datePopup;
        public DateComboBox(JMaskField JMF, SimpleDateFormat SDF) {
         this(SDF);
         setEditor(mcbe = new MyComboBoxEditor(jmf=JMF));
         ((JTextField)getEditor().getEditorComponent()).addKeyListener(ka);
        public DateComboBox(JMaskField JMF) { this(JMF, defaultSDF); }
        public DateComboBox(SimpleDateFormat SDF) {
         setFormat(sdf=SDF);
         editorComponent = (JTextField)getEditor().getEditorComponent();
         addItem(fc);
         editorComponent.addKeyListener(ka);
        public DateComboBox() {
         this(defaultSDF);
        // JComboBox source code sez not to override this, but waddahell
        public void actionPerformed(ActionEvent ae) {
         setValue(getEditor().getItem());
        public void setReturnClass(Class aClass) {
         if (aClass==null || aClass==String.class || aClass==Date.class ||
                       aClass.isAssignableFrom(Calendar.class)) {
             returnClass=aClass;
         } else throw new IllegalArgumentException("Invalid return class");
        public Class getReturnClass() { return returnClass; }
        public void setSelectedItem(Object item) { setValue(item); }
        public void setValue(Object value) {
         ((JTextField)getEditor().getEditorComponent()).setEditable(true);
         Object oldSelectedItem = super.getSelectedItem();
         blockActionEvent=true;
         blockItemStateEvent=true;
         dataModel.setSelectedItem(null);
         blockActionEvent=false;
         blockItemStateEvent=false;
         if (value instanceof Date) {
             if (jmf!=null) jmf.setMaskDocument();
             fc.setTime((Date)value);
             super.setSelectedItem(fc);
         } else if (value instanceof Calendar) {
             if (jmf!=null) jmf.setMaskDocument();
             fc.setTime(((Calendar)value).getTime());
             super.setSelectedItem(fc);
         } else if (alternate!=null && alternate.toString().equalsIgnoreCase(value.toString())) {
             if (jmf!=null) jmf.setOrigDocument();
             super.setSelectedItem(alternate);
             ((JTextField)getEditor().getEditorComponent()).setEditable(false);
         } else if (value instanceof String) {
             try {
              fc.setTime((String)value);
              super.setSelectedItem(fc);
              if (jmf!=null) jmf.setMaskDocument();
             catch (ParseException pe) {
              if (jmf!=null) jmf.setMaskDocument();
              super.setSelectedItem(value);
              fireInvalidDate(new InvalidDateEvent(this, value));
         } else {
             if (jmf!=null) jmf.setMaskDocument();
             fireInvalidDate(new InvalidDateEvent(this, value));
        public void addInvalidDateListener(InvalidDateListener l) {
         listenerList.add(InvalidDateListener.class, l);
        public void removeInvalidDateListener(InvalidDateListener l) {
         listenerList.remove(InvalidDateListener.class, l);
        protected void fireInvalidDate(final InvalidDateEvent e) {
         final Object[] listeners = listenerList.getListenerList();
    //     System.out.println("SI="+super.getSelectedIndex()+", lc="+listeners.length);
         SwingUtilities.invokeLater(new Runnable() { public void run() {
             for (int i=listeners.length-2; i>=0; i-=2 ) {
              if (listeners==InvalidDateListener.class ) {
              ((InvalidDateListener)listeners[i+1]).invalidDate(e);
    protected void fireActionEvent() {
         if (!blockActionEvent) super.fireActionEvent();
    protected void fireItemStateChanged(ItemEvent e) {
         if (!blockItemStateEvent) super.fireItemStateChanged(e);
    public Object getValue() {
         Object selectedItem = super.getSelectedItem();
         if (selectedItem==fc) {
         if (jmf != null) jmf.setMaskDocument();
         if (returnClass==null || returnClass==Calendar.class) return fc;
         if (returnClass==Date.class) return fc.getTime();
         if (returnClass==String.class) return fc.toString();
         } else if (selectedItem==alternate) if (jmf!=null) jmf.setOrigDocument();
         else if (jmf!=null) jmf.setMaskDocument();
         return selectedItem;
    public void setAlternate(Object Alternate) {
         if (alternate != null) super.removeItem(alternate);
         datePopup.setAlternate(Alternate);
         alternate = Alternate;
         super.addItem(alternate);
    public Object getAlternate() { return alternate; }
    public void updateUI() {
         ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
         if (cui instanceof MetalComboBoxUI) { cui = new MetalDateComboBoxUI(); }
         else if (cui instanceof MotifComboBoxUI) { cui = new MotifDateComboBoxUI(); }
         else if (cui instanceof WindowsComboBoxUI) { cui = new WindowsDateComboBoxUI(); }
         setUI(cui);
    class MetalDateComboBoxUI extends MetalComboBoxUI {
         protected ComboPopup createPopup() { return datePopup = new DatePopup(comboBox, sdf); }
    class WindowsDateComboBoxUI extends WindowsComboBoxUI {
         protected ComboPopup createPopup() { return datePopup = new DatePopup(comboBox, sdf); }
    class MotifDateComboBoxUI extends MotifComboBoxUI {
         protected ComboPopup createPopup() { return datePopup = new DatePopup(comboBox, sdf); }
    public void setFormat(SimpleDateFormat SDF) {
         datePopup.setFormat(SDF);
         fc.setFormat(SDF);
    public SimpleDateFormat getFormat() { return sdf; }
    class DatePopup implements ComboPopup, MouseMotionListener, MouseListener,
                   KeyListener, PopupMenuListener, ActionListener {
    private static final SimpleDateFormat defaultSDF = new SimpleDateFormat("MM/dd/yy");
    // protected SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy");
    protected SimpleDateFormat dateFormat;// = new SimpleDateFormat("MM/dd/yy");
    protected DateComboBox comboBox;
    protected Calendar calendar;
    protected JPopupMenu popup;
    protected JLabel monthLabel;
    protected JPanel days = null, alternatePanel = new JPanel(new FlowLayout());
    protected JButton alternateButton = new JButton();
    protected Vector listenerComponents = new Vector();
    protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
    protected void setFormat(SimpleDateFormat SDF) { dateFormat=SDF; }
    protected Color selectedBackground, selectedForeground,
                   background, foreground;
    public DatePopup(JComboBox comboBox) {
         this(comboBox, defaultSDF);
    public DatePopup(JComboBox comboBox, SimpleDateFormat SDF) {
         dateFormat = SDF;
         this.comboBox = (DateComboBox)comboBox;
         calendar = Calendar.getInstance();
         // check Look and Feel
         background = UIManager.getColor("ComboBox.background");
         foreground = UIManager.getColor("ComboBox.foreground");
         selectedBackground = UIManager.getColor("ComboBox.selectionBackground");
         selectedForeground = UIManager.getColor("ComboBox.selectionForeground");
         alternatePanel.setBackground(background);
         alternatePanel.setOpaque(true);
         alternateButton.setBorder(BorderFactory.createRaisedBevelBorder());
         alternatePanel.add(alternateButton);
         alternateButton.addActionListener(this);
         initializePopup();
    //========================================
    // begin ComboPopup method implementations
    public void show() {
         try {
         // if setSelectedItem() was called with a valid date, adjust the calendar
         calendar.setTime( dateFormat.parse( comboBox.getSelectedItem().toString() ) );
         } catch (Exception e) {}
         updatePopup();
         popup.show(comboBox, 0, comboBox.getHeight());
    public void hide() {
         for (int i=0; i<listenerComponents.size(); i++) {
         Component c = (Component)listenerComponents.get(i);
         EventListener[] l = c.getListeners(MouseListener.class);
         for (int j=0; j<l.length; j++) c.removeMouseListener((MouseListener)l[j]);
         listenerComponents.removeAllElements();
         popup.removePopupMenuListener(this);
         popup.setVisible(false);
    protected JList list = new JList();
    public JList getList() { return list; }
    public MouseListener getMouseListener() { return this; }
    public MouseMotionListener getMouseMotionListener() { return this; }
    public KeyListener getKeyListener() { return this; }
    public boolean isVisible() { return popup.isVisible(); }
    public void uninstallingUI() { popup.removePopupMenuListener(this); }
    // end ComboPopup method implementations
    //======================================
    //===================================================================
    // begin Event Listeners
    // MouseListener
    public void mousePressed( MouseEvent e ) {}
    public void mouseReleased( MouseEvent e ) {}
    // something else registered for MousePressed
    public void mouseClicked(MouseEvent e) {
         if ( !SwingUtilities.isLeftMouseButton(e) ) return;
         if ( !comboBox.isEnabled() ) return;
         if ( comboBox.isEditable() ) {
         comboBox.getEditor().getEditorComponent().requestFocus();
         } else comboBox.requestFocus();
         togglePopup();
    protected boolean mouseInside = false;
    public void mouseEntered(MouseEvent e) { mouseInside = true; }
    public void mouseExited(MouseEvent e) { mouseInside = false; }
    // MouseMotionListener
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    // KeyListener
    public void keyPressed(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}
    public void keyReleased( KeyEvent e ) {
         if ( e.getKeyCode() == KeyEvent.VK_SPACE ||
         e.getKeyCode() == KeyEvent.VK_ENTER ) {
         togglePopup();
    * Variables hideNext and mouseInside are used to
    * hide the popupMenu by clicking the mouse in the JComboBox
    public void popupMenuCanceled(PopupMenuEvent e) {}
    protected boolean hideNext = false;
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
         hideNext = mouseInside;
    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}
    // end Event Listeners
    //=================================================================
    //===================================================================
    // begin Utility methods
    protected void togglePopup() {
         if ( isVisible() || hideNext ) hide();
         else show();
         hideNext = false;
    // end Utility methods
    //=================================================================
    // Note *** did not use JButton because Popup closes when pressed
    protected JLabel createUpdateButton(final int field, final int amount) {
         final JLabel label = new JLabel();
         final Border selectedBorder = new EtchedBorder();
         final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
         label.setBorder(unselectedBorder);
         label.setForeground(foreground);
         label.addMouseListener(new MouseAdapter() {
              public void mouseReleased(MouseEvent e) {
              calendar.add(field, amount);
              updatePopup();
              public void mouseEntered(MouseEvent e) {
              label.setBorder(selectedBorder);
              public void mouseExited(MouseEvent e) {
              label.setBorder(unselectedBorder);
         return label;
    protected void setAlternate(Object Alternate) {
         if (Alternate != null) {
         alternateButton.setText(Alternate.toString());
         if (alternatePanel.getParent()!=popup) popup.add(alternatePanel, BorderLayout.SOUTH);
         } else popup.remove(alternatePanel);
    protected void initializePopup() {
         JPanel header = new JPanel(); // used Box, but it wasn't Opaque
         header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
         header.setBackground(background);
         header.setOpaque(true);
         JLabel label;
         label = createUpdateButton(Calendar.YEAR, -1);
         label.setText("<<");
         label.setToolTipText("Previous Year");
         header.add(Box.createHorizontalStrut(12));
         header.add(label);
         header.add(Box.createHorizontalStrut(12));
         label = createUpdateButton(Calendar.MONTH, -1);
         label.setText("<");
         label.setToolTipText("Previous Month");
         header.add(label);
         monthLabel = new JLabel("", JLabel.CENTER);
         monthLabel.setForeground(foreground);
         header.add(Box.createHorizontalGlue());
         header.add(monthLabel);
         header.add(Box.createHorizontalGlue());
         label = createUpdateButton(Calendar.MONTH, 1);
         label.setText(">");
         label.setToolTipText("Next Month");
         header.add(label);
         label = createUpdateButton(Calendar.YEAR, 1);
         label.setText(">>");
         label.setToolTipText("Next Year");
         header.add(Box.createHorizontalStrut(12));
         header.add(label);
         header.add(Box.createHorizontalStrut(12));
         popup = new JPopupMenu();
         popup.setBorder(BorderFactory.createLineBorder(Color.black));
         popup.setLayout(new BorderLayout());
         popup.setBackground(background);
         popup.addPopupMenuListener(this);
         popup.add(BorderLayout.NORTH, header);
    private SimpleDateFormat dowSDF = new SimpleDateFormat("EEE");
    public void actionPerformed(ActionEvent ae) {
         comboBox.setSelectedItem(comboBox.getAlternate());
         hide();
    // update the Popup when either the month or the year of the calendar has been changed
    protected void updatePopup() {
         monthLabel.setText( monthFormat.format(calendar.getTime()) );
         if (days != null) {
         popup.remove(days);
         days = new JPanel(new GridLayout(0, 7));
         days.setBackground(background);
         days.setOpaque(true);
         Calendar setupCalendar = (Calendar) calendar.clone();
         setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
         for (int i = 0; i < 7; i++) {
         int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
         JLabel label = new JLabel(dowSDF.format(setupCalendar.getTime()));
         label.setHorizontalAlignment(JLabel.CENTER);
         label.setForeground(foreground);
         days.add(label);
         setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
         setupCalendar = (Calendar) calendar.clone();
         setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
         int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
         for (int i = 0; i < (first - 1); i++) days.add(new JLabel(""));
         for (int i = 1; i <= setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
         final int day = i;
         final JLabel label = new JLabel(String.valueOf(day));
         label.setHorizontalAlignment(JLabel.CENTER);
         label.setForeground(foreground);
         listenerComponents.add(label);
         label.addMouseListener(new MouseAdapter() {
              public void mouseReleased(MouseEvent e) {
                   label.setOpaque(false);
                   label.setBackground(background);
                   label.setForeground(foreground);
                   calendar.set(Calendar.DAY_OF_MONTH, day);
                   comboBox.setSelectedItem(calendar);
                   hide();
                   comboBox.requestFocus();
              public void mouseEntered(MouseEvent e) {
                   label.setOpaque(true);
                   label.setBackground(selectedBackground);
                   label.setForeground(selectedForeground);
              public void mouseExited(MouseEvent e) {
                   label.setOpaque(false);
                   label.setBackground(background);
                   label.setForeground(foreground);
         days.add(label);
         popup.add(BorderLayout.CENTER, days);
         popup.pack();
    class MyComboBoxEditor extends BasicComboBoxEditor {
    public MyComboBoxEditor() {}
    public MyComboBoxEditor(JMaskField JMF) {
         super.editor = JMF;

Maybe you are looking for

  • Change background color of List Title

    I am able to change the text color however, I am not able to change the background color of the Title on my List. The list template I am using is Vertical Unordered List without Bullets. Here is my code : <span style="color:pink"; "background-color:b

  • Resolution problems

    Making slide show in Premiere Elements 7. Individual frames look good in monitor, but when I play it as a slideshow or movie, resolution goes to the devil. Is this serious? Is there a fix? Is there a way to play it so the resolution improves? (First

  • Automatically creating startup items with a new account

    I'm managing some Macs on an Active Directory network. They're all tied in and working fine as AD connected computers, but as an administrator of these Macs I'd like to make it so that when a user logs in to the domain, the Mac automatically adds som

  • Report server creation fails

    Dear All, When we try to create a new report server it throws the error. Command : opmnctl createcomponent -adminUsername username -adminHost myserverhost -adminPort myserverport -oracleHome E:\Oracle\Middleware\oracle_common -oracleInstance E:\Oracl

  • Dbus error when trying to play dvd

    i get this message when I try to watch a dvd with totem: A security policy in place prevents this sender from sending this message to this recipient, see message bus configuration file (rejected message had interface "org.freedesktop.Hal.Device.Volum