文本未出现在 GUI 计算器的 TextField 上?

Text not appearing on TextField for GUI Calculator?

我一直在制作 GUI 计算器,但我 运行 陷入困境。我知道我的代码仅限于“2”按钮,但那是因为我删除了所有数字,因此代码可以更短地放在此处。当我按下两个时,我知道 Actionlistener 已激活,因为 System.out.println 将打印出 2。但是它不会出现在我的文本字段中,我哪里出错了?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.awt.FlowLayout;

public class CalculatorY {
    public static  JPanel panel = new JPanel(new GridLayout(5, 5));
    public static JButton one, two, three, four, five, six, seven, eight, nine, zero, equal;
    public static JTextField result;
    public static boolean add, sub, mult, div;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Rohini and Sonika's Calculator");
        result = new JTextField(null,90);
        two = new JButton("2");
        equal = new JButton("=");
        two.addActionListener(new button());
        panel.setLayout(new GridLayout(5, 5, 5, 25));
        panel.setLayout(new FlowLayout());
        panel.add(result, BorderLayout.NORTH);
        panel.add(two);
        frame.setVisible(true);
        frame.setSize(200, 400);
        frame.setResizable(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
    }

    public static class button implements ActionListener {
        public void actionPerformed(ActionEvent event) {

            String command = event.getActionCommand();
            String text = result.getText();
            int textLength = text.length();
            String letterValueOne = null;
            String letterValueTwo = null;
            boolean operation = false; 
                    if (operation == false) {
                        if (letterValueOne == null) {
                            letterValueOne = "2";   
                            System.out.println(letterValueOne);
                            result.setText(letterValueOne);
                        } else {
                            letterValueOne = letterValueOne + "2";
                            result.setText(letterValueOne);
                        }
                    } else {
                        if (letterValueTwo == null) {
                            letterValueTwo = "2";
                        } else {
                            letterValueTwo = letterValueTwo + "2";
                        }
                    }
        }
    }
}

它确实在文本字段中输入了 2!您可以通过单击文本字段,按 Ctrl-A,然后按 Ctrl-C,然后粘贴到其他地方来查看。

new JTextField(null, 90) 创建一个足以容纳 90 个字符的文本字段,但这比框架宽(至少在我的系统上是这样),因此它在两侧被切断。如果最大化框架,您应该看到 2.

一些可能的解决方案是:

  • 将框架变大。请注意,您无法预测“90 列”在其他计算机上可能有多宽,因此您无法知道多大才足够大。

  • 缩小文本字段。这有同样的问题。

  • 最后打frame.pack();。这使得框架足够大以容纳其中的所有组件。 FlowLayout 将它们排成一行;您可能想返回使用 BorderLayout.

它实际上出现在您的 textField 上,您根本看不到它,如果它很小 window。变化

result = new JTextField(null,90);

result = new JTextField(null,10);

那么您应该会看到“2”。 另一个 problem:I 不知道这个错误是否存在,因为你删除了不必要的代码,但 Eclipse 告诉我,例如

if (letterValueTwo == null) {
    letterValueTwo = "2";
                    } else {
                        HERE//letterValueTwo = letterValueTwo + "2";
                    }

"//Here" 无法访问,因为您首先分配了 letterValueTwo == null,这就是为什么您的 else 分支将永远不会被执行的原因。

你的问题是 layout/size/placement。我自己,我会做一些不同的事情,包括:

  • 嵌套 JPanel,每个 JPanel 使用自己的布局,这样简单的布局管理器就可以生成复杂的 GUI。
  • 主 JPanel 可以使用 BorderLayout,您可以将显示 JTextField 放置在其 BorderLayout.PAGE_START(或 NORTH)位置。这将限制 JTextField 填充主 JPanel 的顶部,但不允许它像 FlowLayout 那样超出此 JPanel。
  • JButton 可以放在使用 GridLayout 的单独 JPanel 中
  • 这个包含 JPanel 的按钮可以放在主 JPanel 的 BorderLayout.CENTER 位置。

例如,

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

public class CalcEg {
   private static final float BTN_FONT_SIZE = 20f; 
   private static final String[][] BTN_LABELS = {
      {"sqr", "sqrt", "exp", "log"}, 
      {"7", "8", "9", "-"},
      {"4", "5", "6", "+"},      
      {"1", "2", "3", "/"},
      {"0", ".", " ", "="}
   };
   private static final int GAP = 4;
   private static final String NUMBERS = "0123456789.";
   private JPanel mainPanel = new JPanel(new BorderLayout(GAP, GAP));
   private JPanel buttonPanel = new JPanel();
   private JTextField display = new JTextField();

   public CalcEg() {
      int rows = BTN_LABELS.length;
      int cols = BTN_LABELS[0].length;
      buttonPanel.setLayout(new GridLayout(rows, cols, GAP, GAP));
      for (String[] btnLabelRow : BTN_LABELS) {
         for (String btnLabel : btnLabelRow) {
            if (btnLabel.trim().isEmpty()) {
               buttonPanel.add(new JLabel());
            } else {
               JButton btn = createButton(btnLabel);
               if (NUMBERS.contains(btnLabel)) {
                  Action action = new NumberButtonAction(btnLabel);
                  btn.setAction(action);
               }
               buttonPanel.add(btn);
            }
         }
      }
      display.setFont(display.getFont().deriveFont(BTN_FONT_SIZE));
      display.setEditable(false);
      display.setFocusable(false);
      display.setBackground(Color.white);

      mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
      mainPanel.add(buttonPanel, BorderLayout.CENTER);
      mainPanel.add(display, BorderLayout.PAGE_START);
   }

   private JButton createButton(String btnLabel) {
      JButton button = new JButton(btnLabel);
      button.setFont(button.getFont().deriveFont(BTN_FONT_SIZE));
      return button;
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private class NumberButtonAction extends AbstractAction {
      public NumberButtonAction(String name) {
         super(name);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         String displayText = display.getText();
         displayText += getValue(NAME);

         try {
            double d = Double.parseDouble(displayText);
            display.setText(displayText);
         } catch (NumberFormatException e1) {}
      }
   }

   private static void createAndShowGui() {
      CalcEg mainPanel = new CalcEg();

      JFrame frame = new JFrame("CalcEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

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

这将创建此 GUI: