0

Changing foreground colour of a specified index of items in a JComboBox.

Eg,

if (number <= 1) { set the first item of the JComboBox to Red. }

Any way to do this without using CellRenderer? Never ever used CellRenderer before, no experience at all..

Already looked at these sites: Changing a color chooser button's background color in Java, Multiple Colors for Each Item in JComboBox, Colored jcombobox with colored items and focus

3rd one seems to be the most useful but no idea on how to implement..

Thank you.

Codes For Frame:

public class CreateBedForm extends JFrame {

private JPanel contentPane;
private JTextField textFieldPatientID;
private JTextField textFieldPatientName;
private JComboBox comboBoxAllocateBed;
private JComboBox comboBoxDpt;
private String bedStatusF = "Available";
private String selectedDepartment = "";

private int bedsAvailCardio;
private int bedsAvailOncology;
private int bedsAvailOrtho;
private int bedsAvailPediatric;

String[] departments = {"--Select Department--", "Cardiothoracic", "Oncology", "Orthopaedic", "Pediatric"};

Color comboBoxColour = new Color(0, 204, 0);

Color[] colorsForMain = {Color.BLACK, comboBoxColour, comboBoxColour, comboBoxColour, comboBoxColour};

Color[] colorsForCardiothoracic = {Color.BLACK, Color.RED, comboBoxColour, comboBoxColour, comboBoxColour};

Color[] colorsForOncology = {Color.BLACK, comboBoxColour, Color.RED, comboBoxColour, comboBoxColour};

Color[] colorsForOrthopaedic = {Color.BLACK, comboBoxColour, comboBoxColour, Color.RED, comboBoxColour};

Color[] colorsForPediatric = {Color.BLACK, comboBoxColour, comboBoxColour, comboBoxColour, Color.RED};




/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                CreateBedForm frame = new CreateBedForm("", "", "");
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public CreateBedForm(String val1, String val2, String admissionID) {
    setTitle("Assign Bed");
    setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 450, 400);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblPatientId = new JLabel("Patient ID:");
    lblPatientId.setBounds(42, 52, 71, 16);
    contentPane.add(lblPatientId);

    JLabel lblPatientName = new JLabel("Patient Name:");
    lblPatientName.setBounds(42, 97, 96, 16);
    contentPane.add(lblPatientName);

    textFieldPatientID = new JTextField();
    textFieldPatientID.setEditable(false);
    textFieldPatientID.setBounds(138, 49, 116, 22);
    contentPane.add(textFieldPatientID);
    textFieldPatientID.setColumns(10);

    textFieldPatientName = new JTextField();
    textFieldPatientName.setEditable(false);
    textFieldPatientName.setBounds(138, 94, 116, 22);
    contentPane.add(textFieldPatientName);
    textFieldPatientName.setColumns(10);

    JLabel lblAllocatedBed = new JLabel("Allocated Bed:");
    lblAllocatedBed.setBounds(42, 183, 96, 16);
    contentPane.add(lblAllocatedBed);

    comboBoxAllocateBed = new JComboBox();
    comboBoxAllocateBed.setBounds(138, 180, 71, 22);
    contentPane.add(comboBoxAllocateBed);

    JLabel lblNewLabel = new JLabel("Department:");
    lblNewLabel.setBounds(42, 142, 96, 16);
    contentPane.add(lblNewLabel);

    JButton btnAssignBed = new JButton("Assign Bed");
    btnAssignBed.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            //Adding

            String patientID = textFieldPatientID.getText();
            String patientName = textFieldPatientName.getText();

            String selectedDepartment = comboBoxDpt.getSelectedItem().toString();

            String selectedBed = comboBoxAllocateBed.getSelectedItem().toString();

            ChangeBed cb = new ChangeBed(selectedBed, selectedDepartment, patientID, patientName);

            ChangeBedControl cbc = new ChangeBedControl();

            cbc.processAssignBeds(cb, selectedBed);

            //Updating 

            bedStatusF = "Unavailable";

            ChangeBed cb2 = new ChangeBed(selectedBed, selectedDepartment, patientID, patientName);

