Java Swing GUI用户交互

时间:2019-01-09 13:04:08

标签: java swing user-interface

我目前正在使用Java在Eclipse上开发披萨订购程序。

我现在似乎被困住了;我不确定在用户执行完之后如何公开更多的用户交互。

我想添加另一个按钮,以便在选择顶部时将其移至另一组按钮上。

我对Swing GUI不太熟悉,因此我对如何尝试在程序中添加更多按钮感到困惑。

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDateTime;
import javax.swing.*;
//Import used to add interfaces in order to use more commands and to be able to use GUI.

public class PizzaMain implements ActionListener{
    final static String LABEL_TEXT = "Please choose the size of your pizza:";
    JFrame frame;
    JPanel contentPane;
    JLabel label;
    JButton button, button2, button3, button4, button5, button6;
//Button 4,5,6 will be used for more toppings.
//JFrame, JPanel, JLabel, & JButton is used for adding the variables of all the buttons, panels, labels, and frame so they're able to be added into the JPanel in GUI.  

    public PizzaMain() {
        frame = new JFrame("EAST SIDE PIZZA");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new JPanel();
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
        contentPane.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));

        label = new JLabel (LABEL_TEXT);
        label.setAlignmentX(JLabel.TOP_ALIGNMENT);
        contentPane.add(label);
        label.setFont(new Font("Garamond", Font.ITALIC, 15));

        button = new JButton("Small");
        button.setAlignmentX(JButton.LEFT_ALIGNMENT);
        button.setAlignmentY(JButton.CENTER_ALIGNMENT);
        button.setActionCommand("Small");
        button.addActionListener(this);
        contentPane.add(button);
        button.setFont(new Font("Papyrus", Font.ITALIC, 13));
        button.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
                button.setVisible(true);
                button.setText("Pepperoni");
                button2.setText("Cheese");
                button3.setVisible(true);
                button3.setText("Pineapple");
                button4 = new JButton("Mushrooms");
                button4.setActionCommand("Mushrooms");
                button4.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button4);
                button5 = new JButton("Peppers");
                button5.setActionCommand("Peppers");
                button5.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button5);
                button6 = new JButton("Bacon");
                button6.setActionCommand("Bacon");
                button6.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button6);
                label.setVisible(true);
                label.setText("Please choose what topping you want on your pizza:");        
            }
        }); //Used for activating the buttons once they're pressed.

        button2 = new JButton("Medium");
        button2.setAlignmentY(JButton.CENTER_ALIGNMENT);
        button2.setActionCommand("Medium");
        button2.addActionListener(this);
        contentPane.add(button2);
        button2.setFont(new Font("Papyrus", Font.ITALIC, 13));
        button2.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
                button.setVisible(true);
                button.setText("Pepperoni");
                button2.setVisible(true);
                button2.setText("Cheese");
                button3.setVisible(true);
                button3.setText("Pineapple");
//Set text is to keep the buttons but change the text within them & button 4,5, and 6 are for new buttons to be created
                button4 = new JButton("Mushrooms");
                button4.setActionCommand("Mushrooms");
//setFont is for changing the font of the buttons in the actionPerformed sub-method.
                button4.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button4);
                button5 = new JButton("Peppers");
                button5.setActionCommand("Peppers");
                button5.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button5);
                button6 = new JButton("Bacon");
                button6.setActionCommand("Bacon");
                button6.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button6);
                label.setVisible(true);
                label.setText("Please choose what topping you want on your pizza:");    

//Text below is for creating new buttons within the actionPerformed sub-method so that I'm able to add crust options.
                if (button.getText().equals("Thin Crust"));{
                    button.setText("Thin Crust");
                }
                }
            });

        button3 = new JButton("Large");
        button3.setAlignmentY(JButton.RIGHT_ALIGNMENT);
//Right Alignment is used for changing the button's location on the panel so they're able to be lined up.
        button3.setActionCommand("Large");
        button3.addActionListener(this);
        contentPane.add(button3);
        button3.setFont(new Font("Papyrus", Font.ITALIC, 13));
        button3.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
                button.setVisible(true);
                button.setText("Pepperoni");
                button2.setVisible(true);
                button2.setText("Cheese");
                button3.setVisible(true);
                button3.setText("Pineapple");
                button4 = new JButton("Mushrooms");
                button4.setActionCommand("Mushrooms");
                button4.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button4);
                button5 = new JButton("Peppers");
                button5.setActionCommand("Peppers");
                button5.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button5);
                button6 = new JButton("Bacon");
                button6.setActionCommand("Bacon");
                button6.setFont(new Font("Papyrus", Font.ITALIC, 13));
                contentPane.add(button6);
                label.setVisible(true);
                label.setText("Please choose what topping you want on your pizza:");                

                button.isEnabled();
            }
        });
        frame.add(contentPane);

        frame.pack();
        frame.setVisible(true);
    }


