Java使用JCheckboxes从文件中对数据进行排序

时间:2013-04-30 08:43:34

标签: java swing jcheckbox

我正在尝试创建一个程序,该程序将从随机访问文件中获取数据,并根据用户选择的任何复选框对其进行排序。数据应按银行帐号,客户名称或余额进行排序(当用户单击该复选框时,文本区域中的数据将根据该数据进行排序)。数据排序后,输出到JTextArea。我还试图在复选框下方的文本字段中输出文件中的条目总数。

谢谢!

import java.lang.reflect.Array;
import java.nio.file.*;
import java.text.DecimalFormat;
import java.util.Collections;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.*;
import javax.swing.border.Border;

public class  GUIBankAcctSorter extends JFrame implements ItemListener {

    public static void main(String[] args) {

        GUIBankAcctSorter myFrame = new GUIBankAcctSorter();
        myFrame.setVisible(true);

        Path file = Paths.get("C:\\Java\\Bank.txt");

        final String ID_FORMAT = "0000";
        final String NAME_FORMAT = "        ";
        final int NAME_LENGTH = NAME_FORMAT.length();
        final String BALANCE_FORMAT = "00000.00";

        String delimiter = ",";

        String s = ID_FORMAT + delimiter + NAME_LENGTH + delimiter + BALANCE_FORMAT + System.getProperty("line.separator");

        final String EMPTY_ACCT = "0000";

        String[] array = new String[3];
        double balance = 0;

        output(s, array, delimiter,  balance,  EMPTY_ACCT, file);

        }

    private static final long serialVersionUID = 1L;
    private static final int WIDTH = 450;
    private static final int HEIGHT = 310;
    private static final int X_ORIGIN = 200;
    private static final int Y_ORIGIN = 200;

    JLabel title = new JLabel("Bank Account Sorter");
    JLabel sort = new JLabel("Sort By             ");
    JLabel total = new JLabel("Total # of Bank Accounts  ");

    private Container con = getContentPane();
    private FlowLayout layout = new FlowLayout();

    static JTextArea area = new JTextArea(10, 35); 
    static JTextField field = new JTextField(5);

    JCheckBox cust = new JCheckBox(" Cust # ", false);       
    JCheckBox bal = new JCheckBox(" Balance ", false);
    JCheckBox name = new JCheckBox(" Name ", false);


    public static void output(String s, String[] array, String delimiter, double balance, String EMPTY_ACCT, Path file){        
        String temp = "";
        try{
        InputStream iStream = new BufferedInputStream(Files.newInputStream(file));
        BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));     

        while(s != null){
            array = s.split(delimiter);
                if(!array[0].equals(EMPTY_ACCT)){
                    balance = Double.parseDouble(array[2]); 
                    area.append("Cust # " + array[0] + "\t" + " Name: " + array[1] + " Balance " + "\t$" + array[2]  + "\n");                   
                }                               
                    s = reader.readLine();                                          
            } 
            reader.close();

        }catch(Exception e){
            System.out.println("Message: " + e);
        }   
        field.setText(temp);
    }

    public GUIBankAcctSorter(){
        super("Bank Account Sorter");
        Font headFont = new Font("Arial", Font.BOLD, 28);
        con.setLayout(layout);              

        title.setFont(headFont);
        con.add(title);

        area.setEditable(false);
        field.setEditable(false);

        con.add(new JScrollPane(area));

        cust.addItemListener(this);
        bal.addItemListener(this);
        name.addItemListener(this);

        con.add(sort);
        con.add(cust);
        con.add(bal);
        con.add(name);      
        con.add(total);
        con.add(field);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT);
        setResizable(false);
        setLocationRelativeTo(null);        
    }

    public void itemStateChanged(ItemEvent e) {
        Object source = e.getSource();
        int select = e.getStateChange();

        if(source == cust){
            if(select == ItemEvent.SELECTED){
                bal.setSelected(false);
                name.setSelected(false);
            }
        }

        if(source == bal){
            if(select == ItemEvent.SELECTED){
                cust.setSelected(false);
                name.setSelected(false);
            }
        }

        if(source == name){
            if(select == ItemEvent.SELECTED){
                cust.setSelected(false);
                bal.setSelected(false);
            }
        }                   

    }

}

2 个答案:

答案 0 :(得分:1)

在这里,您可以看到一个使用比较器对对象进行排序的好例子。

让我们假设: RowTest是一个表示单行网格的类。 orderAMT是Row的类变量/ Column / JTextField。 现在,下面的代码显示了如何根据其属性orderAMT对RowTest列表进行排序。

 List<RowTest> sortedList = getAllRowsThatNeedToBeSorted();
        Comparator comparator = new OrderAMTComparator();
        Collections.sort(sortedList, comparator);





    public class OrderAMTComparator implements Comparator<RowTest> {

        @Override
        public int compare(RowTest o1, RowTest o2) {
//Here you can use If condition to check which checkbox is selected and sort the list 
//repace getOrderAMT with other fields.

            BigDecimal compareRes = o1.getOrderAMT().getBigdecimalValue().subtract(o2.getOrderAMT().getBigdecimalValue());

//You can just return compareRes.compareTo(new BigDecimal(0))
//But Here I want to show that you can check any condition and return -1,1,0 as your
//requirement      

            if (compareRes.compareTo(new BigDecimal(0)) == -1) {
                return -1;
            } else if (compareRes.compareTo(new BigDecimal(0)) == 1) {
                return 1;
            } else if (compareRes.compareTo(new BigDecimal(0)) == 0 ) {
                return 0;
            }
            return compareRes.intValue();
        }
    }

我希望你明白这一点。如果没有,我会详细说明。 三江源。

答案 1 :(得分:1)

  

无论如何都要使用复选框吗?

当然:

  • 声明一个Account类,用于存储帐号,名称和号码。平衡。
  • 将每个新Account添加到List <{1}}结构中,例如ArrayList.
  • 创建与2个字段中的每个字段相关的Comparator
  • 在排序时,请使用Collections.sort(list,comparator)
  • 使用已排序列表的内容刷新文本区域。

其他提示

  • 由于这些复选框是互斥的,因此它们应该是ButtonGroup JRadioButton个实例。
  • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);更改为setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);&amp; setLocationRelativeTo(null)setLocationByPlatform(true)。有关演示,请参阅this answer
  • 更改setBounds(X_ORIGIN, Y_ORIGIN, WIDTH, HEIGHT);的{​​{1}}(并更有效地使用布局)。