            ChangeBedControl cbc2 = new ChangeBedControl();

            cbc2.processAssignBeds2(cb2, selectedBed, bedStatusF);

            dispose();

            File desktop = new File(System.getProperty("user.home"), "/Desktop"); 
            Document document = new Document(PageSize.A4.rotate());

            com.itextpdf.text.Font font1 = FontFactory.getFont("Verdana", 25, Font.BOLD);
            com.itextpdf.text.Font font2 = FontFactory.getFont("Verdana", 15, Font.BOLD);

            Paragraph p = new Paragraph(("Patient Admission Details"), font1);
            Paragraph p1 = new Paragraph(("Admission ID"), font2);
            Paragraph p2 = new Paragraph(("Patient ID"), font2);
            Paragraph p3 = new Paragraph(("Patient Name"), font2);
            Paragraph p4 = new Paragraph(("Date and Time Admitted"), font2);
            Paragraph p5 = new Paragraph(("Reason"), font2);
            Paragraph p6 = new Paragraph(("Date and Time Discharged"), font2);

            Paragraph pp = new Paragraph(("Bed Allocation Details"), font1);    
            Paragraph p01 = new Paragraph(("Bed ID"), font2);
            Paragraph p02 = new Paragraph(("Department"), font2);

            try {

                PageSize.A4.rotate();

                PdfWriter.getInstance(document, new FileOutputStream(desktop + "/" + textFieldPatientName.getText() + " Admission.pdf"));
                document.open();

                document.add(p);

                PdfPTable table = new PdfPTable(6);
                table.setWidthPercentage(102);

                PdfPCell cell1 = new PdfPCell();
                cell1.addElement(p1);

                PdfPCell cell2 = new PdfPCell();
                cell2.addElement(p2);

                PdfPCell cell3 = new PdfPCell();
                cell3.addElement(p3);

                PdfPCell cell4 = new PdfPCell();
                cell4.addElement(p4);

                PdfPCell cell5 = new PdfPCell();
                cell5.addElement(p5);

                PdfPCell cell6 = new PdfPCell();
                cell6.addElement(p6);

                AdmissionInfoControl aic1 = new AdmissionInfoControl();

                ArrayList<AdmissionInfo> admissionList = new ArrayList<AdmissionInfo>();

                admissionList = aic1.processGetAdmissionInfoView(admissionID);

                PdfPCell ell1;
                PdfPCell ell2;
                PdfPCell ell3;
                PdfPCell ell4;
                PdfPCell ell5;
                PdfPCell ell6;

                for (int i = 0; i < admissionList.size(); i++) {

                    ell1 = new PdfPCell(new Paragraph(admissionList.get(i).getAdmissionID()));
                    ell2 = new PdfPCell(new Paragraph(admissionList.get(i).getPatientID()));
                    ell3 = new PdfPCell(new Paragraph(admissionList.get(i).getPatientName()));
                    ell4 = new PdfPCell(new Paragraph(admissionList.get(i).getDateAdmitted()));
                    ell5 = new PdfPCell(new Paragraph(admissionList.get(i).getReason()));                       
                    ell6 = new PdfPCell(new Paragraph(admissionList.get(i).getDateDischarged()));

                    table.setSpacingBefore(30f);
                    table.addCell(cell1);
                    table.addCell(cell2);
                    table.addCell(cell3);
                    table.addCell(cell4);
                    table.addCell(cell5);
                    table.addCell(cell6);

                    table.addCell(ell1);
                    table.addCell(ell2);
                    table.addCell(ell3);
                    table.addCell(ell4);
                    table.addCell(ell5);
                    table.addCell(ell6);

                }               

                document.add(table);

                document.add(pp);

                PdfPTable table2 = new PdfPTable(2);

                table2.setHorizontalAlignment(Element.ALIGN_LEFT);

                table2.setWidthPercentage(50);

                PdfPCell cell01 = new PdfPCell();
                cell01.addElement(p01);

                PdfPCell cell02 = new PdfPCell();
                cell02.addElement(p02);

                ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();

                bedList = cbc.processGetBedsEdit(textFieldPatientID.getText());

                PdfPCell ell01;
                PdfPCell ell02;

                for (int i = 0; i < bedList.size(); i++) {

                    ell01 = new PdfPCell(new Paragraph(bedList.get(i).getBedID()));
                    ell02 = new PdfPCell(new Paragraph(bedList.get(i).getDepartment()));

                    table2.setSpacingBefore(30f);
                    table2.addCell(cell01);
                    table2.addCell(cell02);

                    table2.addCell(ell01);
                    table2.addCell(ell02);

                }

                document.add(table2);

                document.close();

                JOptionPane.showMessageDialog(null, "Admission PDF has been successfully created.");

            } catch (Exception ex) {

                JOptionPane.showMessageDialog(null, "Error: " + ex);

            }

        }
    });

    btnAssignBed.setBounds(288, 303, 116, 25);
    contentPane.add(btnAssignBed);

    comboBoxDpt = new JComboBox();
    comboBoxDpt.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            String departmentSelection = comboBoxDpt.getSelectedItem().toString();

            ChangeBedControl cbcS = new ChangeBedControl();

            ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();

            bedList = cbcS.processGetAvailBedsEdit(bedStatusF, departmentSelection);

            comboBoxAllocateBed.removeAllItems();

            for (int i = 0; i < bedList.size(); i++) {      
                comboBoxAllocateBed.addItem(bedList.get(i).getBedID());
            }

        }
    });
    //comboBoxDpt.setModel(new DefaultComboBoxModel(new String[] {"--Select Department--", "Cardiothoracic", "Oncology", "Orthopaedic", "Pediatric"}));
    comboBoxDpt = new JComboBox();

    ComboBoxRenderer renderer = new ComboBoxRenderer(comboBoxDpt);

    renderer.setColorsForMain(colorsForMain);
    renderer.setDepartments(departments);

    comboBoxDpt.setRenderer(renderer);

    comboBoxDpt.setBounds(138, 139, 153, 22);
    contentPane.add(comboBoxDpt);


    ChangeBedControl cbc = new ChangeBedControl();

    ArrayList<AdmissionInfo> admissionList = new ArrayList<AdmissionInfo>();

    admissionList = cbc.processGetChangeBedCreate(val1, val2);

    for (int i = 0; i < admissionList.size(); i++) {

        textFieldPatientID.setText(admissionList.get(i).getPatientID());

        textFieldPatientName.setText(admissionList.get(i).getPatientName());

    }

    //=============Distinct Feature=============
            ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();

            int selectedIndex = comboBoxDpt.getSelectedIndex() ;

            String departmentComboBox;

            ChangeBedControl cbc2 = new ChangeBedControl();

            bedList = cbc2.processCountBedsAvailableDpt1();

            for (int i = 0; i < bedList.size(); i++) {

                bedsAvailCardio = bedList.get(i).getRowCountAvail();

            }

            if (bedsAvailCardio <= 3) {



            }

            ChangeBedControl cbc4 = new ChangeBedControl();

            bedList = cbc4.processCountBedsAvailableDpt2();

            for (int i = 0; i < bedList.size(); i++) {

                bedsAvailOncology = bedList.get(i).getRowCountAvail();

            }

            if (bedsAvailOncology <= 3) {



            }

            ChangeBedControl cbc6 = new ChangeBedControl();

            bedList = cbc6.processCountBedsAvailableDpt3();

            for (int i = 0; i < bedList.size(); i++) {

                bedsAvailOrtho = bedList.get(i).getRowCountAvail();

            }

            if (bedsAvailOrtho <= 3) {



            }

            ChangeBedControl cbc8 = new ChangeBedControl();

            bedList = cbc8.processCountBedsAvailableDpt4();

            for (int i = 0; i < bedList.size(); i++) {

                bedsAvailPediatric = bedList.get(i).getRowCountAvail();

            }

            if (bedsAvailPediatric <= 3) {



            }


}

}

