文本字段不显示

时间:2014-09-02 01:55:33

标签: java swing textarea calculator

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame
{
    //Setting out the variables
    JTextField answerResponse;
    JButton one,two,three,four,five,six,seven,eight,nine,zero,add,subtract,multiply,divide,equals;
    String var1, var2, tanswer;
    Double answer;
    JPanel contentpanel;
    public GUI()
    {
        //JFrame Window
        JFrame frame = new JFrame();
        frame.setSize(250, 400);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setVisible(true);
        frame.setTitle("Calculator");
        frame.setLocationRelativeTo(null);

        //Buttons
        one = new JButton("1"); two = new JButton("2"); three = new JButton("3");
        four = new JButton("4"); five = new JButton("5"); six = new JButton("6");
        seven = new JButton("7"); eight = new JButton("8"); nine = new JButton("9");
        zero = new JButton("0"); add = new JButton("+"); divide = new JButton("/");
        multiply = new JButton("*"); subtract = new JButton("-"); equals = new JButton("=");

        //Dimensions
        Dimension dim = new Dimension(75, 25);
        one.setPreferredSize(dim); two.setPreferredSize(dim); three.setPreferredSize(dim);
        four.setPreferredSize(dim); five.setPreferredSize(dim); six.setPreferredSize(dim);
        seven.setPreferredSize(dim); eight.setPreferredSize(dim); nine.setPreferredSize(dim);
        zero.setPreferredSize(new Dimension(225, 25)); add.setPreferredSize(new Dimension(113, 25)); subtract.setPreferredSize(new Dimension(113, 25)); 
        multiply.setPreferredSize(new Dimension(113, 25)); divide.setPreferredSize(new Dimension(113, 25)); equals.setPreferredSize(new Dimension(225, 25));

        //Content Panel
        JPanel contentPanel = new JPanel();
        frame.setContentPane(contentPanel);
        contentPanel.setLayout(new FlowLayout());

        //Adding to content panel
        contentPanel.add(one); contentPanel.add(two); contentPanel.add(three);
        contentPanel.add(four); contentPanel.add(five); contentPanel.add(six);
        contentPanel.add(seven); contentPanel.add(eight); contentPanel.add(nine);
        contentPanel.add(zero); contentPanel.add(add); contentPanel.add(subtract);
        contentPanel.add(multiply); contentPanel.add(divide); contentPanel.add(equals);

        //Declaring Variable Values
        answerResponse = new JTextField(null, 20);
        answerResponse.setEditable(false);
        contentPanel.add(answerResponse);
    }
}

我在尝试制作计算器时遇到问题。名为“answerResponse”的文本字段未显示。其余的按钮等,文本字段应该是顶部的第一个东西。

1 个答案:

答案 0 :(得分:2)

frame.setVisible(true);并将其放在contentPanel.add(answerResponse);下面作为最后一个。

虽然没有证据表明其他情况,但请确保您在事件调度线程的上下文中执行您的UI代码,有关详细信息,请参阅Initial Threads

另请查看Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

您还应该习惯不使用setSize窗口并使用pack代替,因为这会考虑平台和窗口边框之间出现的各种外观和差异