gpt4 book ai didi

java - ComboBox 不监听事件

转载 作者:行者123 更新时间:2023-11-30 05:46:03 26 4
gpt4 key购买 nike

此应用程序显示一个包含不同 JComboBox 和 JLabel 的框架。当用户单击最后一个(样式组合框)时应生成一个事件,并且 JLabel 中的文本应根据每个组合框中所选的选项进行格式化。

当我单击“样式”组合框时,没有任何反应。
还有一个我无法弄清楚的错误:(

输出

enter image description here

package labtasksix;

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class MyFrame extends JFrame {

String NameO []= {"Select name:","TimesRoman","Serif","SansSerif","Monospaced"};
String ColorO[]={"Select color:","RED","BLUE","GREEN"};
String SizeO []={"Select size:","8","12","16","20"};
String StyleO[]={"Select style:","BOLD","ITALIC","PLAIN"};

JLabel lbl= new JLabel("Text Formatted");
JComboBox Name= new JComboBox(NameO);
JComboBox Colour= new JComboBox(ColorO);
JComboBox Size= new JComboBox(SizeO);
JComboBox Style= new JComboBox(StyleO);

public MyFrame() {
super("Format Frame");
setLayout(new FlowLayout());
add(Name);
add(Size);
add(Style);
add(Colour);
add(lbl);
Name.setMaximumRowCount(3);
Size.setMaximumRowCount(3);
Style.setMaximumRowCount(3);
Colour.setMaximumRowCount(3);
EventHandler handler= new EventHandler();
Style.addItemListener(handler);
}

class EventHandler implements ItemListener{

@Override
public void itemStateChanged(ItemEvent e) {

//When user chooses from the last combobox (style)
if(e.getSource()==Style)
{
if(Name.getSelectedItem().equals("BOLD"))
{
lbl.setFont(new Font((String)Name.getSelectedItem(),Font.BOLD, (int) Size.getSelectedItem()));
}

if(Name.getSelectedItem().equals("ITALIC"))
{
lbl.setFont(new Font((String)Name.getSelectedItem(),Font.ITALIC, (int) Size.getSelectedItem()));

}
if(Name.getSelectedItem().equals("PLAIN"))
{
lbl.setFont(new Font((String)Name.getSelectedItem(),Font.PLAIN, (int) Size.getSelectedItem()));

}
if(Colour.getSelectedItem().equals("RED"))
{

lbl.setForeground(Color.red);
}
if(Colour.getSelectedItem().equals("BLUE"))
{

lbl.setForeground(Color.BLUE);
}
if(Colour.getSelectedItem().equals("GREEN"))
{

lbl.setForeground(Color.GREEN);
}

}
}
}
}

最佳答案

它正在监听,但您正在检查 ComboBox.getSelectedItem(),该事件在事件触发时尚未更新。事件相关的项目在事件本身中被引用;调用 e.getItem() 来检索它:

Object item = e.getItem();
if (item.equals("BOLD")) {
lbl.setFont(new Font((String) item, Font.BOLD, /* wrong: (int) Size.getSelectedItem() */ 8));
}

您的尺寸计算(上面评论)也是错误的。您的尺寸选择框包含字符串,因此您必须解析它们(或将模型更改为整数)。

此外...每次更改您都会收到两个事件,首先是 ItemEvent.DESELECTED(对于旧项目),然后是 ItemEvent.SELECTED。您应该检查您感兴趣的 Activity :

if (e.getSource() == Style && e.getStateChange() == ItemEvent.SELECTED) { 

关于java - ComboBox 不监听事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54817407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com