从GUI外部的类添加元素到JList

时间:2015-04-01 23:50:56

标签: java swing object

我创建了一个应用程序,它将事件附加到JButtons类以及我在GUI类中多次实例化的其他swing组件。

MenuItemEventHandler附加到每个菜单项。

我发现很难找到解决方法。它可能盯着我的脸。我最初的解决方案是将按钮事件处理程序放在GUI类中,并更改GUI类的字段以显示其他列表项。或者甚至将JListMenuItemEventHandler类传递到GUI,但我似乎找不到合适的解决方案。我已经在网上搜索了人们讨论MVC的问题。我不确定我是否需要这种程度的深度。

下面是一个创建菜单项按钮部分的类,它附加了ButtonEventHandler

public class MenuItem 
{
    private JButton addFood;
    private String foodName;

    // food name was passed in by another class.    
    public void createButtons()  
    {
        JButton newButton = new JButton();

        newButton.setBounds(260, 157, 40,30);

        MenuItemEventHandler action = new MenuItemEventHandler(this.foodName);

        newButton.setAction(action);
        this.addFood = newButton;
    }

    public JButton getAddFoodButton() 
    {
        return this.addFood;
    }   
}

处理GUI中实例化的每个按钮的事件。

public class MenuItemEventHandler extends AbstractAction 
{
    private String menuItemName;
    private DefaultListModel<String> orderedFood;

    public MenuItemEventHandler(String foodName) 
    {
        this.menuItemName = foodName;
    }

    private static final long serialVersionUID = 1L;

    @Override
    public void actionPerformed(ActionEvent arg0) 
    {
        /* button clicked add this objects food name to the list
         * on the gui.
         * 
         */ 
    }
}

public class GUI2Test 
{
    private JPanel mainPanel;
    private JFrame frame;
    private JList<String> orderList;
    public DefaultListModel<String> orderedFood;

    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable() 
        {
            public void run() 
            {
                new GUI2Test();
            }
        });
    }

    public GUI2Test()  
    {
        createForm();
        createList();

        /*
        *  would normaly loop to create multiple panels 
        */
        MenuItem button1 = new MenuItem();

        button1.createButtons();    
        frame.add(button1.getAddFoodButton());
        frame.add(orderList);
        mainPanel.setLayout(null);
        frame.add(mainPanel);
        frame.setVisible(true);
    }

    public void createList() 
    {
        orderedFood = new DefaultListModel<String>();
        orderList = new JList<String>(orderedFood);
        orderList.setBounds(20, 140, 200, 400);
        orderList.setBackground(Color.yellow);
        orderList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        orderList.setLayoutOrientation(JList.VERTICAL);
        orderedFood.addElement("test");
    }

    public void createForm() 
    {
        frame = new JFrame("Resturant");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1000, 700);
        frame.setVisible(true);
        mainPanel = new JPanel();
        mainPanel.setLayout(null);
    }
}

0 个答案:

没有答案