//Used to run the GUI once the program ha sstarted running.
    private static void runGUI() {
        JFrame.setDefaultLookAndFeelDecorated(true);
//Adds borders to the GUI window.
        PizzaMain size = new PizzaMain();
    }
    public static void main(String[] args) {
//InvokeLate is used for updating the GUI; such as changing the buttons or changing a label after a button is pressed.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                runGUI();
            }
        });
    }

//Used to override since I was getting errors without it.
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
}

我希望输出结果是,一旦按下浇头按钮,它将进入第三组按钮,为披萨提供更多选择,而不是根本不做任何事情。

预先感谢

2 个答案:

答案 0 :(得分:0)

也许与只对每个选择使用按钮相比,带有单个提交按钮的JCheckBoxes和JRadioButtons可能更适合您的需求。如果仍然需要侦听器,则所有JComponent都具有ActionListener或更适合该组件的侦听器,JCheckBoxes和JRadioButton也具有ItemListener和ChangeListener。

如果您希望使用JButtons,建议将分组在一起的按钮移动到JPanel上,并将其可见性设置为true或false。另外,如果有两个浇头可供选择,我会将按钮的+和-用于或多或少的浇头,并有一个整数字段来存储用户指定的浇头数量。

我想出了办法,控制GUI元素的最佳方法是通过JPanels。是否需要JLabel一定的大小或位置?将其包装在JPanel中,并将其模制成应有的样子。

