多次按下排序按钮时排序表错误? [英] Sorting Table is wrong when the sort button be pressed more than once?

查看:101
本文介绍了多次按下排序按钮时排序表错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这里有问题。我创建程序将数据添加到表中,并在按下按钮时对其进行排序。当我按下排序按钮一次,没有错。但是当我再次按下它是错误的。所以为什么?请帮我。
这是代码。

I have a problem here. I create program to add data to the table and sort it when i press the button. when i press the sort button once, it isn't wrong. but when i press again it is wrong. so why? please help me. this is the code.

Nama Class

Nama Class

public class Nama  {
    private String nama;
    private int index;

    public Nama(String n,int i){
        nama=n;index=i;
    }
    void setData(String n,int i){
        nama=n;index=i;
    }
    String nama(){
        return nama;
    }
    int ind(){
        return index;
    }


    public String toString(){
        return(String.format("%s %d", nama,index));
    }


}

MergeSort Class

MergeSort Class

    import java.util.*;
    public class MergeSortS{


        public void merge_sort(int low,int high,Nama [] a){
            int mid;
            if(low<high) {
                   mid=(low+high)/2;
                   merge_sort(low,mid,a);
                   merge_sort(mid+1,high, a);
                   merge(low,mid,high,a);
            }
        }
        public void merge(int low,int mid,int high,Nama [] a){
            int h,i,j,k;
            Nama b[]=new Nama[50];
            h=low;
            i=low;
            j=mid+1;

            while((h<=mid)&&(j<=high)){
                if(a[h].nama().compareToIgnoreCase(a[j].nama())<0){
                    b[i]=a[h];
                    h++;
                }

                else{
                    b[i]=a[j];
                    j++;
                }

                i++;
            }
            if(h>mid){
                for(k=j;k<=high;k++){
                    b[i]=a[k];
                    i++;
                }
            }
            else{
                for(k=h;k<=mid;k++){
                    b[i]=a[k];
                    i++;
                }
            }
            for(k=low;k<=high;k++) a[k]=b[k];
        }
        public MergeSortS() {
        }

    }

小组类

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Kareem
 */
public class Panel extends JPanel implements ActionListener{
    JTable table;
    JTextField tf1,tf2,tf3,tf4;
    JButton b1,b2,b3,b4,b5,b6,b7;
    Vector rows,columns,temp;
    DefaultTableModel tabModel;
    String[]data = new String[3];
    String [] column = {"Nama", "Nim", "IP"};
    Nama[] n,nim,ip;
    MergeSortS mS;
    int c=0,index=0;

    public Panel(){
        this.setBounds(0,0,1280, 800);
        this.setLayout(null);
        inaTf();
        inaTab();
        inaBut();

        n= new Nama[50];
        nim= new Nama[50];
        ip= new Nama[50];
        mS=  new MergeSortS();
        this.setVisible(true);
    }

    public void inaTab(){
                        rows=new Vector();
                columns= new Vector();
                temp= new Vector();


                addColumns(column);

            tabModel=new DefaultTableModel();
            tabModel.setDataVector(rows,columns);

            table = new JTable(tabModel);
            table.setPreferredScrollableViewportSize(new 
               Dimension(500, 70));
            table.setFillsViewportHeight(true);
            table.setBounds(100,100,200,200);
            JScrollPane scroll = new JScrollPane(table);
            scroll.setBounds(50,50,400,400);
            add(scroll);

    }
    public void inaBut(){
        b1=new JButton("add Row");
        b1.setBounds(50,600,90,25);
        add(b1);
        b1.addActionListener(this);

        b2=new JButton("Delete Row");
        b2.setBounds(170,600,90,25);
        add(b2);
        b2.addActionListener(this);

        b3=new JButton("SortName");
        b3.setBounds(290,600,120,25);
        add(b3);
        b3.addActionListener(this);
        b5=new JButton("SortNim");
        b5.setBounds(290,650,120,25);
        add(b5);
        b5.addActionListener(this);
        b6=new JButton("SortIP");
        b6.setBounds(290,700,120,25);
        add(b6);
        b6.addActionListener(this);

        b4=new JButton("RESET");
        b4.setBounds(170,650,90,25);
        add(b4);
        b4.addActionListener(this);
    }

    public void inaTf(){
        tf1=new JTextField();
        tf1.setBounds(640,50,90,25);
        add(tf1);

        JLabel l1= new JLabel("Nama \t: ");
        l1.setBounds(530,50,90,25);
        add(l1);

        tf2=new JTextField();
        tf2.setBounds(640,80,90,25);
        add(tf2);

        JLabel l2= new JLabel("Nim     : ");
        l2.setBounds(530,80,90,25);
        add(l2);

        tf3=new JTextField();
        tf3.setBounds(640,110,90,25);
        add(tf3);

        JLabel l3= new JLabel("IPK      : ");
        l3.setBounds(530,110,90,25);
        add(l3);

        tf4=new JTextField();
        tf4.setBounds(640,140,90,25);
        add(tf4);

        JLabel l4= new JLabel("Hapus Baris ke ");
        l4.setBounds(530,140,120,25);
        add(l4);
    }

        public void addRow() 
        {
                Vector r;
                r = createBlankElement();
                rows.addElement(r);

                table.addNotify();
        }
        public void addRow(String [] data) 
        {       
                Vector r=new Vector();
                r = isi(data);
                rows.addElement(r);

                table.addNotify();
        }

        public Vector createBlankElement() 
        {
                Vector t = new Vector();
                t.addElement((String) " ");
                t.addElement((String) " ");
                t.addElement((String) " ");

                return t;
        }
        public Vector isi(String[] data) {
                Vector t = new Vector();

                    for(int j=0;j<3;j++){
                        t.addElement((String) data[j]);
                    }


                return t;
        }
        public void addColumns(String[] colName) {
                for(int i=0;i<colName.length;i++)
                columns.addElement((String) colName[i]);
        }
        void deleteRow(int index) {
             if(index!=-1) { 
                rows.removeElementAt(index);
                table.addNotify();
               }


        }



    @Override
    public void actionPerformed(ActionEvent e) {
        try{
        if(e.getSource()==b1){
            data[0]=tf1.getText()+" "+index;
            n[index]=new Nama(data[0],index);
            data[1]=tf2.getText();
            nim[index]=new Nama(data[1],index);
            data[2]=tf3.getText()+rows.size();
            ip[index]=new Nama (data[2],index);
            c=c+1;
            index=index+1;
            addRow(data);
        }
        if(e.getSource()==b2){
            int i;
            i=Integer.parseInt(tf4.getText());

            deleteRow(i);

//            for(;i<rows.size();i++){
//                n[i]=n[i+1];
//            }

        }
        if(e.getSource()==b3){

          mS.merge_sort(0, rows.size()-1, n);
          temp.setSize(rows.size());
          for(int i=0;i<index;i++){
                temp.set(i, rows.get(n[i].ind()));

           }
           for(int i=0;i<index;i++){
                rows.set(i, temp.get(i));
           }
        }

        if(e.getSource()==b4){
            rows.setSize(0);
            temp.setSize(0);
            for(int i=0;i<index;i++)n[i]=null;
            index=0;
        }
        if(e.getSource()==b5){
             mS.merge_sort(0, rows.size()-1, nim);
             temp.setSize(rows.size());
           for(int i=0;i<rows.size();i++){
                temp.set(i, rows.get(nim[i].ind()));

           }

           for(int i=0;i<rows.size();i++){
                rows.set(i, temp.get(i));
           }
        }
        if(e.getSource()==b6){
             mS.merge_sort(0, rows.size()-1, ip);
             temp.setSize(rows.size());
           for(int i=0;i<rows.size();i++){
                temp.add(i, rows.get(ip[i].ind()));

           }

           for(int i=0;i<rows.size();i++){
                rows.set(i, temp.get(i));
           }
        }
           repaint();


        }
        catch (Throwable t){
         JOptionPane.showMessageDialog(null, "AAAAAA");   
        }

    }

}

Frame Class

Frame Class

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Kareem
 */
public class Frame extends JFrame {

    public Frame(){
        super("Penghitung Gaji");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
        this.setSize(1280, 800);
        this.getContentPane().add(new Panel());
        this.setVisible(true);

    }

    public static void main(String[] args) {
        Frame frame = new Frame();
    }
}

谢谢。抱歉我的英语不好。

Thanks. And Sorry for my bad english.

推荐答案


Dashing through the snow
In a one-horse open sleigh
O'er the fields we go
Laughing all the way

Bells on bobtail ring'
Making spirits bright
What fun it is to ride and sing
A sleighing song tonight!

    Jingle bells, jingle bells,
    Jingle all the way.
    Oh! what fun it is to ride
    In a one-horse open sleigh.

    Jingle bells, jingle bells, ....





  • 从代码中唱歌,如果不是这首你最喜欢的歌,请向我道歉

    • song singing from code, please to apologize me if isn't this one your favorite song

      无法评论或建议,在我的代码中排除使用的LayoutManager,我走的路径最不耐烦,我无尽的懒惰

      can't comment or suggesting, excluding used LayoutManager in my code, I walked the path of least resistance, my endless lazyness



      . . .

      代码

      import java.awt.BorderLayout;
      import java.awt.GridLayout;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      import java.util.ArrayList;
      import java.util.List;
      import javax.swing.JButton;
      import javax.swing.JFrame;
      import javax.swing.JLabel;
      import javax.swing.JPanel;
      import javax.swing.JScrollPane;
      import javax.swing.JTable;
      import javax.swing.JTextField;
      import javax.swing.ListSelectionModel;
      import javax.swing.RowSorter.SortKey;
      import javax.swing.ScrollPaneConstants;
      import javax.swing.SortOrder;
      import javax.swing.SwingConstants;
      import javax.swing.border.EmptyBorder;
      import javax.swing.table.DefaultTableCellRenderer;
      import javax.swing.table.DefaultTableModel;
      import javax.swing.table.TableRowSorter;
      
      public class MyFrame {
      
          private JFrame frame = new JFrame();
          private JTable table;
          private JPanel buttonPanel = new JPanel();
          private JPanel buttonPanelSouth = new JPanel();
          private JPanel textFieldPanel = new JPanel();
          private JPanel northPanel = new JPanel();
          private JPanel centerPanel = new JPanel();
          private JLabel l1, l2, l3, l4;
          private JTextField tf1, tf2, tf3, tf4;
          private JButton b1, b2, b3, b4, b5, b6, b7;
          private String[] columnNames = {"Nama", "Nim", "IP", "Hapus Baris ke"};
          private Object[][] data = {
              {"igor", "B01_125-358", "1.124.01.125", true},
              {"lenka", "B21_002-242", "21.124.01.002", true},
              {"peter", "B99_001-358", "99.124.01.001", false},
              {"zuza", "B12_100-242", "12.124.01.100", true},
              {"jozo", "BUS_011-358", "99.124.01.011", false},
              {"nora", "B09_154-358", "9.124.01.154", false},
              {"xantipa", "B01_001-358", "1.124.01.001", false},};
          private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
              private static final long serialVersionUID = 1L;
      
              @Override
              public boolean isCellEditable(int row, int column) {
                  switch (column) {
                      case 3:
                          return true;
                      default:
                          return false;
                  }
              }
      
              @Override
              public Class getColumnClass(int column) {
                  return getValueAt(0, column).getClass();
              }
          };
      
          public MyFrame() {
              table = new JTable(model);
              table.setAutoCreateRowSorter(true);
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.setFillsViewportHeight(true);
              table.getSelectionModel().setSelectionMode(
                      ListSelectionModel.SINGLE_SELECTION);
              DefaultTableCellRenderer stringRenderer =
                      (DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
              stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
              JScrollPane pane = new JScrollPane(table,
                      ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                      ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              centerPanel.setLayout(new BorderLayout(10, 10));
              centerPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
              centerPanel.add(pane);
              centerPanel.add(pane);
      //        
              b1 = new JButton("add Row");
              b1.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      model.addRow(new Object[]{(tf1.getText()).trim(),
                                  (tf2.getText()).trim(), (tf3.getText()).trim(), true});
                  }
              });
              b2 = new JButton("Delete Row");
              b2.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      int rowToDelete = 0;
                      int rowToModel = 0;
                      if (table.getSelectedRow() > -1) {
                          rowToDelete = table.getSelectedRow();
                          rowToModel = table.convertRowIndexToModel(rowToDelete);
                          model.removeRow(rowToModel);
                      }
                  }
              });
              b3 = new JButton("RESET");
              b3.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      table.getRowSorter().setSortKeys(null);
                  }
              });
              b4 = new JButton("SortName");
              b4.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      table.getRowSorter().toggleSortOrder(0);
                  }
              });
              b5 = new JButton("SortNim");
              b5.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      TableRowSorter rowSorter = (TableRowSorter) table.getRowSorter();
                      List<SortKey> sortKeys = new ArrayList<SortKey>();
                      SortKey sortKey = new SortKey(1, SortOrder.ASCENDING);
                      sortKeys.add(sortKey);
                      rowSorter.setSortKeys(sortKeys);
                      rowSorter.sort();
                  }
              });
              b6 = new JButton("SortIP");
              b6.addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      TableRowSorter rowSorter = (TableRowSorter) table.getRowSorter();
                      List<SortKey> sortKeys = new ArrayList<SortKey>();
                      SortKey sortKey = new SortKey(2, SortOrder.DESCENDING);
                      sortKeys.add(sortKey);
                      SortKey sortKey1 = new SortKey(1, SortOrder.ASCENDING);
                      sortKeys.add(sortKey1);
                      SortKey sortKey2 = new SortKey(0, SortOrder.UNSORTED);
                      sortKeys.add(sortKey2);
                      rowSorter.setSortKeys(sortKeys);
                      rowSorter.sort();
                  }
              });
              b7 = new JButton("SortIP");
              buttonPanel.setLayout(new GridLayout(1, 0, 50, 0));
              buttonPanel.setBorder(new EmptyBorder(2, 10, 2, 10));
              buttonPanel.add(b1);
              buttonPanel.add(b2);
      //
              buttonPanelSouth.setLayout(new GridLayout(1, 4, 5, 5));
              buttonPanelSouth.add(b3);
              buttonPanelSouth.add(b7);
              b7.setVisible(false);
              buttonPanelSouth.add(b4);
              buttonPanelSouth.add(b5);
              buttonPanelSouth.add(b6);
              centerPanel.add(buttonPanelSouth, BorderLayout.SOUTH);
      
      //
              l1 = new JLabel("Nama : ", JLabel.RIGHT);
              tf1 = new JTextField();
              l2 = new JLabel("Nim  : ", JLabel.RIGHT);
              tf2 = new JTextField();
              l3 = new JLabel("IPK : ", JLabel.RIGHT);
              tf3 = new JTextField();
              l4 = new JLabel("Hapus Baris ke :", JLabel.RIGHT);
              tf4 = new JTextField();
              textFieldPanel.setLayout(new GridLayout(4, 2, 10, 10));
              textFieldPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
              textFieldPanel.add(l1);
              textFieldPanel.add(tf1);
              textFieldPanel.add(l2);
              textFieldPanel.add(tf2);
              textFieldPanel.add(l3);
              textFieldPanel.add(tf3);
              textFieldPanel.add(l4);
              textFieldPanel.add(tf4);
      //
              northPanel.setLayout(new BorderLayout());
              northPanel.add(textFieldPanel);
              northPanel.add(buttonPanel, BorderLayout.SOUTH);
      //
              frame.add(northPanel, BorderLayout.NORTH);
              frame.add(centerPanel);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
          }
      
          public static void main(String[] arg) {
              java.awt.EventQueue.invokeLater(new Runnable() {
                  @Override
                  public void run() {
                      MyFrame myFrame = new MyFrame();
                  }
              });
          }
      }
      

      这篇关于多次按下排序按钮时排序表错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