之前我问了一个类似的问题,但是我遇到了不同代码的问题。当我运行该程序时,会弹出窗口,但labels
,textboxes
和button
未显示。将非常感谢帮助!我正在使用Eclipse IDE
。
import javax.swing.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class MonthlySalesTax extends JFrame {
private JPanel panel; // A panel to hold everything
private JTextField totalSales; // To get total sales
private JButton calcButton; // Calculates everything
// Constants for tax rates
private final double COUNTY_RATE = 0.02;
private final double STATE_RATE = 0.04;
// Constants for window size
private final int WINDOW_WIDTH = 360;
private final int WINDOW_HEIGHT = 100;
/**
* Constructor
*/
public MonthlySalesTax() {
// Set the title.
setTitle("Monthly Sales Tax Reporter");
// Specify what happens when the close button is clicked.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Build the panel that contains the other components.
buildPanel();
// Size and display the window
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
}
/**
* The buildPanel method creates a panel containing other components.
*/
private void buildPanel() {
// Create a label prompting for the total sales.
JLabel totalSalesMsg = new JLabel("Enter the total sales:");
//Create a text field for total sales.
totalSales = new JTextField(10);
// Create a button to click.
calcButton = new JButton("Calculate Sales Tax");
// Add an action listener to the button.
calcButton.addActionListener(new CalcButtonListener());
// Create a panel.
panel = new JPanel();
// Add the label, text field, and button to the panel.
panel.add(totalSalesMsg);
panel.add(totalSales);
panel.add(calcButton);
}
/**
* CalcButtonListener is an action listener class for the calcbutton component.
*/
private class CalcButtonListener implements ActionListener {
/**
* actionPerformed method
* @param e An ActionEvent object.
*/
public void actionPerformed(ActionEvent e) {
double totalSalesAmount, // To hold the total sales amount
countyTaxAmount, // To hold the county tax
stateTaxAmount, // To hold the state tax
totalTaxAmount; // To hold the total tax
// Create a DecimalFormat object to format output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Get the total sales.
totalSalesAmount = Double.parseDouble(totalSales.getText());
// Calculate the county tax.
countyTaxAmount = totalSalesAmount * COUNTY_RATE;
// Calculate the state tax.
stateTaxAmount = totalSalesAmount * STATE_RATE;
// Calculate the total sales.
totalTaxAmount = countyTaxAmount + stateTaxAmount;
// Display the result.
JOptionPane.showMessageDialog(null, "County Sales Tax: $" +
dollar.format(countyTaxAmount) +
"\nState Sales Tax: $" +
dollar.format(stateTaxAmount) +
"\nTotal Sales Tax: $" +
dollar.format(totalTaxAmount));
}
}
/**
* The main method creates an instance of the SalesTax class,
* causing it to display its window.
*/
public static void main(String[] args) {
MonthlySalesTax stx = new MonthlySalesTax();
}
}
答案 0 :(得分:0)
啊,我忘了按照你们的建议将面板添加到JFrame中。
很简单:
add(panel);
谢谢大家!