[英]Listbox in Java
I was trying to build the Font window of Notepad using Java using the code shown below. 我试图使用Java,使用下面显示的代码来构建记事本的“字体”窗口。 But, I'm facing a problem in setting the size of the text as specified inside listbox. 但是,我在设置列表框内指定的文本大小时遇到问题。
I'm trying to get the respective size corresponding to the index of the selected item but couldn't find any such method. 我正在尝试获取与所选项目的索引对应的相应大小,但找不到任何此类方法。
f = new Frame("Font");
f.setLayout(new GridLayout(3, 3));
b1 = new Button("OK");
l1 = new Label("Font :");
l2 = new Label("Size :");
l3 = new Label("Font Style :");
lb1 = new List(10, false);
lb2 = new List(10, false);
lb3 = new List(5, false);
String [] s = {"Times New Roman", "Arial", "Verdana", "Trebuchet MS", "Papyrus","Monotype Corsiva","Microsoft Sans Serif", "Courier", "Courier New"};
for(int i = 0; i < s.length; i++)
{
lb1.add(s[i]);
}
for(int i = 8; i <=72; i += 2)
{
lb2.add(i + "");
}
String [] s1 = {"BOLD", "ITALIC", "PLAIN"};
for(int i = 0; i < s1.length; i++)
{
lb3.add(s1[i]);
}
f.add(l1);
f.add(l2);
f.add(l3);
f.add(lb1);
f.add(lb2);
f.add(lb3);
f.add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(lb3.isIndexSelected(0))
fo = new Font(lb1.getSelectedItem(), Font.BOLD, **lb2.getSelectedIndex**());
else if(lb3.isIndexSelected(1))
fo = new Font(lb1.getSelectedItem(), Font.ITALIC, lb2.getSelectedIndex());
else
fo = new Font(lb1.getSelectedItem(), Font.PLAIN, lb2.getSelectedIndex());
ta1.setFont(fo);
MyFrame15.f.dispose();
}
});
f.setSize(300, 300);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int)((d.getWidth() / 2) - 200);
int y = (int)((d.getHeight() / 2) - 200);
f.setLocation(x, y);
f.setVisible(true);
}
To get the size as required by user we can use: lb2.getSelectedItem(); 要获得用户所需的大小,我们可以使用:lb2.getSelectedItem(); which returns a String but the third argument of Font constructor requires an integer.Therefore, we use parseInt() method of Integer class to convert the string received to integer.The code is as follows: Font(lb1.getSelectedItem(), Font.BOLD, Integer.parseInt(lb2.getSelectedItem() )); 它返回一个String,但是Font构造函数的第三个参数需要一个整数。因此,我们使用Integer类的parseInt()方法将接收到的字符串转换为整数,代码如下:Font(lb1.getSelectedItem(),Font。 粗体 , Integer.parseInt(lb2.getSelectedItem() ));
I would suggest you use Swing for this. 我建议您为此使用Swing。 You can start with the Swing tutorial on Text Component Features which already contains a working example that does what you want. 您可以从有关文本组件功能的Swing教程开始,该教程已经包含一个可以执行所需操作的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.