如何将值从一个JLabel传输到另一个JLabel

如何将值从一个JLabel传输到另一个JLabel

本文介绍了如何将值从一个JLabel传输到另一个JLabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个计算器,但是当你点击完成按钮时,我无法弄清楚如何将 resultpane 中的值输入第一个文本框。

I have this calculator working, but I can't figure out how to get the value in the resultpane to the first textbox when you click the "finish" button.

我是Java的新手。我试过这样做,但我一直都是错误的。

I'm new to Java. I've tried doing it, but I kept getting an error.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.AbstractAction;
import static javax.swing.Action.NAME;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestCalculator {

public static void main(String[] args) {
    new TestCalculator();
}

public TestCalculator() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            }

            ResultPane resultPane = new ResultPane();

            JFrame frame = new JFrame("Testing");
            frame.setGlassPane(resultPane);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new BorderLayout());
            frame.add(new CalculatorPane(resultPane));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

public class ResultPane extends JPanel {

    private JLabel result;
    private Timer timer;

    private int xDelta = (Math.random() > 0.5) ? 1 : -1;
    private int yDelta = (Math.random() > 0.5) ? 1 : -1;

    ;

    public ResultPane() {
        setOpaque(false);
        setLayout(null);
        result = new JLabel();
        Font font = result.getFont();
        font = font.deriveFont(Font.BOLD, 26f);
        result.setFont(font);
        add(result);
        timer = new Timer(40, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Point point = result.getLocation();
                point.x += xDelta;
                point.y += yDelta;
                if (point.x < 0) {
                    point.x = 0;
                    xDelta *= -1;
                } else if (point.x + result.getWidth() > getWidth()) {
                    point.x = getWidth() - result.getWidth();
                    xDelta *= -1;
                }
                if (point.y < 0) {
                    point.y = 0;
                    yDelta *= -1;
                } else if (point.y + result.getHeight() > getHeight()) {
                    point.y = getHeight() - result.getHeight();
                    yDelta *= -1;
                }
                result.setLocation(point);
                repaint();
            }

        });
        timer.start();
    }

    public void setResult(Number number) {
        result.setText("Result: " + NumberFormat.getNumberInstance().format(number));
        result.setSize(result.getPreferredSize());
        setVisible(true);
    }

}

public class CalculatorPane extends JPanel {

    private final ResultPane resultPane;

    private final JLabel firstNumberLabel = new JLabel("First Number:");
    private final JLabel secondNumberLabel = new JLabel("Second Number:");

    private final JTextField firstNumberField = new JTextField(5);
    private final JTextField secondNumberField = new JTextField(5);

    public CalculatorPane(ResultPane resultPane) {

        setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;

        this.resultPane = resultPane;

        JPanel fields = new JPanel();
        fields.add(firstNumberLabel);
        fields.add(firstNumberField);
        fields.add(secondNumberLabel);
        fields.add(secondNumberField);

        add(fields, gbc);

        JPanel buttons = new JPanel();
        buttons.add(new JButton(new AddAction()));
        buttons.add(new JButton(new SubtractAction()));
        buttons.add(new JButton(new MultiplyAction()));
        buttons.add(new JButton(new DivideAction()));
        buttons.add(new JButton(new ToText1Action()));

        add(buttons, gbc);

    }

    public class AddAction extends AbstractAction {

        public AddAction() {
            putValue(NAME, "+");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 + num2;

                //num1.setResult(firstNumberField);
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class SubtractAction extends AbstractAction {

        public SubtractAction() {
            putValue(NAME, "-");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 - num2;
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class MultiplyAction extends AbstractAction {

        public MultiplyAction() {
            putValue(NAME, "x");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 * num2;
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class DivideAction extends AbstractAction {

        public DivideAction() {
            putValue(NAME, "/");
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                double num1 = Double.parseDouble(firstNumberField.getText());
                double num2 = Double.parseDouble(secondNumberField.getText());

                double result = num1 / num2;
                resultPane.setResult(result);
            } catch (NumberFormatException exp) {
            }
        }

    }
    public class ToText1Action extends AbstractAction {
        public ToText1Action() {
            putValue(NAME, "Finish");
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            try {

                //i would like to put it here


            } catch (NumberFormatException exp) {
            }
        }
    }
}
}


推荐答案

为ResultPane提供一个新的公共方法,允许您从其JLabel中提取文本,例如:

Give your ResultPane a new public method that allows you to extract the text from its JLabel, something like:

  public String getResultText() {
     return result.getText();
  }

然后在想要获取该字段的文本时调用它:

And then call it when you want to get the text of that field:

  public class ToText1Action extends AbstractAction {
     public ToText1Action() {
        putValue(NAME, "Finish");
     }

     @Override
     public void actionPerformed(ActionEvent e) {
         String resultText = resultPane.getResultText();
         double number = // extract number from resultText
         firstNumberField.setText(number);
     }
  }

更好的是,只需将最新结果值存储在double变量,它是类的实例字段,比如名为 lastResult ,并设置firstNumberField。

Better still, simply store the latest result value in a double variable that is an instance field of the class, say called lastResult and set the firstNumberField with that.

注意你不应该有空的拦截块。

Note that you should not have empty catch blocks.

编辑

例如:

public class CalculatorPane extends JPanel {
  private final ResultPane resultPane;
  private final JLabel firstNumberLabel = new JLabel("First Number:");
  private final JLabel secondNumberLabel = new JLabel("Second Number:");
  private final JTextField firstNumberField = new JTextField(5);
  private final JTextField secondNumberField = new JTextField(5);

  private double result = 0.0;   // ****** declared here

  // ***** etc..... *****

  public class DivideAction extends AbstractAction {

     public DivideAction() {
        putValue(NAME, "/");
     }

     @Override
     public void actionPerformed(ActionEvent e) {
        try {
           double num1 = Double.parseDouble(firstNumberField.getText());
           double num2 = Double.parseDouble(secondNumberField.getText());

           result = num1 / num2; // ****** note variable not declared
           resultPane.setResult(result);
        } catch (NumberFormatException exp) {
           // show error message
           // set text fields to "0"
        }
     }

  }

  public class ToText1Action extends AbstractAction {
     public ToText1Action() {
        super("Finish");
        putValue(MNEMONIC_KEY, KeyEvent.VK_F);
     }

     @Override
     public void actionPerformed(ActionEvent e) {
        firstNumberField.setText(String.format("%.2f", result));
     }
  }

这篇关于如何将值从一个JLabel传输到另一个JLabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 16:15