从按钮打开菜单

时间:2015-12-22 22:27:14

标签: java jbutton

hello eveybody我创建了这段代码:

response is y
Would you like another card? (Y or N) n
response is y
Would you like another card? (Y or N)
屏幕截图: enter image description here

enter image description here

我很想在页面内打开一个新的页面,每个按钮都会打开,在里面我会写出食物的菜单来选择和接近它的价格写的?请帮助我,我根本不能这样做,可以知道如何......

由于

2 个答案:

答案 0 :(得分:0)

您可以使用JPanel在其他Container中绘制内容。 (JPanel和JFrame是容器)

但是你说你只想写文字。所以你可以使用JTextArea。 Javadoc会帮助你。

答案 1 :(得分:0)

正如Emz的评论中所指出的,CardLayout是这种情况下最好的拳头。为每个菜单创建JPanel,并将其添加到JPanel CardLayout。然后使用按钮在面板之间切换。

以下是一个例子:

public class Example extends JPanel {

    Example() {

        JPanel starters = new JPanel(new FlowLayout());
        starters.add(new JLabel("starters..."));
        JPanel drinks = new JPanel(new FlowLayout());
        drinks.add(new JLabel("drinks..."));

        JPanel main = new JPanel(new CardLayout());
        main.add(starters, "starters");
        main.add(drinks, "drinks");

        JPanel buttons = new JPanel();
        JButton startersButton = new JButton("Starters");
        startersButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CardLayout cl = (CardLayout)(main.getLayout());
                cl.show(main, "starters");
            }
        });

        JButton drinksButton = new JButton("Starters");
        drinksButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CardLayout cl = (CardLayout)(main.getLayout());
                cl.show(main, "drinks");
            }
        });

        buttons.add(startersButton);
        buttons.add(drinksButton);

        setLayout(new BorderLayout());
        add(main);
        add(buttons, BorderLayout.PAGE_START);
    }
}

添加到框架并运行。