Java ActionListener附加一个组合框
我尝试使用gui,以便根据用户从第一个列表中选择的内容,可以看到第二个列表 为了做到这一点,我需要在第一个组合框中添加一个动作侦听器。然后在action listener类中执行switch语句。然而,当我实现这个时,我会出错 是否允许在占位符空组合框上附加完整组合框Java ActionListener附加一个组合框,java,swing,user-interface,combobox,append,Java,Swing,User Interface,Combobox,Append,我尝试使用gui,以便根据用户从第一个列表中选择的内容,可以看到第二个列表 为了做到这一点,我需要在第一个组合框中添加一个动作侦听器。然后在action listener类中执行switch语句。然而,当我实现这个时,我会出错 是否允许在占位符空组合框上附加完整组合框 package balanceThatSheep; /* * This Class is the GUI for the program. */ import javax.swing.*; import java.awt
package balanceThatSheep;
/*
* This Class is the GUI for the program.
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BalancingInterface extends JFrame{
private JLabel sexL, classL, weightL, forageL, concentratesL;
private JButton calculateB, exitB;
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
private SheepTypeListHandler stlHandler;
private static final int WIDTH = 600;
private static final int HEIGHT = 500;
public BalancingInterface(Data getSomeData){
// Create four labels
sexL = new JLabel("Select Sheep Type: ", SwingConstants.CENTER);
classL = new JLabel("Select Sheep Classification: ", SwingConstants.CENTER);
weightL = new JLabel("Select Sheep Weight: ", SwingConstants.CENTER);
forageL = new JLabel("Select a Forage: ", SwingConstants.CENTER);
concentratesL = new JLabel("Select Feed Concentrates: ", SwingConstants.CENTER);
//Create the Arrays
String [] sheepType = {"Ewe", "Ram", "Lamb"}; //Three Choices - can only pick one
String [] eweClass = {"Maintenance", "Nonlactating, first 15 weeks gestation",
"Last 6 wks gestation OR Last 8 wks lactation suckling singles",
"First 8 wks lactation suckling singles OR last 8 wks lactation suckling twins",
"First 8 weeks lactation suckling twins", "Replacement lambs and yearlings"};
String [] ramClass = {"Replacement lambs and yearlings"}; //This is the only option for Rams
String [] lambClass = {"Finishing", "Early-weaned"}; //Only 2 choices
String [] forageNames = getSomeData.getForageNames(); //Pull in the forage names
String [] placeholder = {""}; //Use this list as a placeholder
//Create Drop Down Lists
JComboBox<String> sheepListCB = new JComboBox<>(sheepType); //Can Only Pick one element - good
JComboBox<String> sheepEweClassCB = new JComboBox<>(eweClass); //If ewe selected
JComboBox<String> sheepRamClassCB = new JComboBox<>(ramClass); //If ram selected
JComboBox<String> sheepLambClassCB = new JComboBox<>(lambClass); //If lamb selected
JComboBox<String> foragesCB = new JComboBox<>(forageNames); //Can Only Pick one element - good
JComboBox<String> placeholderCB = new JComboBox<>(placeholder); //Use as a placeholder
JComboBox<String> placeholder2CB = new JComboBox<>(placeholder); //Use as a placeholder
JComboBox<String> placeholder3CB = new JComboBox<>(placeholder); //Use as a placeholder
//Create Calculate Button
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//Calculate button you are making the program listen to it.
//Create Exit Button
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
//Handle the Selection of the Sheep Type
stlHandler = new SheepTypeListHandler();
sheepListCB.addActionListener(stlHandler);
//Set the title of the window box
setTitle("Welcome to the Sheep Ration Balancer");
//Get the container
Container pane = getContentPane();
//Set the layout
pane.setLayout(new GridLayout(6, 2)); //6 rows, 2 columns
//Place all items created
pane.add(sexL);
pane.add(sheepListCB);
pane.add(classL);
pane.add(placeholderCB);
pane.add(weightL);
pane.add(placeholder2CB);
pane.add(forageL);
pane.add(foragesCB);
pane.add(concentratesL);
pane.add(placeholder3CB);
pane.add(calculateB);
pane.add(exitB);
//set the size of the window and display it
setSize(WIDTH,HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//repaint - usually used for graphics - might work here
repaint();
} //End Constructor
/*
* This method will execute after the constructor
*/
public void paint(Graphics g)
{
super.paint(g);
} //End paint Method
private class SheepTypeListHandler implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if (e == "ewe")
placeholderCB.append(sheepEweClassCB);
if (e == "ram")
placeholder2CB.append(sheepRamClassCB);
else
placeholder3CB.append(sheepLambClassCB);
//TODO - Finish this Method
} //End actionPerformed Method
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//TODO - Finish this Method
} //End actionPerformed Method
} //End CalculateButtonHandler Class
private class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
} //End actionPerformed Method
} //End ExitButton Method Class
} //End of BalancingInterface Class
包装平衡;
/*
*此类是程序的GUI。
*/
导入javax.swing.*;
导入java.awt.*;
导入java.awt.event.*;
公共类平衡接口扩展JFrame{
私人JLabel sexL、classL、weight、forageL、concentratesL;
私有JButton计算器b、exitB;
私有CalculateButtonHandler cbHandler;
私有ExitButtonHandler ebHandler;
私有SheepTypeListHandler stlHandler;
专用静态最终整数宽度=600;
专用静态最终内部高度=500;
公共平衡接口(数据getSomeData){
//创建四个标签
sexL=新的JLabel(“选择绵羊类型:”,SwingConstants.CENTER);
classL=新的JLabel(“选择绵羊分类:”,SwingConstants.CENTER);
weightL=新的JLabel(“选择绵羊体重:”,SwingConstants.CENTER);
forageL=新的JLabel(“选择饲料:”,SwingConstants.CENTER);
浓缩物SL=新的JLabel(“选择饲料浓缩物:”,SwingConstants.CENTER);
//创建数组
String[]sheepType={“Ewe”、“Ram”、“Lamb”};//三个选项-只能选择一个
字符串[]eWebClass={“维持”,“非哺乳期,妊娠前15周”,
“最后6周妊娠或最后8周哺乳期哺乳单胎”,
“前8周哺乳期单胎或后8周哺乳期双胎”,
“前8周哺乳期哺乳双胞胎”、“替换羔羊和一岁羔羊”};
String[]ramClass={“替换羔羊和一岁羔羊”};//这是Rams的唯一选项
字符串[]lambClass={“正在完成”,“早期断奶”};//只有2个选项
String[]forageNames=getSomeData.getForageNames();//拉入搜索名称
String[]占位符={”“};//将此列表用作占位符
//创建下拉列表
JComboBox sheepListCB=新的JComboBox(sheepType);//只能选择一个元素-好
JComboBox sheepeweclassb=新JComboBox(eweClass);//如果选择了ewe
JComboBox sheepRamClassCB=新的JComboBox(ramClass);//如果选择了ram
JComboBox sheepLambClassCB=新的JComboBox(lambClass);//如果选择了lamb
JComboBox-foragesCB=新的JComboBox(forageNames);//只能选择一个元素-好
JComboBox占位符CB=新的JComboBox(占位符);//用作占位符
JComboBox占位符2CB=新的JComboBox(占位符);//用作占位符
JComboBox占位符3CB=新的JComboBox(占位符);//用作占位符
//创建计算按钮
calculateB=新按钮(“计算”);
cbHandler=新的CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
//“计算”按钮,使程序收听它。
//创建退出按钮
exitB=新的JButton(“退出”);
ebHandler=新的ExitButtonHandler();
addActionListener(ebHandler);
//处理绵羊类型的选择
stlHandler=新的SheepTypeListHandler();
sheepListCB.addActionListener(stlHandler);
//设置窗口框的标题
setTitle(“欢迎来到绵羊配给平衡器”);
//拿容器
容器窗格=getContentPane();
//设置布局
setLayout(新的GridLayout(6,2));//6行,2列
//放置所有创建的项目
窗格。添加(sexL);
窗格。添加(sheepListCB);
窗格。添加(classL);
添加(占位符CB);
窗格。添加(重量);
窗格。添加(占位符2CB);
窗格。添加(多孔凝胶);
窗格。添加(foragesCB);
窗格。添加(浓缩液);
窗格。添加(占位符3CB);
窗格。添加(b);
添加(exitB);
//设置窗口的大小并显示它
设置尺寸(宽度、高度);
setVisible(真);
setDefaultCloseOperation(关闭时退出);
//重绘-通常用于图形-可能在这里工作
重新油漆();
}//结束构造函数
/*
*此方法将在构造函数之后执行
*/
公共空间涂料(图g)
{
超级油漆(g);
}//结束绘制方法
私有类SheepTypeListHandler实现ActionListener{
已执行的公共无效操作(操作事件e)
{
如果(e==“ewe”)
占位符cb.append(sheepeweclassb);
如果(e==“ram”)
占位符2cb.append(sheepRamClassCB);
其他的
占位符3cb.append(sheepLambClassCB);
//TODO-完成此方法
}//结束actionPerformed方法
}
私有类CalculateButtonHandler实现ActionListener
{
已执行的公共无效操作(操作事件e)
{
//TODO-完成此方法
}//结束actionPerformed方法
}//结束CalculateButtonHandler类
私有类ExitButtonHandler实现ActionListener
{
已执行的公共无效操作(操作事件e)
{
系统出口(0);
}//结束actionPerformed方法
}//结束ExitButton方法类
}//BalancingInterface类结束
完整代码如上所示。我正在使用的组合框是“sheepListCB”。上面的操作侦听器显示了我实现下一个组合框的逻辑。但是,它不起作用 也许你想要这样的东西 从第一个组合框中选择一个值,然后填充第二个组合框:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ComboBoxTwo extends JPanel implements ActionListener
{
private JComboBox<String> mainComboBox;
private JComboBox<String> subComboBox;
private Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();
public ComboBoxTwo()
{
String[] items = { "Select Item", "Color", "Shape", "Fruit" };
mainComboBox = new JComboBox<String>( items );
mainComboBox.addActionListener( this );
// prevent action events from being fired when the up/down arrow keys are used
mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
add( mainComboBox );
// Create sub combo box with multiple models
subComboBox = new JComboBox<String>();
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
add( subComboBox );
String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
subItems.put(items[1], subItems1);
String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
subItems.put(items[2], subItems2);
String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
subItems.put(items[3], subItems3);
}
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new ComboBoxTwo() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
import java.awt.*;
导入java.awt.event.*;
导入java.util.*;
导入javax.swing.*;
公共类ComboBoxTwo扩展JPanel实现ActionListener
{
专用JComboBox主组合框;
专用JComboBox子omboBox;
私有哈希表子项=新哈希表();
公营机构
{
字符串[]项={“选择项”、“颜色”、“形状”、“水果”};
mainComboBox=新的JComboBox(项目);
mainComboBox.addActionListener(这个);
//防交流