答案 1 :(得分:0)

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PizzaMain implements ActionListener {
 final static String LABEL_TEXT = "Please choose the size of your pizza:";
StringBuilder selectedOutput = new StringBuilder();
JFrame frame;
JPanel contentPane;
JLabel label;
JButton button, button2, button3, button4, button5, button6;
 /*Button 4,5,6 will be used for more toppings.
 JFrame, JPanel, JLabel, & JButton is used for adding the variables of all 
 the buttons, panels, labels, and frame so they're able to be added into the 
 JPanel in GUI.*/ 

public PizzaMain() {
    frame = new JFrame("EAST SIDE PIZZA");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    contentPane = new JPanel();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
    contentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    label = new JLabel(LABEL_TEXT);
    label.setAlignmentX(JLabel.TOP_ALIGNMENT);
    contentPane.add(label);
    label.setFont(new Font("Garamond", Font.ITALIC, 15));

    //Add other pizza buttons here  Size buttons ..Small Pizza,Large Pizza ,Medium Pizza,Family Size
    //Once these buttons are created add then to the contentPane
    //Since your user initial point of entry
    button = new JButton("Small");
    button.setAlignmentX(JButton.LEFT_ALIGNMENT);
    button.setAlignmentY(JButton.CENTER_ALIGNMENT);
    button.setActionCommand("Small");
    button.addActionListener(this);
    contentPane.add(button);
    button.setFont(new Font("Papyrus", Font.ITALIC, 13));

    JButton largePizza = new JButton("Large");
    largePizza.setAlignmentX(JButton.LEFT_ALIGNMENT);
    largePizza.setAlignmentY(JButton.CENTER_ALIGNMENT);
    largePizza.setActionCommand("Large");
    largePizza.addActionListener(this);
    contentPane.add(largePizza);

    //This panel is displayed on the second stage after the user has selected his/her Pizza size
    //Add other pizza type button  Pepperoni,Cheese,Ham,blah blah
    //add these buttons to jpanel
    //set each button actionListener  copy paste
    JPanel jPanel = new JPanel();
    jPanel.setBackground(Color.GREEN);
    jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.PAGE_AXIS));
    jPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    button4 = new JButton("Pepperoni");
    button4.setAlignmentX(JButton.LEFT_ALIGNMENT);
    button4.setAlignmentY(JButton.CENTER_ALIGNMENT);
    button4.setFont(new Font("Papyrus", Font.ITALIC, 13));
    button4.addActionListener(this);
    jPanel.add(button4);

    button5 = new JButton("Cheese");
    button5.setAlignmentX(JButton.LEFT_ALIGNMENT);
    button5.setAlignmentY(JButton.CENTER_ALIGNMENT);
    button5.setFont(new Font("Papyrus", Font.ITALIC, 13));
    button5.addActionListener(this);
    jPanel.add(button5);


    //This page is the last selection stage you can have many pages in form of JPanel as above
    //add other options here ,veggetables,topping
    //add them to jPanel2
    JPanel jPanel2 = new JPanel();
    jPanel2.setBackground(Color.RED);
    jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.PAGE_AXIS));
    jPanel2.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    button6 = new JButton("Vegetables");
    button6.setAlignmentX(JButton.LEFT_ALIGNMENT);
    button6.setAlignmentY(JButton.CENTER_ALIGNMENT);
    button6.setActionCommand("Small in Japen2");
    button6.setFont(new Font("Papyrus", Font.ITALIC, 13));
    button6.addActionListener(this);

    JButton button7 = new JButton("meat");
    button7.setAlignmentX(JButton.LEFT_ALIGNMENT);
    button7.setAlignmentY(JButton.CENTER_ALIGNMENT);
    button7.setActionCommand("Small in Japen2");
    button7.setFont(new Font("Papyrus", Font.ITALIC, 13));
    button7.addActionListener(this);
    jPanel2.add(button7);

    JButton backButtonToPanel1 = new JButton("<<<");
    backButtonToPanel1.setAlignmentX(JButton.LEFT_ALIGNMENT);
    backButtonToPanel1.setAlignmentY(JButton.CENTER_ALIGNMENT);
    backButtonToPanel1.setFont(new Font("Papyrus", Font.ITALIC, 13));
    backButtonToPanel1.addActionListener(this);
    jPanel2.add(backButtonToPanel1);

    JTextField output = new JTextField();
    jPanel2.add(output);

    /*button to select another option following option {pepperoni,cheese} these options are found in jPanel2
    When user chooses small pizza  contentPane will removeAll its childrens,repaint its self and validate its action
    It will repaint itself again and then add second panel
    User selected option is then stored in a StringBuilder log will show the activity
    Once done it will take the user to the next Panel for more options
    This step is used to define buttons actions*/
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            selectedOutput.append("selected -> small");
            contentPane.setLayout(new CardLayout());
            contentPane.removeAll();
            contentPane.repaint();
            contentPane.revalidate();
            contentPane.repaint();
            contentPane.add(jPanel);
            contentPane.revalidate();
            System.out.println("small clicked will take you to jpanel 1");
        }
    });

    largePizza.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            selectedOutput.append("selected -> Large Pizza");
            contentPane.setLayout(new CardLayout());
            contentPane.removeAll();
            contentPane.repaint();
            contentPane.revalidate();
            contentPane.repaint();
            contentPane.add(jPanel);
            contentPane.revalidate();
            System.out.println("large clicked will take you to jpanel 1");
        }
    });

    // button to select the following optins  {pepperoni,meat} options in JPanel 2
    button4.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            selectedOutput.append("   and,pepperoni");
            output.setText(selectedOutput.toString());
            contentPane.setLayout(new CardLayout());
            contentPane.removeAll();
            contentPane.repaint();
            contentPane.revalidate();
            contentPane.repaint();
            contentPane.add(jPanel2);
            contentPane.revalidate();
            System.out.println("large clicked will take you to jpanel 2");
        }
    });

    // button to select the following optins  {pepperoni,meat} options in JPanel 2
    button5.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            selectedOutput.append("   and,cheese");
            output.setText(selectedOutput.toString());
            contentPane.setLayout(new CardLayout());
            contentPane.removeAll();
            contentPane.repaint();
            contentPane.revalidate();
            contentPane.repaint();
            contentPane.add(jPanel2);
            contentPane.revalidate();
            System.out.println("This will remain here showing user final option");
        }
    });

    button7.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            output.setText("");
            selectedOutput.append("  topped with meat");
            output.setText(selectedOutput.toString());
            contentPane.setLayout(new CardLayout());
            contentPane.removeAll();
            contentPane.repaint();
            contentPane.revalidate();
            contentPane.repaint();
            contentPane.add(jPanel2);
            contentPane.revalidate();
            System.out.println("This will remain here showing user final option");

        }
    });

    backButtonToPanel1.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            contentPane.removeAll();
            contentPane.repaint();
            contentPane.revalidate();
            contentPane.repaint();
            contentPane.add(jPanel);
            contentPane.revalidate();
            System.out.println("We are going back");

        }
    });
    frame.add(contentPane);
    frame.pack();
    frame.setVisible(true);
}

private static void runGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    PizzaMain size = new PizzaMain();
}

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

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

}
}

以上解决方案使用JPanels和动态页面布局。 工作原理 显示第一页( JPanel1 ),用户可以选择披萨大小 {small,medium,Large} 选择比萨大小后,将显示另一页(JPanel2)

在JPanel2中,用户可以有其他选择披萨类型的选项,也可以选择返回到JPanel1的选项。

控制台将帮助您进行所有正在发生的活动。

* NB 我在最后一个JPanel中添加了一个JTextField来显示所有选定的用户选项。