已有259人关注
Java从入门到精通(第四版) 249页 例13.14 接口后面的代码有什么作用?
发表在Java答疑区 2017-06-09
是否精华
版块置顶:

import java.awt.*;


import javax.swing.*;


public class JComboBoxTest extends JFrame {

JComboBox<String> jc = new JComboBox<>(new MyComboBox());

JLabel jl = new JLabel("请选择证件");


public JComboBoxTest() {

setTitle("在窗体中使用列表组件");

setSize(500, 400);

setVisible(true);

setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

Container c = getContentPane();

c.setLayout(new FlowLayout());

c.add(jl);

c.add(jc);

}


public static void main(String[] args) {

new JComboBoxTest();

}


class MyComboBox extends AbstractListModel<String> implements ComboBoxModel<String> {

String selectedItem = null;

String[] test = { "身份证", "学生证", "军官证", "工人正" };


public String getElementAt(int index) {

return test[index];

}


public int getSize() {

return test.length;

}


public void setSelectedItem(Object item) {

selectedItem = (String) item;

}


public Object getSelectedItem() {

return selectedItem;

}


public int getIndex() {

for (int i = 0; i < test.length; i++) {

if (test[i].equals(getSelectedItem()))

return i;

}

return 0;

}

}

}

疑问:String selectedItem = null;这段代码有什么作用?

     为什么要获取test字符数组中的索引值和长度?

      最后一点for循环是做什么用的?

分享到:
精彩评论 3
David
学分:914 LV7
TA的每日心情
最后的冲刺
2017-07-15 10:46:08
2017-06-10
沙发

(1)定义局部变量时,要为局部变量赋值,null为String类型的默认值。

(2)在实现接口ComboBoxModel的同时,需要实现接口中的抽象方法,获取数组的索引值和长度等,均为必须实现的抽象方法。

(3)获得被选中菜单项的索引值。

chenbaojunjava
学分:58 LV3
2017-06-10
板凳

David 发表于2017-06-10 15:24

(1)定义局部变量时,要为局部变量赋值,null为String类型的默认值。

(2)在实现接口ComboBoxModel的同时,需要实现接口中的抽象方法,获取数组的索引值和长度等,均为必须实现的抽象方法。

(3)获得被选中菜单项的索引值。

最后的for循环有是什么作用?注释掉之后运行,也没见到什么影响啊?

使用下面代码(改写)是不是更简单:

package test;


import java.awt.*;


import javax.swing.*;


public class GaiXie13_14 extends JFrame{

private  JComboBox<String>combobox;

public GaiXie13_14(){

setTitle("本窗体改写下拉列表框");

setSize(500, 300);

setVisible(true);

setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

Container c=getContentPane();

c.setLayout(new FlowLayout());

JLabel jl=new JLabel("请选择证件");

c.add(jl);

combobox=new JComboBox<>();

c.add(combobox);    

combobox.addItem("身份证");

combobox.addItem("军人证");

combobox.addItem("学生证");

combobox.addItem("工作证");

combobox.setSelectedItem(null);

}

public static void main(String[] args) {

new GaiXie13_14();

}

}


David
学分:914 LV7
TA的每日心情
最后的冲刺
2017-07-15 10:46:08
2017-06-12
地板

(1)for循环的作用是,让数组中的每一个元素和被选中的菜单项作比较,最后返回与被选中的菜单项相同元素的索引。

(2)读者的代码也是正确的,而且比源码要简便。

首页上一页 1 下一页尾页 3 条记录 1/1页
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照