Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何实现documentlistener_Java_Swing_User Interface_Gridbaglayout_Documentlistener - Fatal编程技术网

Java 如何实现documentlistener

Java 如何实现documentlistener,java,swing,user-interface,gridbaglayout,documentlistener,Java,Swing,User Interface,Gridbaglayout,Documentlistener,我已经创建了一些文本字段,我想从中使用用户输入。我已经读到我应该使用documentlistener,但是在我认为正确的地方实现它有一些困难 在代码中,我试图将其实现到文本字段tf1。im应该得到的输入被解析为一个double,这样我就可以对它进行一些数学计算 这是我试图实现它的代码 import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Dimension; import java.awt

我已经创建了一些文本字段,我想从中使用用户输入。我已经读到我应该使用documentlistener,但是在我认为正确的地方实现它有一些困难

在代码中,我试图将其实现到文本字段tf1。im应该得到的输入被解析为一个double,这样我就可以对它进行一些数学计算

这是我试图实现它的代码

import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


public class Display {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;

public static void addComponentsToPane(Container pane) {

    if (RIGHT_TO_LEFT) {
        pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }
    JButton button;
    JLabel label;

    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    if (shouldFill) {
    //natural height, maximum width
    c.fill = GridBagConstraints.HORIZONTAL;
    }
    if (shouldWeightX) {
    c.weightx = 0.5;
    }

    ...

    button = new JButton("Value Bet");
    c.fill = GridBagConstraints.HORIZONTAL;
    c.ipady = 0;
    c.gridx = 0;
    c.gridy = 1;
    pane.add(button, c);
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            JFrame frame = new JFrame("Value Bet");
            frame.setVisible(true);
            frame.setSize(500,300);
            GridBagLayout layout = new GridBagLayout();
            frame.setLayout(layout);
            GridBagConstraints c = new GridBagConstraints();

            JLabel label;
            JTextField tf;

            if (shouldFill) {
            //natural height, maximum width
            c.fill = GridBagConstraints.HORIZONTAL;
            }
            if (shouldWeightX) {
            c.weightx = 0.5;
            }

            ...

            final JTextField tf1 = new JTextField();
            c.fill = GridBagConstraints.HORIZONTAL;
            c.gridx = 1;
            c.gridy = 2;
            frame.add(tf1, c);

            tf1.getDocument().addDocumentListener(new DocHandler(){
                public class DocHandler implements DocumentListener{

                    @Override
                    public void changedUpdate(DocumentEvent arg0) {
                        tfHasChanged();

                    }

                    @Override
                    public void insertUpdate(DocumentEvent arg0) {
                        tfHasChanged();

                    }

                    @Override
                    public void removeUpdate(DocumentEvent arg0) {
                        tfHasChanged();

                    }

                }

                public void tfHasChanged(){
                    double chance1 = Double.parseDouble(tf1.getText());
                }
            });      

            ... div components


}

 private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Betting Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the content pane.
        addComponentsToPane(frame.getContentPane());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

 public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

对于数字,您必须实现DocumentFilter或直接将JFormattedTextField与数字格式化程序一起使用

然后是可能的方式(块执行)代码行

formatter.setMinimum(0.0);
formatter.setMaximum(1000.00);
并为
textField1
添加一些公式,例如
textField1
等于
textField2
中的值,例如

import java.awt.*;
import java.awt.font.TextAttribute;
import java.math.*;
import java.text.*;
import java.util.Map;
import javax.swing.*;
import javax.swing.JFormattedTextField.*;
import javax.swing.event.*;
import javax.swing.text.InternationalFormatter;

public class DocumentListenerAdapter {

    public static void main(String args[]) {
        JFrame frame = new JFrame("AbstractTextField Test");
        final JFormattedTextField textField1 = new JFormattedTextField(new Float(10.01));
        textField1.setFormatterFactory(new AbstractFormatterFactory() {

            @Override
            public AbstractFormatter getFormatter(JFormattedTextField tf) {
                NumberFormat format = DecimalFormat.getInstance();
                format.setMinimumFractionDigits(2);
                format.setMaximumFractionDigits(2);
                format.setRoundingMode(RoundingMode.HALF_UP);
                InternationalFormatter formatter = new InternationalFormatter(format);
                formatter.setAllowsInvalid(false);
                formatter.setMinimum(0.0);
                formatter.setMaximum(1000.00);
                return formatter;
            }
        });
        final Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
        attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
        final JFormattedTextField textField2 = new JFormattedTextField(new Float(10.01));
        textField2.setFormatterFactory(new AbstractFormatterFactory() {

            @Override
            public AbstractFormatter getFormatter(JFormattedTextField tf) {
                NumberFormat format = DecimalFormat.getInstance();
                format.setMinimumFractionDigits(2);
                format.setMaximumFractionDigits(2);
                format.setRoundingMode(RoundingMode.HALF_UP);
                InternationalFormatter formatter = new InternationalFormatter(format);
                formatter.setAllowsInvalid(false);
                //formatter.setMinimum(0.0);
                //formatter.setMaximum(1000.00);
                return formatter;
            }
        });
        textField2.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void changedUpdate(DocumentEvent documentEvent) {
                printIt(documentEvent);
            }

            @Override
            public void insertUpdate(DocumentEvent documentEvent) {
                printIt(documentEvent);
            }

            @Override
            public void removeUpdate(DocumentEvent documentEvent) {
                printIt(documentEvent);
            }

            private void printIt(DocumentEvent documentEvent) {
                DocumentEvent.EventType type = documentEvent.getType();
                double t1a1 = (((Number) textField2.getValue()).doubleValue());
                if (t1a1 > 1000) {
                    Runnable doRun = new Runnable() {

                        @Override
                        public void run() {
                            textField2.setFont(new Font(attributes));
                            textField2.setForeground(Color.red);
                        }
                    };
                    SwingUtilities.invokeLater(doRun);
                } else {
                    Runnable doRun = new Runnable() {

                        @Override
                        public void run() {
                            textField2.setFont(new Font("Serif", Font.BOLD, 16));
                            textField2.setForeground(Color.black);
                        }
                    };
                    SwingUtilities.invokeLater(doRun);
                }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.NORTH);
        frame.add(textField2, BorderLayout.SOUTH);
        frame.setVisible(true);
        frame.pack();
    }

    private DocumentListenerAdapter() {
    }
}

如果tf1是一个文本字段,则文档侦听器将实现3种方法,如changedUpdate、insertUpdate、removeUpdate

tf1.getDocument().addDocumentListener(new DocumentListener() {

    @Override
        public void changedUpdate(DocumentEvent e){

                              //do some math
                               tf1.getText(); 
                                   }

        @Override
        public void insertUpdate(DocumentEvent e) {

                                  /do some math
                               tf1.getText(); 
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            // TODO Auto-generated method stub

        }
});    

我建议您放弃整个方法,使用模态对话框,正如我在上一个问题中建议的那样。或者,为了获得最好的帮助,至少解释一下为什么你不想采用这种方法。为了更快地获得更好的帮助,请发布一个。给定
“价值赌注”
,我一直认为最好的组件应该是一个
JSpinner
,带有
NumberModel
——但是OP似乎忽略了我@安德鲁·汤普森(Andrew Thompson)当然,我的坏习惯是,默认情况下,我从不检查askers用户档案,这是为了保护我的精神健康:-)我通常不检查档案,只是在我有强烈的似曾相识感的时候(哦,别激动,那些有趣的小技巧可能是正确的,因为我复制/粘贴了;)。