当每个面板处于Gridlayout中时,如何将两个面板添加到单个JFrame中?

时间:2018-10-22 18:27:05

标签: java user-interface jframe flowlayout

我已经做了很多挖掘工作,但似乎无法弄清我在做什么错。我正在创建一个框架,并尝试向其中添加两个网格面板。每个面板均设置为1行3列的网格布局。

但这是我运行它时出现的内容: Screenshot

我知道我缺少一些简单的东西,但是我很难弄清楚它到底是什么。很抱歉这个问题,但我现在很茫然。任何帮助将不胜感激!

public class MadewellSalesTaxWindow  extends JFrame
{
private JFrame frame; // the frame
private JPanel panel1; //top panel
private JPanel panel2; //bottom panel
private JLabel messageLabel; // label right of field
private JTextField TaxTextField; // label for text field
private JButton calcCountyButton; // these are the button names
private JButton calcStateButton;
private JButton calcTotalButton;
private final int WINDOW_WIDTH = 500;  // window width
private final int WINDOW_HEIGHT = 150; // window height
private final double STATE_TAX = 0.065;
private final double COUNTY_TAX = 0.03;
String pattern = "###,###,###,###.##";
DecimalFormat decimalFormat = new DecimalFormat(pattern); // output formatting

public MadewellSalesTaxWindow()
{
    // window title
    setTitle("Sales Tax Calculator");

    // window size
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

    // clarify what occurs upon window closing
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // call frame constructor
    frame = new JFrame();

    // calls the function that builds the panels
    buildPanel();

    // adds the panels to the frame
    add(panel1);
    add(panel2);

    // displays the window (very important)
   setVisible(true);
}

private void buildPanel()
{
    // this label gives the user instructions
    messageLabel = new JLabel("Enter total sales for the month: $");

    // 10 characters should be enough for monthly sales unless the company is massive
    TaxTextField = new JTextField(10);

    // creates the buttons
    calcCountyButton = new JButton("Calculate County Tax");
    calcStateButton = new JButton("Calculate State Tax");
    calcTotalButton = new JButton("Calculate Total Sales Tax");


    // adds action listeners to each of the buttons
    calcCountyButton.addActionListener(new CountyButtonListener());
    calcStateButton.addActionListener(new StateButtonListener());
    calcTotalButton.addActionListener(new TotalButtonListener());

    // create 2 new panels
    panel1 = new JPanel();
    panel2 = new JPanel();

    // add the appropriate elements to the top panel and the bottom panel
    panel1.add(messageLabel);
    panel1.add(TaxTextField);
    panel2.add(calcCountyButton);
    panel2.add(calcStateButton);
    panel2.add(calcTotalButton);

    // set the layouts for the panels so that they display correctly
    panel1.setLayout(new GridLayout(1,3)); 
    panel2.setLayout(new GridLayout(1,3)); 
}

1 个答案:

答案 0 :(得分:0)

请参见Two Panels in one JFrame?

最后,您的框架需要布局以容纳两个面板。

添加

setLayout(new GridLayout(2,1));

构造函数。