import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class PizzaOrder1 extends JPanel implements ActionListener {
// Used to cancel an order and clear the form.
private JButton cancelButton;
// Displays what the user ordered.
private JButton orderButton;
// Field to enter the name of the person ordering the pizza.
private JTextField nameField;
// The toppings the user would like.
private JComboBox<String> toppings = new JComboBox<String>();
private JCheckBox deliveryBox = new JCheckBox();
public void PizzaOrder1() {
// Delivery
JPanel deliveryPanel = new JPanel();
deliveryPanel.add(deliveryBox);
deliveryPanel.add(new JLabel("Delivery"));
add(deliveryPanel);
// Person ordering
JPanel namePanel = new JPanel();
namePanel.add(new JLabel("Name: "));
nameField = new JTextField(15);
namePanel.add(nameField);
add(namePanel);
// Toppings
toppings.addItem("Pepperoni");
toppings.addItem("Mushrooms");
toppings.addItem("Anchovies");
add(toppings);
// Order and cancel buttons
JPanel buttonPanel = new JPanel();
orderButton = new JButton("Place order");
orderButton.addActionListener(this);
buttonPanel.add(orderButton);
cancelButton = new JButton("Cancel order");
cancelButton.addActionListener(this);
buttonPanel.add(cancelButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent buttonEvent) {
if (buttonEvent.getSource() == orderButton) {
Order();
}
clear();
}
private void Order() {
String order = nameField.getText() + " ordered a pizza with " + toppings.getSelectedItem() + ". ";
if (deliveryBox.isSelected()) {
order = order + "This pizza will be delivered. ";
} else {
order = order + "This pizza will be picked up. ";
}
order = order + "This pizza should be ";
// Show the order in a popup window.
JOptionPane.showMessageDialog(this, order);
}
private void clear() {
nameField.setText("");
deliveryBox.setSelected(false);
toppings.setSelectedIndex(0);
}
public static void main(String[] args) {
JFrame f=new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Pizza Order");
f.setSize(new Dimension(400, 400));
// Create the panel that will display the image and text
PizzaOrder1 componentsPanel = new PizzaOrder1();
// Add the image panel to the center of the window
Container contentPane = f.getContentPane();
contentPane.add(componentsPanel, BorderLayout.CENTER);
// Display the window.
f.setVisible(true);
}
}
我正在运行Windows命令提示符,它编译并运行正常,但运行时它只显示正确大小的灰色窗口。我不确定我哪里出错了。
答案 0 :(得分:5)
这个问题是由于方法和构造函数之间的区别混淆造成的。
public void PizzaOrder1() { // this is a METHOD!
鉴于:
public PizzaOrder1() { // this is a CONSTRUCTOR!