Codes for ComboBoxRenderer Class:

public class ComboBoxRenderer implements ListCellRenderer{

private Color comboBoxColour;

private Color[] colorsForMain;

private Color[] colorsForCardiothoracic;

private Color[] colorsForOncology;

private Color[] colorsForOrthopaedic;

private Color[] colorsForPediatric;

private String[] departments;

public ComboBoxRenderer() {};


public ComboBoxRenderer(JComboBox comboBoxDpt) {

}


public String[] getDepartments() {
    return departments;
}


public void setDepartments(String[] departments) {
    this.departments = departments;
}


public Color getComboBoxColour() {
    return comboBoxColour;
}

public void setComboBoxColour(Color comboBoxColour) {
    this.comboBoxColour = comboBoxColour;
}

public Color[] getColorsForMain() {
    return colorsForMain;
}

public void setColorsForMain(Color[] colorsForMain) {
    this.colorsForMain = colorsForMain;
}

public Color[] getColorsForCardiothoracic() {
    return colorsForCardiothoracic;
}

public void setColorsForCardiothoracic(Color[] colorsForCardiothoracic) {
    this.colorsForCardiothoracic = colorsForCardiothoracic;
}

public Color[] getColorsForOncology() {
    return colorsForOncology;
}

public void setColorsForOncology(Color[] colorsForOncology) {
    this.colorsForOncology = colorsForOncology;
}

public Color[] getColorsForOrthopaedic() {
    return colorsForOrthopaedic;
}

public void setColorsForOrthopaedic(Color[] colorsForOrthopaedic) {
    this.colorsForOrthopaedic = colorsForOrthopaedic;
}

public Color[] getColorsForPediatric() {
    return colorsForPediatric;
}

public void setColorsForPediatric(Color[] colorsForPediatric) {
    this.colorsForPediatric = colorsForPediatric;
}


@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    return list;

}

}

