[英]Assigning values to JButtons from object arrayList
我正在EPOS系统上工作,并且作为程序的一部分,我正在生成存储在ArrayList中的所有项目的GridLayout。 在ArrayList项中,所有对象及其必需的成员变量(例如名称,条形码和价格)都存储在其中。 我目前已经做到了,以便填充网格,但是按钮没有动作,而且我不确定如何处理类中的数据,也许有某种方法可以分配当前项目对象的值,即被迭代到正在制作的按钮上? 因为每个按钮都是由我的代码制作的,而不是“手工制作的”。 相关代码如下:
public class gridCreator extends JFrame {
ObjectCreator obj = new ObjectCreator();
GridLayout itemGrid = new GridLayout();
JFrame frame = new JFrame("pls work");
static gridCreator instance;
public static void main(String[] args) throws FileNotFoundException {
instance = new gridCreator();
instance.createGrids();
instance.createAndShowGUI();
}
public void createGrids() throws FileNotFoundException{
obj.loadItems();
itemGrid.setColumns(20);
itemGrid.setRows(4);
for (ObjectCreator.Item item : obj.items){
addComponentsToPane(item);
}
}
private void addComponentsToPane(ObjectCreator.Item item) {
JButton button = new JButton(item.getName());
frame.add(button);
}
附带说明一下,ObjectCreator类是对象本身的生成位置。
您可以使该类实现ActionListener
,并分配该actionListener的所有按钮:
public class gridCreator extends JFrame implements ActionListener{
ObjectCreator obj = new ObjectCreator();
GridLayout itemGrid = new GridLayout();
JFrame frame = new JFrame("pls work");
static gridCreator instance;
public static void main(String[] args) throws FileNotFoundException {
instance = new gridCreator();
instance.createGrids();
instance.createAndShowGUI();
}
public void createGrids() throws FileNotFoundException{
obj.loadItems();
itemGrid.setColumns(20);
itemGrid.setRows(4);
for (ObjectCreator.Item item : obj.items){
addComponentsToPane(item);
}
}
private void addComponentsToPane(ObjectCreator.Item item) {
JButton button = new JButton(item.getName());
frame.add(button);
}
@Override
public void actionPerformed(ActionEvent e) {
//do actions here
}
然后,在JFrame的动作侦听器中,您可以进行特定于案例的动作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.