如何使用java swing在jlist中的现有元素下添加新元素?

时间:2017-11-08 06:50:10

标签: java swing jlist mouseclick-event

我用mlist来显示我的数据库数据。该过程适用于从数据库中获取数据并在jlist元素中显示。我需要通过click事件在jlist元素下显示我的数据。示例:包含用户名的Jlist,一旦我点击特定用户,它应该在jlist元素下面显示用户的属性。

建议我,如果有办法执行此过程,或者无法在特定的jlist元素下显示。

由于式提前。

3 个答案:

答案 0 :(得分:3)

您要做的第一件事总是首先是JavaDocstutorials,因为他们往往不会这样做,并举例说明如何做到这一点。

因此,您现在需要基于MouseEvent(或Point)的元素索引。有趣的是,在浏览JList JavaDocs时,我偶然发现了这个例子......

 MouseListener mouseListener = new MouseAdapter() {
     public void mouseClicked(MouseEvent e) {
         if (e.getClickCount() == 2) {
             int index = list.locationToIndex(e.getPoint());
             System.out.println("Double clicked on Item " + index);
          }
     }
 };
 list.addMouseListener(mouseListener);

好的,我们知道JList中元素的索引,我们可以使用ListModel#elementAt来获取可用于查询数据库的物理元素,查找属性,或者,如果您已正确完成并将实际对象嵌入到模型中,请获取属性。

将元素动态添加到JList / ListModel的唯一方法是通过可变ListModel,例如DefaultListModel

说了这么多,JTableJTree都是显示复合信息的更好的组件。

答案 1 :(得分:1)

这是动态树的工作示例,它将数据库加载为节点,将其表作为子节点加载。首先,您必须创建一个包含数据库的所有节点的root节点,然后隐藏根节点后你感觉到数据库列表。之后当我们点击任何数据库节点时,它会在树中动态加载它的表(注意:它只在单击数据库节点时加载表)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class DatabaseTree implements TreeSelectionListener {

  JFrame frame;
  DefaultTreeModel treeModel;
  DefaultTreeCellRenderer cellRenderer;
  JScrollPane pane;
  JTree tree;
  Connection connection;
  PreparedStatement pst;
  ResultSet rs;
  List<String> databaseNode = new ArrayList<String>();

  public DatabaseTree() {
    // JFrame.setDefaultLookAndFeelDecorated(true);
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    root.setUserObject("Database");
    treeModel = new DefaultTreeModel(root);
    try {
      Class.forName("com.mysql.jdbc.Driver");
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ganesh", "root",
          "admina");
      pst = connection.prepareStatement("show databases");
      rs = pst.executeQuery();
      while (rs.next()) {
        String text = rs.getString(1);
        databaseNode.add(text);
        root.add(new DefaultMutableTreeNode(text));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    tree = new JTree(treeModel);
    tree.addTreeSelectionListener(this);
    tree.setRootVisible(false);
    tree.expandRow(0);
    pane = new JScrollPane(tree);
    frame.getContentPane().add(pane);
    frame.setVisible(true);
    frame.pack();
  }

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

  @Override
  public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
    String text = (String) node.getUserObject();
    if (databaseNode.contains(text)) {
      if (node.getChildCount() == 0) {
        try {
          pst = connection.prepareStatement("show tables in " + text);
          rs = pst.executeQuery();
          while (rs.next()) {
            String data = rs.getString(1);
            node.add(new DefaultMutableTreeNode(data));
          }
        } catch (Exception ee) {
          ee.printStackTrace();
        }
      }
    }
  }
}

<强>已更新 对于树节点上的click事件,您必须在其上添加mouseListener

 tree.addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        TreePath treePath = tree.getPathForLocation(e.getX(), e.getY());
        if (treePath != null)
          String text = ((DefaultMutableTreeNode)treePath.getLastPathComponent()).getUserObject();
          txtField.setText(text);
            else
         txtField.setText("");
      }
    });
  }

答案 2 :(得分:1)

@Arunachalam这是树节点使用DefaultTreeCellRenderer包含图像的示例。

import java.awt.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;

public class DatabaseTree implements TreeSelectionListener {

  JFrame frame;
  DefaultTreeModel treeModel;
  DefaultTreeCellRenderer cellRenderer;
  JScrollPane pane;
  JTree tree;
  Connection connection;
  PreparedStatement pst;
  ResultSet rs;
  List<String> databaseNode = new ArrayList<String>();

  public DatabaseTree() {
    // JFrame.setDefaultLookAndFeelDecorated(true);
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    root.setUserObject(new JLabel("Databases", new ImageIcon("/images/g.jpg"), JLabel.CENTER));
    treeModel = new DefaultTreeModel(root);
    try {
      Class.forName("com.mysql.jdbc.Driver");
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ganesh", "root",
          "admina");
      pst = connection.prepareStatement("show databases");
      rs = pst.executeQuery();
      while (rs.next()) {
        String text = rs.getString(1);
        databaseNode.add(text);
        root.add(new DefaultMutableTreeNode(new JLabel(text, new ImageIcon("/images/g.jpg"),
            JLabel.CENTER)));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    tree = new JTree(treeModel);
    tree.setCellRenderer(new MyTreeCellRenderer());
    tree.addTreeSelectionListener(this);
    tree.setRootVisible(true);
    tree.expandRow(0);
    pane = new JScrollPane(tree);
    frame.setContentPane(pane);
    frame.setVisible(true);

  }

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

  @Override
  public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
    String text = ((JLabel) node.getUserObject()).getText();
    JLabel label = null;
    if (databaseNode.contains(text)) {
      if (node.getChildCount() == 0) {
        try {
          pst = connection.prepareStatement("show tables in " + text);
          rs = pst.executeQuery();
          while (rs.next()) {
            String data = rs.getString(1);
            label = new JLabel(data);
            node.add(new DefaultMutableTreeNode(label));
          }
        } catch (Exception ee) {
          ee.printStackTrace();
        }
      }
    }
  }

  class MyTreeCellRenderer extends DefaultTreeCellRenderer {

    JLabel label;

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                                                  boolean expanded, boolean leaf, int row,
                                                  boolean hasFocus) {

      DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
      label = (JLabel) node.getUserObject();

      if (selected) {
        label.setBackground(backgroundSelectionColor);
        label.setForeground(textSelectionColor);
      } else {
        label.setBackground(backgroundNonSelectionColor);
        label.setForeground(textNonSelectionColor);
      }
      return label;
    }
  }
}