- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
应用简单,一个框架中有两个面板
第一个面板,从数据库中检索所有学生,使用多个 hashmap 获取父子排列并将其显示在树上。
第二个面板,当您点击一个学生时,该学生的所有详细信息 (selectionlistener) 都会显示在文本框中。
现在,当我在第二个面板上更改学生的姓名时,数据库会正确更新它,但树显示旧值。
我试过 treepanel.reload(),我试过 treemodellistener。
谁能帮帮我。在网上浏览了很多解决方案,都是部分的,我无法将其应用到我的代码中。
提前致谢。
主框架.java
/**
* @author Suraj Baliga
*
* Returns a JFrame with two Panels one having the Jtree and other
* having the details of the selected tree component.It also has dynamic tree and
* dynamic textbox where updation of text in the textbox will change the value in
* databse on click of save button.The JDBC localhost url may change with each machine
* as the database location and port number may vary.
*/
package Student_Details;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import org.apache.commons.collections.MultiHashMap;
public final class Main_frame extends JPanel
{
String sname,sschool;
ArrayList StudName_arrylst = new ArrayList();
ArrayList SchlName_arrylst = new ArrayList();
ArrayList StudDetailTxtFld_arrylst = new ArrayList();
static public Connection connect,connect_update;
public ResultSet resultSet;
public static ResultSet resultset2;
MultiHashMap SchlStud_hashmap = new MultiHashMap();
int i,j,k,k2,z;
DefaultMutableTreeNode tree_parent;
int SchlName_arylist_length, StudNamearrylst_length;
private tree_generation treePanel;
static JButton save_button = new JButton("Save");
static JButton cancel_button = new JButton("Cancel");
static JTextField studName_txtbox= new JTextField();
static JTextField studAddress_txtbox = new JTextField();
static JTextField studOthr_txtbox = new JTextField();
static public String user_name;
static public String user_add;
static public String user_other;
static JLabel name_label = new JLabel("Name : ");
static JLabel address_label = new JLabel("Adress : ");
static JLabel other_label = new JLabel("Other Deatils : ");
static String studDetailsTxtbox_disp[] = new String[10];
static String studDetailsTxtbx_disp_db[] = new String[10];
static String studDetailsTxtbxchange[] = new String[10];
public JPanel panel;
static JPanel panel_boxes = new JPanel();
public Main_frame()
{
super(new BorderLayout());
//Create the components.
treePanel = new tree_generation();
populateTree(treePanel);
//Lay everything out.
treePanel.setPreferredSize(new Dimension(300, 150));
add(treePanel, BorderLayout.WEST);
panel = new JPanel(new GridLayout(1, 2));
add(panel, BorderLayout.CENTER);
}
public void populateTree(tree_generation treePanel)
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement AllStuddetails = connect.prepareStatement("SELECT * from student_details");
resultSet = AllStuddetails.executeQuery();
while (resultSet.next())
{
sname = resultSet.getString(1);
sschool = resultSet.getString(3);
SchlStud_hashmap.put(sschool, sname);
}
}
catch (Exception e)
{
}
Set keySet = SchlStud_hashmap.keySet();
Iterator keyIterator = keySet.iterator();
while (keyIterator.hasNext())
{
Object key = keyIterator.next();
SchlName_arrylst.add(key);
Collection values = (Collection) SchlStud_hashmap.get(key);
Iterator valuesIterator = values.iterator();
while (valuesIterator.hasNext())
{
StudName_arrylst.add(valuesIterator.next());
}
SchlName_arylist_length = SchlName_arrylst.size();
StudNamearrylst_length = StudName_arrylst.size();
String schlname_tree[] = new String[SchlName_arylist_length];
String studname_tree[] = new String[StudNamearrylst_length];
Iterator SchlName_iterator = SchlName_arrylst.iterator();
i = 0;
while (SchlName_iterator.hasNext())
{
schlname_tree[i] = SchlName_iterator.next().toString();
}
Iterator StudName_iterator = StudName_arrylst.iterator();
j = 0;
while (StudName_iterator.hasNext())
{
studname_tree[j] = StudName_iterator.next().toString();
j++;
}
for (k = 0; k < schlname_tree.length; k++)
{
tree_parent = treePanel.addObject(null, schlname_tree[k]);
for (k2 = 0; k2 < studname_tree.length; k2++)
{
treePanel.addObject(tree_parent, studname_tree[k2]);
}
}
StudName_arrylst.clear();
SchlName_arrylst.clear();
}
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("Student Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
Main_frame newContentPane = new Main_frame();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
panel_boxes.setLayout(null);
name_label.setBounds(55,90,150,100);
studName_txtbox.setBounds(225,130, 155, 25);
panel_boxes.add(name_label);
panel_boxes.add(studName_txtbox);
address_label.setBounds(55,160, 150, 100);
studAddress_txtbox.setBounds(225,200, 155, 25);
panel_boxes.add(address_label);
panel_boxes.add(studAddress_txtbox);
other_label.setBounds(55,220, 150, 100);
studOthr_txtbox.setBounds(225,270, 155, 25);
panel_boxes.add(other_label);
panel_boxes.add(studOthr_txtbox);
save_button.setBounds(150,350, 100, 50);
cancel_button.setBounds(350,350, 100, 50);
panel_boxes.add(save_button);
panel_boxes.add(cancel_button);
frame.add(panel_boxes);
//Display the window.
frame.pack();
frame.setSize(1000,700);
frame.setVisible(true);
save_button.setEnabled(false);
cancel_button.setEnabled(false);
studName_txtbox.addFocusListener(new FocusListener()
{
@Override //since some additional functionality is added by the user to
//the inbuilt function @override notation is used
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
@Override
public void focusLost(FocusEvent e)
{
System.out.println("out of focus textbox");
}
});
studAddress_txtbox.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
@Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
studOthr_txtbox.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e)
{
save_button.setEnabled(true);
cancel_button.setEnabled(true);
}
@Override
public void focusLost(FocusEvent e)
{
save_button.setEnabled(false);
cancel_button.setEnabled(false);
}
});
cancel_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== cancel_button )
{
clear_textboxes();
}
}
} );
save_button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== save_button )
{
selectionButtonPressed();
}
}
} );
}
public void fill_textboxes(ArrayList a1)
{
Iterator alldetails = a1.iterator();
z=0;
while (alldetails.hasNext())
{
studDetailsTxtbx_disp_db[z]= (String) alldetails.next();
System.out.println("this is the Detail : "+studDetailsTxtbx_disp_db[z]);
z++;
}
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
public static void selectionButtonPressed()
{
studDetailsTxtbxchange[0]=studName_txtbox.getText();
studDetailsTxtbxchange[1]=studAddress_txtbox.getText();
studDetailsTxtbxchange[2]=studOthr_txtbox.getText();
try
{
if((studDetailsTxtbxchange[0].equals(""))||(studDetailsTxtbxchange[0] == null)||(studDetailsTxtbxchange[1].equals(""))||(studDetailsTxtbxchange[1] == null)||(studDetailsTxtbxchange[2].equals(""))||(studDetailsTxtbxchange[2] == null))
{
JOptionPane.showMessageDialog(null,"One of the Fields is Blank","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here inside else baby..that has : : "+studDetailsTxtbxchange[0]);
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement execqry = connect.prepareStatement("select * from student_details where student_name='"+studDetailsTxtbxchange[0]+"'");
resultset2=execqry.executeQuery();
System.out.println("control at end if else");
if(resultset2.next())
{
JOptionPane.showMessageDialog(null,"Sorry This name already exists","Error",JOptionPane.ERROR_MESSAGE);
}
else
{
System.out.println("control here");
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void clear_textboxes()
{
studName_txtbox.setText(studDetailsTxtbx_disp_db[0]);
studAddress_txtbox.setText(studDetailsTxtbx_disp_db[1].toString());
studOthr_txtbox.setText(studDetailsTxtbx_disp_db[2]);
}
void dbaction(String string)
{
studDetailsTxtbox_disp[0]= string;
System.out.println("This is the stuff :" + studDetailsTxtbox_disp[0]);
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2","suraj","suraj");
PreparedStatement statement4 = connect.prepareStatement("SELECT * from student_details where student_name ='"+studDetailsTxtbox_disp[0]+"'");
resultSet = statement4.executeQuery();
while(resultSet.next())
{
user_name = resultSet.getString("student_name");
StudDetailTxtFld_arrylst.add(user_name);
System.out.println("name :"+user_name);
user_add = resultSet.getString("student_address");
StudDetailTxtFld_arrylst.add(user_add);
System.out.println("address : "+ user_add);
user_other = resultSet.getString("student_school");
StudDetailTxtFld_arrylst.add(user_other);
System.out.println("school : "+user_other);
}
}
catch (Exception e1)
{
e1.printStackTrace();
}
fill_textboxes(StudDetailTxtFld_arrylst);
}
public static void main(String[] args)
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run()
{
createAndShowGUI();
}
});
}
}
tree_generation.java
/**
* @author Suraj
*
* Tree generation and actions such as adding new parent or child takes place here
* Section Listeners for displaying relavent details of the selected student.
*/
package Student_Details;
import java.awt.GridLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
public class tree_generation extends JPanel
{
protected DefaultMutableTreeNode rootNode;
protected DefaultTreeModel treeModel;
protected JTree tree;
public String studDetailsTxtbox_disp[] = new String[10];
public tree_generation()
{
super(new GridLayout(1,0));
rootNode = new DefaultMutableTreeNode("Click for Student Details");
treeModel = new DefaultTreeModel(rootNode);
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener()
{
@Override
public void valueChanged(TreeSelectionEvent e)
{
studDetailsTxtbox_disp[0]= tree.getLastSelectedPathComponent().toString();
Main_frame db = new Main_frame();
db.dbaction(studDetailsTxtbox_disp[0]);
}
});
tree.setShowsRootHandles(true);
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane);
}
/** Add child to the currently selected node. */
public DefaultMutableTreeNode addObject(Object child)
{
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = tree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
}
else
{
parentNode = (DefaultMutableTreeNode)
(parentPath.getLastPathComponent());
}
return addObject(parentNode, child, true);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child)
{
return addObject(parent, child, false);
}
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
Object child,
boolean shouldBeVisible)
{
DefaultMutableTreeNode childNode =
new DefaultMutableTreeNode(child);
if (parent == null)
{
parent = rootNode;
}
//It is key to invoke this on the TreeModel
treeModel.insertNodeInto(childNode, parent,
parent.getChildCount());
//Make sure the user can see the new node.
if (shouldBeVisible)
{
tree.scrollPathToVisible(new TreePath(childNode.getPath()));
}
return childNode;
}
static void loadit()
{
tree_generation.treeModel.reload();
//i tried this too//
//treePanel = new tree_generation();
// populateTree(treePanel);
}
class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
/*
* If the event lists children, then the changed
* node is the child of the node we've already
* gotten. Otherwise, the changed node and the
* specified node are the same.
*/
int index = e.getChildIndices()[0];
node = (DefaultMutableTreeNode)(node.getChildAt(index));
System.out.println("The user has finished editing the node.");
System.out.println("New value: " + node.getUserObject());
}
public void treeNodesInserted(TreeModelEvent e) {
}
public void treeNodesRemoved(TreeModelEvent e) {
}
@Override
public void treeStructureChanged(TreeModelEvent e)
{
System.out.println("tree sturct changed") ;
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode)(e.getTreePath().getLastPathComponent());
node.setUserObject("HELLO WORLD");
tree.updateUI();
e.getTreePath();
}
}
}
查询 - 数据库名称:treedata2
create table student_details(student_name varchar(20),student_address varchar(30),student_school varchar(20));
insert into student_details values('suraj','mangalore','dps');
insert into student_details values('prassana','Bangalore lalbagh 23/16 2nd main road','dps');
insert into student_details values('deepika','Mangalore kadri park , 177b','dav');
insert into student_details values('sujith','delhi , rajinder nagar, d black','dav');
insert into student_details values('sanjay','bombay marina drive, 12/34','dav');
insert into student_details values('suresh','jaipur , lalbagh cjhowki','kv');
insert into student_details values('manu','surat, pune warior house','kv');
insert into student_details values('tarun','chennai, glof club','salwan');
insert into student_details values('vinay','haryana, indutrial area','hindu senior');
insert into student_details values('veeru','trivendrum, kottayam 12/77','canara')
最佳答案
好的,我想我发现了您的代码中有问题的地方,但您可能应该自己尝试并确认。
Class.forName("org.apache.derby.jdbc.ClientDriver");
connect_update = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata2", "suraj", "suraj");
PreparedStatement updateQry = connect.prepareStatement("UPDATE student_details SET student_name='"+studDetailsTxtbxchange[0]+"',student_address='"+studDetailsTxtbxchange[1]+"',student_school='"+studDetailsTxtbxchange[2]+"' WHERE student_name='"+user_name+"' and student_address='"+user_add+"'and student_school='"+user_other+"'");
updateQry.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Updated!","UPDATED",JOptionPane.OK_OPTION);
tree_generation.loadit();
在这段代码中,您确实更新了数据库,但没有更新树的模型。您正在调用静态方法 loadit()
但该方法不包含任何代码。为了工作,您可能应该刷新/重新加载您的 TreeModel。有不同的方法可以做到这一点。一种是直接发现 TreeNode 以使用新值刷新和更新它。另一种方法是重新创建您的整个 TreeModel(但如果您的树很大,这可能会很昂贵)。使用对象映射模型(例如 JPA/Hibernate),您可以通过适当的 MVC 模式和模型通知更新值的 View 来获得更清晰的东西,但它需要额外的努力来设置。
就其值(value)而言,您应该考虑删除那些 static
关键字,因为它们不是必需的,也没有被适本地使用。只要有可能,您应该尽量避免使用该关键字(除非它与 final
结合使用来描述常量值)。
还有一点,尽量使用合适的LayoutManager的而不是使用绝对定位。使用适当的布局管理器可以让您的代码更易于维护,并且在不同平台/外观和感觉上更易于移植。
关于java - 如何在 JTree 上显示动态更新?/如何刷新或重新加载 JTree?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11671242/
我正在尝试动态使用 JTree 组件。在根节点下,我有四个节点,其中之一(“操作”)可以有 0 到多个子节点。这是由用户通过根据用户请求打开的单独窗口中的可编辑列表来设置的。编辑此列表后,用户点击“保
我阅读了很多有关此的主题,但仍然存在一些问题。我正在使用 NB 的 java 桌面项目。我已经从调色板创建了树,现在每次单击按钮后我想创建新树并刷新它。所以我在我想让新的 jTree 添加一些 Def
应用简单,一个框架中有两个面板 第一个面板,从数据库中检索所有学生,使用多个 hashmap 获取父子排列并将其显示在树上。 第二个面板,当您点击一个学生时,该学生的所有详细信息 (selection
我有两个 JTrees,里面有一些模拟数据,我想要做的是能够接受每个“工作”(15663-1、15663-2 等)并为每个创建一个节点,它下面的每个部分都有一个节点,以及连接到它下面每个部分的组件。在
当我在 JMenu 上单击鼠标时,它可以正常工作。 我将鼠标移开,它就消失了(正常)。然后我双击我的 JTree 中唯一的条目。 然后,当我单击我的 JMenu 时,它看起来像这样。它出现在 JTre
当我尝试动态更新我的 JTree 时,它工作得很好,但只显示我的新树。但后来我尝试将它添加到 JFrame - 什么也没有发生。 JTree 不更新。我不明白为什么。 public MainFor
我在名为 TreeFrame 的 JFrame 子类的构造函数中包含此代码。我想在 JTree 中显示 3 个级别,每个级别 10 个项目。为什么这会按预期工作: private DefaultTre
我目前在使用 JTree 的单元格编辑器时遇到问题。我的 JTree 中有两个不同的对象:Users 和 Books。 所以用户是 Bianca,书籍是节点。这些节点内的标签(眼睛、油漆标签和垃圾桶)
如何获得 JTree只听其TreeModel虽然它实际上对用户可见,或者至少让它在相应的 JFrame 后立即取消注册。被处置了吗? 据我所知,JTree 从其模型中取消注册的唯一情况是,如果您向它传
我在扩展 JTree 时遇到了奇怪的问题。我尝试将 JTree 添加到 JScrollPane。 树应该恢复到展开状态,但它不起作用 - 树已折叠。 代码如下: if (expansionSta
我想要发生的是在编辑 JTree 时,如果我在编辑框外单击,我想提交编辑。tree.setInvokesStopCellEditing(true); 有所帮助,如果我单击 JTree 中的某处,就会提
我有一个 JTree当用户将鼠标悬停在树节点上时,我想向用户显示一些描述。 我从文档中读到我们可以使用 MouseMotionListener为此。但是我怎样才能获得鼠标移动到的节点的值呢? 任何指针
我正在使用 JTree 并在此命名 JTree 节点 我正在使用右键单击(通过弹出窗口重命名)或 F2 键或双击。但问题是:当我重命名一个名称并按下 Enter 键时,节点成功重命名,当我重命名一个名
我正在使用 Netbeans 在 JAVA 中开发一个小型桌面应用程序。我放置了一个 JTree 并动态填充它。现在一切顺利,我想实现以下两件事: 当填充 JTree 时,它会自动展开它将开始显示
我创建了一个树单元渲染器/编辑器框架,诚然有点老套,但它在 Windows 和 Linux 上运行得很好。下图展示了一个示例设置。 目标是,如果用户单击图像(数字)1 或 2,则应用程序会响应该单击,
我有两个关于 Icons 的问题。 我使用 ImageIcons 作为 JTree 上的默认图标。按照教程的建议,我使用此方法加载图标: protected ImageIcon createImage
我目前正在使用 JTree,更准确地说是使用 CheckBoxTree,这是一个由 JIDE 创建的继承类。我需要找到一种重置树的方法,意思是: 清除选择 删除节点 我尝试取消设置 Tree 变量、t
假设我的 JTree 由以下节点组成。 new DefaultMutableTreeNode("DisplayThisTextOnly {donotdisplaystringsinhere}"); 如
双击时,我将双击的 Jtree 节点的背景突出显示为绿色。当我双击其他节点时,之前选择的绿色节点应该恢复到原来的状态,并且新双击的节点应该亮起绿色。 它在某种程度上起作用,但行为不一致。当我双击子节点
我有这个 Jtree,我必须在我的 tbltables 表中插入“表”。 (我的意思是我的 MSQL 数据库中有一个名为 tbltables 的表,其中有一个表列表)。 所以这些表中也可以有表。所以现
我是一名优秀的程序员,十分优秀!