简体   繁体   English

如何禁用或启用按钮取决于Jlist中的组件数

[英]How to disable or able buttons depends on the number of components in Jlist

everyone. 大家。 I am implementing drag and drop GUI. 我正在实现拖放GUI。 What I want to do at the moment is disable or able the buttons on my GUI depends on the number of components of Jlist. 目前我想做的是禁用或使我的GUI上的按钮取决于Jlist组件的数量。

Here is my code 这是我的代码

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

@SuppressWarnings("serial")
public class FileDragDemo extends JPanel {
    private JList list = new JList();

public FileDragDemo() {
  list.setDragEnabled(true);
  list.setTransferHandler(new FileListTransferHandler(list));


  JScrollPane scrollPane = new JScrollPane(list);





  JButton btnCompare = new JButton("Compare");
  btnCompare.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent arg0) {

      }
  });

  JButton btnAnalyze = new JButton("Analyze");
  btnAnalyze.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {


      }
  });

  JButton btnRefresh = new JButton("Refresh");
  btnRefresh.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
          DefaultListModel listModel = (DefaultListModel) list.getModel();
          listModel.removeAllElements();

      }
  });



  if (list.getModel().getSize() > 1){
      btnAnalyze.setEnabled( false );
  }

//      if (listModel.getSize() > 1){
//          btnAnalyze.setEnabled( false );
//      }

  GroupLayout groupLayout = new GroupLayout(this);
  groupLayout.setHorizontalGroup(
      groupLayout.createParallelGroup(Alignment.LEADING)
          .addGroup(groupLayout.createSequentialGroup()
              .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 316, GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(ComponentPlacement.RELATED)
              .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
                  .addComponent(btnRefresh, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addComponent(btnAnalyze, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                  .addComponent(btnCompare, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
              .addContainerGap())
  );
  groupLayout.setVerticalGroup(
      groupLayout.createParallelGroup(Alignment.LEADING)
          .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 144, GroupLayout.PREFERRED_SIZE)
          .addGroup(groupLayout.createSequentialGroup()
              .addContainerGap()
              .addComponent(btnCompare)
              .addPreferredGap(ComponentPlacement.RELATED)
              .addComponent(btnAnalyze)
              .addPreferredGap(ComponentPlacement.RELATED)
              .addComponent(btnRefresh))
  );
  setLayout(groupLayout);
 }



 private static void createAndShowGui() {
  FileDragDemo mainPanel = new FileDragDemo();

  JFrame frame = new JFrame("FileDragDemo");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel);
  frame.pack();
  frame.setLocationByPlatform(true);
  frame.setVisible(true);
 }

 public static void main(String[] args) {
  SwingUtilities.invokeLater(new Runnable() {
     public void run() {
        createAndShowGui();
     }
  });
 }
}

@SuppressWarnings("serial")
class FileListTransferHandler extends TransferHandler {
private JList list;


public FileListTransferHandler(JList list) {
   this.list = list;
}

public int getSourceActions(JComponent c) {
   return COPY_OR_MOVE;
}

public boolean canImport(TransferSupport ts) {
   return ts.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}

 public boolean importData(TransferSupport ts) {
   try {
      @SuppressWarnings("rawtypes")
      List data = (List) ts.getTransferable().getTransferData(
            DataFlavor.javaFileListFlavor);
      if (data.size() < 1) {
         return false;
      }

      DefaultListModel listModel = new DefaultListModel();
      for (Object item : data) {
         File file = (File) item;
         listModel.addElement(file);

      }

      list.setModel(listModel);
      return true;

   } catch (UnsupportedFlavorException e) {
      return false;
   } catch (IOException e) {
      return false;
   }
}
}

When drag and dropped elements in Jlist are more than 1, I want to disable btnAnalyze. 当Jlist中的拖放元素大于1时,我想禁用btnAnalyze。 Also when drag adn dropped element in Jlist is 1, I want to disable btnCompare. 另外,当Jlist中的元素拖动和删除元素为1时,我想禁用btnCompare。

Please help me out. 请帮帮我。 Thanks 谢谢

myJList.getModel().getSize();

will give you the number of components in yout JList . 将为您提供JList的组件JList

And button.setEnabled(false); button.setEnabled(false); will disable your Button . 将禁用您的Button

Alright so the only change I really made was to move your FileListTransfer handler into the actual class so that it is really just a sub class and then declared the buttons globally. 好吧,所以我真正所做的唯一更改是将FileListTransfer处理程序移到实际的类中,以便它实际上只是一个子类,然后在全局范围内声明了按钮。 Give this a go. 快去 Basically we are using what Rakesh said and checking what the size is and enabling vs disabling as it goes. 基本上,我们正在使用Rakesh所说的内容,并检查大小,并随即启用或禁用。

Move Transfer class into same class as rest 将“转移课程”移到与其他人相同的课程中

Declare Buttons globally 全局声明按钮

package assistance;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

@SuppressWarnings("serial")
public class FileDragDemo extends JPanel {

private JList list = new JList();
private JButton btnCompare, btnAnalyze, btnRefresh;

public FileDragDemo() {
    list.setDragEnabled(true);
    list.setTransferHandler(new FileListTransferHandler(list));

    JScrollPane scrollPane = new JScrollPane(list);

    btnCompare = new JButton("Compare");
    btnCompare.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

        }
    });

    btnAnalyze = new JButton("Analyze");
    btnAnalyze.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

        }
    });

    btnRefresh = new JButton("Refresh");
    btnRefresh.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            DefaultListModel listModel = (DefaultListModel) list.getModel();
            listModel.removeAllElements();

        }
    });

//      if (listModel.getSize() > 1){
//          btnAnalyze.setEnabled( false );
//      }
    GroupLayout groupLayout = new GroupLayout(this);
    groupLayout.setHorizontalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
            .addGroup(groupLayout.createSequentialGroup()
                    .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 316, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
                            .addComponent(btnRefresh, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnAnalyze, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnCompare, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
    );
    groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(Alignment.LEADING)
            .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 144, GroupLayout.PREFERRED_SIZE)
            .addGroup(groupLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(btnCompare)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(btnAnalyze)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(btnRefresh))
    );
    setLayout(groupLayout);
}

private static void createAndShowGui() {
    FileDragDemo mainPanel = new FileDragDemo();

    JFrame frame = new JFrame("FileDragDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(mainPanel);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGui();
        }
    });
}

@SuppressWarnings("serial")
class FileListTransferHandler extends TransferHandler {

    private JList list;

    public FileListTransferHandler(JList list) {
        this.list = list;
    }

    public int getSourceActions(JComponent c) {
        return COPY_OR_MOVE;
    }

    public boolean canImport(TransferSupport ts) {
        return ts.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
    }

    public boolean importData(TransferSupport ts) {
        try {
            @SuppressWarnings("rawtypes")
            List data = (List) ts.getTransferable().getTransferData(
                    DataFlavor.javaFileListFlavor);
            if (data.size() < 1) {
                return false;
            }

            DefaultListModel listModel = new DefaultListModel();
            for (Object item : data) {
                File file = (File) item;
                listModel.addElement(file);

            }

            list.setModel(listModel);
            if (list.getModel().getSize() > 1) {
                btnCompare.setEnabled(true);
                btnAnalyze.setEnabled(false);
            } else if (list.getModel().getSize() == 1) {
                btnCompare.setEnabled(false);
                btnAnalyze.setEnabled(true);
            }
            return true;

        } catch (UnsupportedFlavorException e) {
            return false;
        } catch (IOException e) {
            return false;
        }
    }
  }
}

在此处输入图片说明

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM