【问题标题】:Getting data from JSpinner and store it into an Array从 JSpinner 获取数据并将其存储到数组中
【发布时间】:2019-12-03 20:06:34
【问题描述】:

我目前遇到了另一个问题,这次是 JSpinners。我想通过添加按钮通过右键单击在屏幕上动态添加 JSpinners。添加它们之后,我希望将它们插入到 JSpinner 数组中,然后将来自 JSpinner 的数据存储到 Date ArrayList 中。到目前为止,我面临这个问题:

  • 如果我添加一个新的 JSpinner,日期数组不会自动从第二个或第三个 JSpinner 获取日期。它只从第一个 JSpinner 获取数据。

我真的迷路了。感谢这里的任何帮助。谢谢和最好的问候

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;

public class TestingGround
{
    Toolkit toolkit;
    JFrame frame;
    JPopupMenu menu;

    Calendar calendar1, calendar2;
    Date startDate, saveThisDate;
    String stringStoredInitialRequestDate;
    ArrayList <Date> dateArray; // array to store the dates from the request date
    JSpinner spinner;
    ArrayList <JSpinner> spinnerArray;
    SpinnerModel model1;


    int countAddClicks;
    int val1;

    public TestingGround()
    {
        frame = new JFrame("Testing ground area");

        centerToScreen();

        menu = new JPopupMenu();
        JMenuItem addRow = new JMenuItem("Add ComboBox");
        JMenuItem removeRow = new JMenuItem("Remove ComboBox");
        JPanel panel = new JPanel();
        JPanel mainGridPanel = new JPanel(); 

        mainGridPanel.setLayout(new GridLayout(0,2));
        mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
        panel.add(mainGridPanel);
        // -------------------------------------------

        dateArray = new <Date> ArrayList(); // array used to store the initial request dates
        spinnerArray = new <JSpinner> ArrayList();

        JButton saveDataButton = new JButton("save state");
        countAddClicks =0;
        val1 = -1;
        panel.add(saveDataButton);

        // ACTION LISTENERS
        addRow.addActionListener(new ActionListener(){ // Right click to add JComboBoxes to the screen
                public void actionPerformed(ActionEvent event) {
                    System.out.println("Starting click is: " + countAddClicks);

                    // JSPINNER 1
                    calendar1 = Calendar.getInstance();
                    Date now = calendar1.getTime();
                    calendar1.add(Calendar.YEAR, -10);

                    Date startDate = calendar1.getTime();
                    calendar1.add(Calendar.YEAR, 20);

                    Date endDate = calendar1.getTime();

                    model1  = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);

                    spinner  = new JSpinner(model1); // creating Visual Spinner 
                    String format = "dd MMM yy"; // formatting Visual Spinner 1

                    JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
                    spinner.setEditor(editor); // applying the formatting to the visual spinner  

                    spinnerArray.add(countAddClicks,spinner); // adds the spinner to the array of spinners

                    /*
                    model1.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent e) {
                    changedDate = ((SpinnerDateModel) e.getSource()).getDate();

                    }
                    });
                     */
                    saveThisDate = now;
                    dateArray.add(countAddClicks, saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);   
                    countAddClicks++;

                    System.out.println("After click is: " + countAddClicks);         

                    mainGridPanel.add(spinner); // add the JTextField to the JPanel
                    mainGridPanel.repaint();
                    mainGridPanel.revalidate();

                }
            });

        removeRow.addActionListener(new ActionListener(){
                public void actionPerformed (ActionEvent event) {
                    countAddClicks--;  

                    if (countAddClicks <0) {
                        countAddClicks = 0;
                    }

                    if (spinnerArray.size() > 0 & dateArray.size() >0 ) {

                        spinner = spinnerArray.remove(spinnerArray.size()-1);
                        mainGridPanel.remove(spinner);
                    }

                    System.out.println("After removal click is: " + countAddClicks);
                    mainGridPanel.revalidate();      
                    mainGridPanel.repaint();

                }
            });

        saveDataButton.addActionListener (new ActionListener() {
                public void actionPerformed(ActionEvent e) {


                   dateArray.clear();  

                    for (int i=0; i< spinnerArray.size(); i++) {

                        JSpinner tempSpinner = spinnerArray.get(i); // creating a temporary spinner

                        calendar2 = Calendar.getInstance(); // creating a temporary calendar

                        Date now2 = calendar2.getTime(); 
                        calendar1.add(Calendar.YEAR, -50);

                        Date startDate2 = calendar2.getTime();
                        calendar2.add(Calendar.YEAR, 50);

                        Date endDate2 = calendar2.getTime();

                        SpinnerModel model2  = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);

                        tempSpinner.setModel(model2); // setting up a temporary spinnerModel and adding it to this instance of JSpinner


                        model2.addChangeListener(new ChangeListener() { // adding a listener to this model2
                                public void stateChanged(ChangeEvent e) {
                                    saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking for user input
                                    System.out.println(saveThisDate); // for testing purpose it is showing that it detects the change
                                }

                            });    




                          dateArray.add(saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);   

                        }



                    // Only for checking purpose if the arrays are the correct sizes
                    System.out.println();
                    System.out.println("The size of the JSpinner Array is: " + spinnerArray.size() ); // showing correct
                    System.out.println("The content of the Date Array is: " + dateArray ); // checking the Date array. This is where data is not added, it is not working!
                    System.out.println("The size of the Date Array is: " + dateArray.size()); // showing correct
                    System.out.println();
                }

            });
        // Cand dau click din butonul cel mai din dreapta (3) se deschide menium popup 
        frame.addMouseListener(new MouseAdapter() {
                public void mouseReleased(MouseEvent event) {
                    if (event.getButton() == event.BUTTON3) {
                        menu.show(event.getComponent(), event.getX(),event.getY());
                    }
                } 
            }); 

        menu.add(addRow);
        menu.add(removeRow);

        frame.add(panel);

        frame.setVisible(true);
    }

    public void centerToScreen()
    {
        frame.setSize(700,600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("A Popup Menu");

        toolkit = frame.getToolkit();
        Dimension size = toolkit.getScreenSize();
        frame.setLocation((size.width-frame.getWidth())/2, (size.height-frame.getHeight())/2);

    }

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

【问题讨论】:

  • 为什么。我的意思是这些问题真的很明确和明确。不要删除,如果您真的想删除它,请留下一个问题,因为“太宽泛”...
  • 因为这些是网站的规则。它本身不是一个帮助网站,也不是“请帮我完成我的作业网站”,而是一个问答网站,这意味着您的问题应该尽可能具体。正如@AndrewThompson 所指出的那样,多部分问题不合适。
  • 修改为只询问一个问题。我无法删除代码,因为它不会清楚然后搜索问题。我认为问题出在“saveDateButton”部分,但还要留下其他代码来理解所有问题。
  • “到目前为止我正面临这个问题:” 好的 .. 这足以让我删除近距离投票。但如果这里有一个实际问题,“导致此问题的代码错误是什么?”“我该如何解决这个问题,那将是理想问题?” .. 和提示:添加@HovercraftFullOfEels(或重要的@)以通知新评论的人。

标签: java swing jspinner


【解决方案1】:

其中一个 ArrayList 中的空值的来源:您正在将空值添加到 dateArray ArrayList

    Date changedDate; // null


    addRow.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // .....
            dateArray.add(countAddClicks, changedDate);  // changedDate is null

而且您永远不会更改这些值。是的,您将 new Date 实例分配给 changedDate 变量,但 ArrayList 没有保存变量,它保存的是 objects

注意这里:

    saveDataButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dateArray.clear();
            for (int i = 0; i < spinnerArray.size(); i++) {
                //.....
                model2.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent e) {
                        changedDate = ((SpinnerDateModel) e.getSource()).getDate();  // **** (A) ****
                        System.out.println(changedDate);
                    }
                });
                // ...
            }
        }
    });

再次更改 dateArray 变量持有的 Date 实例,但同样,这对 ArrayList 持有的空值没有影响。

我建议您摆脱 dateArray ArrayList,而是在需要时(在侦听器中)从 JSpinner 中提取数据。

【讨论】:

  • @zypa:但是你明白我上面解释的空值的原因吗?您正试图在错误的时间提取 Date 数据,在用户有机会设置它之前,在它只是 null 之前。相反,如果您需要存储的日期,请在侦听器中用户设置它们之后提取它们。
  • 我现在会尝试解决这个问题。给我一些时间,并感谢有关空值问题的更新。有道理
  • @zypa:这些日期的目的是什么?如果删除了微调器,则要从列表中删除日期吗?更多背景信息将非常有帮助。
  • @zypa: 所以你需要一个 MVC 结构,其中一个非 GUI 模型对象应该代表每一行或每一行,并保存每一行中显示的数据,以及一个“视图”对象,可能是一个创建 JPanel 的对象,该 JPanel 包含并显示单行,其状态由其模型对象表示,......也许还有一个模型对象的 ArrayList......
  • @zypa:不要屈服于绝望,尤其是这么快。请理解,最激烈的学习来自于斗争,斗争越艰辛,学习的效果就越好。
【解决方案2】:

@Hovercraft Full Of Eels 我已经解决了这个问题!!我很自豪,现在一切正常。因此它会动态添加 JSpinner 并将日期存储在单独的 Array Slot 中。如果有人会搜索类似的东西,我将粘贴代码,以便他们可以将其用作参考。再次感谢

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;

public class TestingGround {
    Toolkit toolkit;
    JFrame frame;
    JPopupMenu menu;

    Calendar calendar1, calendar2;
    Date startDate, saveThisDate;

    ArrayList<Date> dateArray; // array to store the dates from the request date
    JSpinner spinner;
    ArrayList<JSpinner> spinnerArray;
    SpinnerModel model1;
    JPanel mainGridPanel;

    int countAddClicks;

    public TestingGround() {
        frame = new JFrame("Testing ground area");

        centerToScreen();

        menu = new JPopupMenu();
        JMenuItem addRow = new JMenuItem("Add ComboBox");
        JMenuItem removeRow = new JMenuItem("Remove ComboBox");
        JPanel panel = new JPanel();
        mainGridPanel = new JPanel();

        mainGridPanel.setLayout(new GridLayout(0, 2));
        mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
        panel.add(mainGridPanel);
        // -------------------------------------------

        dateArray = new <Date>ArrayList(); // array used to store the initial
                                            // request dates
        spinnerArray = new <JSpinner>ArrayList();

        JButton saveDataButton = new JButton("save state");
        countAddClicks = 0;

        panel.add(saveDataButton);

        // ACTION LISTENERS
        addRow.addActionListener(new ActionListener() { // Right click to add
                                                        // JComboBoxes to the
                                                        // screen
            public void actionPerformed(ActionEvent event) {
                System.out.println("Starting click is: " + countAddClicks);

                // JSPINNER 1
                calendar1 = Calendar.getInstance();
                Date now = calendar1.getTime();
                calendar1.add(Calendar.YEAR, -10);

                Date startDate = calendar1.getTime();
                calendar1.add(Calendar.YEAR, 20);

                Date endDate = calendar1.getTime();

                model1 = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);

                spinner = new JSpinner(model1); // creating Visual Spinner
                String format = "dd MMM yy"; // formatting Visual Spinner 1

                JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
                spinner.setEditor(editor); // applying the formatting to the
                                            // visual spinner

                spinnerArray.add(countAddClicks, spinner); // adds the spinner
                                                            // to the array of
                                                            // spinners

                saveThisDate = now;
                dateArray.add(countAddClicks, saveThisDate); // add to the DATE
                                                                // array the new
                                                                // date (in the
                                                                // correct slot,
                                                                // going side by
                                                                // side with the
                                                                // other array);
                countAddClicks++;

                System.out.println("After click is: " + countAddClicks);

                mainGridPanel.add(spinner); // add the JTextField to the JPanel
                mainGridPanel.repaint();
                mainGridPanel.revalidate();

            }
        });

        removeRow.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                countAddClicks--;

                if (countAddClicks < 0) {
                    countAddClicks = 0;
                }

                if (spinnerArray.size() > 0 & dateArray.size() > 0) {

                    spinner = spinnerArray.remove(spinnerArray.size() - 1);
                    dateArray.remove(dateArray.size() - 1);
                    mainGridPanel.remove(spinner);
                }

                System.out.println("After removal click is: " + countAddClicks);
                mainGridPanel.revalidate();
                mainGridPanel.repaint();

            }
        });

        saveDataButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                dateArray.clear();

                for (int i = 0; i < spinnerArray.size(); i++) {

                    JSpinner tempSpinner = new JSpinner(); // creating a
                                                            // temporary spinner

                    calendar2 = Calendar.getInstance(); // creating a temporary
                                                        // calendar

                    Date now2 = calendar2.getTime();
                    calendar2.add(Calendar.YEAR, -50);

                    Date startDate2 = calendar2.getTime();
                    calendar2.add(Calendar.YEAR, 50);

                    Date endDate2 = calendar2.getTime();

                    SpinnerModel model2 = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);

                    tempSpinner.setModel(model2); // setting up a temporary
                                                    // spinnerModel and adding
                                                    // it to this instance of
                                                    // JSpinner

                    model2.addChangeListener(new ChangeListener() { // adding a
                                                                    // listener
                                                                    // to this
                                                                    // model2
                        public void stateChanged(ChangeEvent e) {
                            saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking
                                                                                            // for
                                                                                            // user
                                                                                            // input
                            System.out.println(saveThisDate); // for testing
                                                                // purpose it is
                                                                // showing that
                                                                // it detects
                                                                // the change
                        }

                    });

                    saveThisDate = (Date) spinnerArray.get(i).getValue();
                    System.out.println("Content of the Spinner Array is: " + spinnerArray.get(i).getValue());
                    dateArray.add(saveThisDate); // add to the DATE array the
                                                    // new date (in the correct
                                                    // slot, going side by side
                                                    // with the other array);

                }

                // Only for checking purpose if the arrays are the correct sizes
                System.out.println();
                System.out.println("The size of the JSpinner Array is: " + spinnerArray.size()); // showing
                                                                                                    // correct
                System.out.println("The content of the Date Array is: " + dateArray); // checking
                                                                                        // the
                                                                                        // Date
                                                                                        // array.
                                                                                        // This
                                                                                        // is
                                                                                        // where
                                                                                        // data
                                                                                        // is
                                                                                        // not
                                                                                        // added,
                                                                                        // it
                                                                                        // is
                                                                                        // not
                                                                                        // working!
                System.out.println("The size of the Date Array is: " + dateArray.size()); // showing
                                                                                            // correct
                System.out.println();
            }

        });
        // Cand dau click din butonul cel mai din dreapta (3) se deschide menium
        // popup
        frame.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent event) {
                if (event.getButton() == event.BUTTON3) {
                    menu.show(event.getComponent(), event.getX(), event.getY());
                }
            }
        });

        menu.add(addRow);
        menu.add(removeRow);

        frame.add(panel);

        frame.setVisible(true);
    }

    public void centerToScreen() {
        frame.setSize(700, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("A Popup Menu");

        toolkit = frame.getToolkit();
        Dimension size = toolkit.getScreenSize();
        frame.setLocation((size.width - frame.getWidth()) / 2, (size.height - frame.getHeight()) / 2);

    }

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

【讨论】:

  • dateArray 有什么用途?所有必要的信息都保存在 spinnerArray 中,实际上在上面的代码中,当您决定提取数据时,您会清除 dateArray(丢弃所有收集的信息),然后重新填充。
  • 最终会将数据保存在excel中。还没到那一步……我想再过一个月……它进展得很慢。每个数组将进入不同的 Excel 行。现在下一步我将在一个日期和另一个日期之间添加一个计算。 In-Out 并创建一个 int 结果。这最终将按月/年分组并创建自动统计信息。非常漂亮:)
  • 那么它仍然是一种不必要且危险的数据复制,ArrayList版本的“并行数组”反模式。我强烈建议您摆脱 dateArray,并在需要数据时从组件中提取数据。
  • 好的。我理解这个问题并将审查整个代码
猜你喜欢
  • 2017-04-21
  • 2013-05-16
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 2022-09-27
  • 2019-12-22
  • 1970-01-01
  • 2011-10-10
相关资源
最近更新 更多