【问题标题】:Assigning values to JButtons from object arrayList从对象 arrayList 为 JButtons 赋值
【发布时间】:2016-10-13 09:43:25
【问题描述】:

我正在开发 EPOS 系统,作为程序的一部分,我正在生成存储在 ArrayList 中的所有项目的 GridLayout。在 items 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 类是创建对象本身的地方。

【问题讨论】:

    标签: java swing arraylist jbutton


    【解决方案1】:

    您可以让该类实现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 的动作侦听器中,您可以进行特定于案例的动作。

    【讨论】:

    • 非常感谢,这非常很有帮助,但是我仍然不确定如何确保每个按钮都能够访问类的值?我试图将每个按钮映射到迭代的当前对象,但我不确定从那里去哪里?
    • @TooLateTheHero - 我不确定我是否完全理解
    猜你喜欢
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 2013-03-20
    相关资源
    最近更新 更多