Swing Exploration: Write a JCHECKListBox component

xiaoxiao2021-03-06  97

I remember that there is a TcheckListBox control in Delphi, which is a list of tick. Now let's make one, just call JCheckListbox.

Before writing code, consider the following questions:

· Inherited: Of course, inheriting from Swing Jlist.

· Data expansion: For Jlist, it shows a series of Object. Regardless of its type, use a default renderer (DEFAULTLASTCELLRENDERER, inheriting from Jlabel), each entry is set with Object.toString (). However, for JCheckListBox, in addition to displaying text, consider whether each entry is selected, if selected, to display "tick". Therefore, JLIST needs to maintain the status information of "Each entry is selected". We put in a Boolean array.

· Renderer: The default rendere is definitely can't, can't display the tick. Nature wants to use JCheckbox to re-do a renderer, set to jchecklistbox.

· Mouse listener: You can now draw each entry, but not enough, you must respond to click on the mouse to check / uncheck. So add a mouse monitor to respond to the mouse event on JChecklistbox. Of course, if you want it to enter the keyboard input (for example, Ctrl A) can also be made such as the method.

ChecklistBoxModel: For easy operation, here is also an CHECKLISTMODEL from AbstractListModel, which can send events when the entry CHECK changes.

Ok, because the code and principles are simple, no more, give the code directly, as well as simple comments:

Import java.awt. *;

Import java.awt.event. *;

Import javax.swing. *;

Import javax.swing.event. *;

Public class jchecklistbox extends jlist {

// This Boolean array loads all Items to be information by CHECK.

Private boolean [] checkedItems = null;

/ **

* Define a simple ListModel that can send Check changing events.

* /

Class ChecklistBoxModel Extends AbstractListModel {

Private Object [] items = null;

ChecklistBoxModel (Object [] items) {

THIS.ITEMS = Items;

}

Public int getSize () {

Return Items.length;

}

Public Object getElementat (INT i) {

Return Items [i];

}

Protected Void Firecheckchanged (Object Source, INT INDEX) {

FireContentSchanged (Source, INDEX, INDEX);

}

Public Object GetItem (int index) {

Return items [index];

}

}

/ **

* A constructor is covered here. Other jlist you can overwrite yourself, anyway, SUPER is OK again.

* @Param Items Object []

* /

Public JCheckListBox (Object [] Items) {setModel (New ChecklistboxModel (items);

INIT ();

}

/ **

* Initialization control. Including initialization Boolean arrays, install a renderer, install a mouse overlay.

* /

protected void init () {

CheckedItems = new bolean [this.getmodel (). getsize ()];

Class mycellrenderer extends jcheckbox imports listcellrenderer {

Public mycellrenderer () {

Setopaque (TRUE);

}

Public Component getListCellrendereComponent

Jlist List,

Object Value,

Int index,

Boolean isselected,

Boolean CellHasfocus) {

// This code is basically plagiarized from DefaultListCellrenderer.java.

Setcomponentorientation (list.getComponentorientation);

IF (isselected) {

SetBackground (list.getSelectionbackGround ());

SetForeground (list.getSelectionForeGroup);

} else {

SetBackground (List.getBackground ());

SetForeground (List.getForeGround ());

}

Value InstanceOf icon {

Seticon (ICON) value);

SetText ("" ");

} else {

Seticon (NULL);

SetText ((value == null)? ": value.tostring ());

}

Setenabled (List.isenabled ());

SetFont (list.getfont ());

// Although plagiarism, you can don't forget to set Check information.

This.SetSelected (ISCHECKED);

Return this;

}

}

This.SetCellrenderer (New mycellrenderer ());

/ / Define a mouse overlay. If you click on an Item, turn its CHECK status.

Class checkboxlistener extends mouseadapter {

Public void mouseclicked (mouseevent e) {

INT INDEX = LocationToIndex (E.GETPOINT ());

InvertChecked (INDEX);

}

}

This.Addmouser (New CheckBoxListener ());

}

/ **

* Turn the CHECK status of the specified Item.

* @Param Index INT

* /

Public void invertChecked (int index) {

CheckedItems [index] =! checkedItems [index];

// Don't forget to send Event.

ChecklistBoxModel model = (checklistboxmodel) getModel ();

Model.fireCheckChanged (this, index);

THIS.REPAINT ();

}

/ **

* Whether Item is specified by Check.

* @Param Index INT

* @Return Boolean * /

Public boolean ischecked (int index) {

Return checkedItems [index];

}

/ **

* Get the number of selected items

* /

Public int getCheckedcount () {

Int results = 0;

For (int i = 0; i

IF (CheckedItems [I]) {

RESULT ;

}

}

Return Result;

}

/ **

* All arrays of the Item index.

* /

Public int [] getCheckedindices () {

int [] result = new int [getCheckedcount ()];

INT INDEX = 0;

For (int i = 0; i

IF (CheckedItems [I]) {

Result [index] = i;

INDEX ;

}

}

Return Result;

}

Public static void main (String [] args) {

JFrame Frame = New Jframe ("JCheckListBox - xiaozhonghua@hotmail.com");

Final JchecklistBox List = New JChecklistBox (New Object [] {"Zhang San", "Li Si", "Wang Di Menzi", "Wood Six"});

Frame.getContentPane (). Add (new jscrollpane (list), borderlayout.center;

JButton Button = New JButton ("OK");

Button.addActionListener (New ActionListener () {

Public Void ActionPerformed (ActionEvent E) {

System.exit (0);

}

});

Frame.getContentPane (). add (button, borderlayout.south);

Final Jlabel Label = New Jlabel ("There is no choice.");

List.getModel (). AddlistDatalistener (New ListDataListener () {

Public void intervalded (ListDataEvent E) {}

Public Void IntervalRemoved (listdataevent e) {}

Public Void Contentschanged (ListDataEvent E) {

IF (list.getCheckedcount () == 0) {

Label.setText ("There is no choice.");

} else {

String text = "Current selection:";

int [] indices = list.getCheckedindices ();

For (int i = 0; i

Text = (ChecklistBoxmodel) List.getModel ()). GetItem (INDES [I]). TOSTRING () ",";

}

Label.Settext (Text);

}

});

Frame.getContentPane (). add (label, borderlayout.north);

Frame.setBounds (300, 300, 400, 200);

Frame.show ();

}

}

转载请注明原文地址:https://www.9cbs.com/read-104010.html

New Post(0)