Community
  • 1
  • 1
domster
  • 556
  • 2
  • 8
  • 26
  • Take a look at your second link. You are not adding any code to set string values inside the combobox. Look at the ComboBoxRenderer class in the second link. – A.Sharma Aug 02 '16 at 17:47

1 Answers1

0

If you look at the second link you provided you can see the following line of code:

static Color[] colors = {Color.BLUE, Color.GRAY, Color.RED};

Each index of the colors array matches the index of the String objects in the JComboBox.

In your case, because you want the first index to be red, you would make the first index of the color array to be red:

static Color[] colors = {Color.BLUE, Color.RED, Color.BLUE}; //Index # 1 is red.
A.Sharma
  • 2,771
  • 1
  • 11
  • 24
  • I implemented the codes already but i got a Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException. And my frame is blank. I'm actually implementing the colours in a frame that i've already made and created. – domster Aug 02 '16 at 16:31
  • I'll add it to my post.. Please help me A.Sharma.. ! Thank you! – domster Aug 02 '16 at 16:47
  • Sorry A.Sharma im new to stackoverflow.. My post was just edited right? – domster Aug 02 '16 at 17:34
  • I would also approach it differently. You should modularize your code as much as possible to make it easier to maintain. You can create a class that extends the JComboBox and pass the colors and string as arguments in the constructor. Then create a JComboBox for each patient. Currently at work so I can't really create the entire implementation right now. – A.Sharma Aug 02 '16 at 18:30
  • It's all good Sharma, what if i were to just stick to this? My project is due soon for submission in school... – domster Aug 02 '16 at 18:34
  • At my school, I would get a 0 if the code doesn't compile. If your code isn't going to compile, then the instructor has nothing to grade. I'm getting my Master's though so that may be diff. Just **look at the second link, and see and UNDERSTAND it.** It should make sense to you in about a half and hour and it will start to click. – A.Sharma Aug 02 '16 at 18:37
  • I just noticed that there was an additional declaration of the comboBox. I've now removed it and reposition the codes with the renderer but there's an error saying 'adding container's parent to itself'... – domster Aug 02 '16 at 19:01
  • Sharma i'll make a move first.. it's 3am here. Once i wake up i'll look at this post again. Would appreciate if you could kindly help me.. PM or any other ways. I'm new to this site. Don't really know how the chat system works, etc. Thank you Sharma! – domster Aug 02 '16 at 19:10