【问题标题】:Setting foreground colour specific index of JComboBox设置 JComboBox 的前景色特定索引
【发布时间】:2016-12-08 00:05:43
【问题描述】:

更改 JComboBox 中指定项目索引的前景色。

例如,

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

有什么方法可以在不使用 CellRenderer 的情况下做到这一点?从来没有用过CellRenderer,完全没有经验..

已经看过这些网站: Changing a color chooser button's background color in Java, Multiple Colors for Each Item in JComboBox, Colored jcombobox with colored items and focus

第三个似乎是最有用的,但不知道如何实现..

谢谢。

框架代码:

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



            }


}

}

ComboBoxRenderer 类的代码:

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;

}

}

【问题讨论】:

  • 看看你的第二个链接。您没有添加任何代码来设置组合框中的字符串值。查看第二个链接中的 ComboBoxRenderer 类。

标签: java jcombobox foreground


【解决方案1】:

如果您查看您提供的第二个链接,您可以看到以下代码行:

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

colors 数组的每个索引都与 JComboBox 中的 String 对象的索引匹配。

在您的情况下,因为您希望第一个索引为红色,您可以将颜色数组的第一个索引设为红色:

static Color[] colors = {Color.BLUE, Color.RED, Color.BLUE}; //Index # 1 is red.

【讨论】:

  • 我已经实现了代码,但是我在线程“AWT-EventQueue-0”java.lang.NullPointerException 中遇到了异常。我的框架是空白的。我实际上是在我已经制作和创建的框架中实现颜色。
  • 我会把它添加到我的帖子中.. 请帮助我 A.Sharma.. !谢谢!
  • 抱歉 A.Sharma 我是 stackoverflow 的新手。我的帖子刚刚编辑对了吗?
  • 我也会以不同的方式处理它。您应该尽可能地模块化您的代码,以使其更易于维护。您可以创建一个扩展 JComboBox 的类,并将颜色和字符串作为参数传递给构造函数。然后为每个患者创建一个 JComboBox。目前正在工作,所以我现在无法真正创建整个实现。
  • 这一切都很好夏尔马,如果我坚持这个怎么办?我的项目即将在学校提交......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2012-12-29
  • 2014-03-20
相关资源
最近更新 更多