Using JTree to list Objects - java

Currently I am trying to learn Swing. I want to make a JTree with my ArrayList which has Object instances in it. Every object has a name and I want to able to change that name with right click and then an appearing change button. But I don't really understand the Mouselistener. I Googled and got a mouse listener but I don't know how to add the setName method.
Lager is my example Object. 400 is the capacity.
private DefaultMutableTreeNode createTree() {
Lager s = new Lager("Name",400);
DefaultMutableTreeNode root = new DefaultMutableTreeNode(s);
DefaultMutableTreeNode vegetableNode = new DefaultMutableTreeNode("Vegetables");
DefaultMutableTreeNode fruitNode = new DefaultMutableTreeNode("Fruits");
// add the child nodes to the root node
root.add(vegetableNode);
root.add(fruitNode);
return root;
}
Here is the mouse listener I copied.
DefaultMutableTreeNode root = createTree();
JTree tree = new JTree(root);
tree.addMouseListener ( new MouseAdapter ()
{
public void mousePressed ( MouseEvent e )
{
if ( SwingUtilities.isRightMouseButton ( e ) )
{
TreePath path = tree.getPathForLocation ( e.getX (), e.getY () );
Rectangle pathBounds = tree.getUI ().getPathBounds ( tree, path );
if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) )
{
JPopupMenu menu = new JPopupMenu ();
menu.add ( new JMenuItem ( "Test" ) );
System.out.println(tree.getLastSelectedPathComponent());
menu.show ( tree, pathBounds.x, pathBounds.y + pathBounds.height ); // pathBounds.y/x sind die Positionen des Lagers auf den ich Rechtsklicke
}
}
}
} );
this.add(tree);

Related

Selecting the leaf of jtree that will open another jrame in netbeans

Good day,
I am trying to create a tree view in order to display for the user the other j Frames in Netbeans.
When the user select a leaf, it will display for him the required forum.
What I am facing right now that when selecting the other leaves, it is display for me all forums.
Here is my codes
private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)
jTree1.getLastSelectedPathComponent();
if (node == null) return;
Object nodeInfo = node.getUserObject();
jTree1.getSelectionModel().setSelectionMode
(TreeSelectionModel.SINGLE_TREE_SELECTION);
JTree tree = new JTree();
Employee emp = new Employee();
rectutment rec = new rectutment();
interview inter = new interview();
DefaultMutableTreeNode firstLeaf = ((DefaultMutableTreeNode)tree.getModel().getRoot()).getFirstLeaf();
tree.setSelectionPath(new TreePath(firstLeaf.getPath()));
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
root.add(firstLeaf);
firstLeaf.add(new DefaultMutableTreeNode("firstleaf"));
model.reload();
emp.add(tree);
emp.pack();
emp.setVisible(true);
if ( emp.isActive()&& rec.isActive()){
emp.dispose();
}
else{
rec.dispose();
}
rec.setDefaultCloseOperation(emp.EXIT_ON_CLOSE);
rec.setLocationRelativeTo(emp);
rec.add(tree);
rec.pack();
rec.setVisible(true);
}
Any ideas?

How do I get all TextFields from a pane with foreach-loop?

Is it possible in JavaFx to iterate through all Textfield in a pane and set the settings for all of them at once? The below dosn't work but I imagine something like this:
for(TextField tf : gridpane.getChildrens){
txf.setEditable(false);
txf_.setBlendMode(BlendMode.DARKEN);
}
Given this
Pane pane = new Pane();
TextField textField1 = new TextField();
TextField textField2 = new TextField();
pane.getChildren().addAll(textField1, textField2);
you can get the textfields like this:
for( Node node: pane.getChildren()) {
if( node instanceof TextField) {
System.out.println( node);
}
}
and an alternative would be to lookup the css class:
Set<Node> nodes = pane.lookupAll(".text-field");
for( Node node: nodes) {
System.out.println( node);
}

Display selected Item in JComboBox when item is clicked

I currently have 2 JComboBoxes. When an item in the first JComboBox is selected, relevant items are displayed in JComboBox2. However when I try to select the items in the second JComboBox it keeps returning to default. However it is registering the value of the item that is selected, just not displaying the selected item in the JComboBox.
Here is a snippet of my code:
mainComboBox = new JComboBox( treeItems);
mainComboBox.addActionListener( this );
getContentPane().add( mainComboBox, BorderLayout.WEST );
// Create sub combo box with multiple models
subComboBox = new JComboBox();
subComboBox.addActionListener(this);
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
getContentPane().add( subComboBox, BorderLayout.EAST );
String [] chromalveolataItems = chromalveolataTreeSet.toArray(new String[chromalveolataTreeSet.size()]);
subItems.put(treeItems[1], chromalveolataItems);
String [] mycetozoaItems = mycetozoaTreeSet.toArray(new String[mycetozoaTreeSet.size()]);
subItems.put(treeItems[2], mycetozoaItems);
String [] metazoaItems = metazoaTreeSet.toArray(new String[metazoaTreeSet.size()]);
subItems.put(treeItems[3], metazoaItems);
String [] viridiplantaeItems = viridiplantaeTreeSet.toArray(new String[viridiplantaeTreeSet.size()]);
subItems.put(treeItems[4], viridiplantaeItems);
String [] virusesItems = virusesTreeSet.toArray(new String[virusesTreeSet.size()]);
subItems.put(treeItems[5], virusesItems);
.
#Override
public void actionPerformed(ActionEvent e)
{
String item = (String)mainComboBox.getSelectedItem();
Object o = subItems.get( item );
String organismComboItem = (String)subComboBox.getSelectedItem();
if(treeArray.contains(organismComboItem)){
//System.out.println(treeArray.indexOf(organismComboItem));
String selectedId = idArray.get(treeArray.indexOf(organismComboItem));
System.out.println(selectedId);
}
if (o == null)
{
subComboBox.setModel( new DefaultComboBoxModel() );
}
else
{
subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
}
}
There is probably a relatively simple solution to this however I am new to Java so please forgive me.
Any help whatsoever would be much appreciated! :)
Looks to me like you based your code on the example found in this posting: Binding comboboxes in swing (or one like it).
When you use examples don't add extra code.
subComboBox.addActionListener(this);
The example does not do this. By adding the same listener to the subComboBox you are telling it to reset itself every time you select an item from it. Only the mainComboBox needs the ActionListener.

SWT Application: Are Draggable Tabs Possible?

I am building a Java application using SWT. One of the requirements of the application is that it have multiple windows. Rather than having "forever independent" windows, I thought it would be cool to implement a feature like in most browsers where you have a single, tabular window, where each tab can be dragged out to create a separate window. After a little research using the Google, it seems possible to accomplish this using JavaFX, but is it possible (and relatively easy) to achieve the same functionality in SWT? Thanks in advance.
While my take might be a little late, here it is nonetheless. Below snippet is a rough POC that allows to drag an item from the CTabFolder and when the item is dropped outside of the bounds of the folder, a shell is opened to show items' content.
public static void main( String[] args ) {
Display display = new Display();
final Shell shell = new Shell( display );
shell.setLayout( new FillLayout() );
final CTabFolder folder = new CTabFolder( shell, SWT.BORDER );
for( int i = 0; i < 4; i++ ) {
CTabItem item = new CTabItem( folder, SWT.CLOSE );
item.setText( "Item " + i );
Text text = new Text( folder, SWT.MULTI );
text.setText( "Content for Item " + i );
item.setControl( text );
}
Listener dragListener = new Listener() {
private CTabItem dragItem;
public void handleEvent( Event event ) {
Point mouseLocation = new Point( event.x, event.y );
switch( event.type ) {
case SWT.DragDetect: {
CTabItem item = folder.getItem( mouseLocation );
if( dragItem == null && item != null ) {
dragItem = item;
folder.setCapture( true );
}
break;
}
case SWT.MouseUp: {
if( dragItem != null && !folder.getBounds().contains( mouseLocation ) ) {
popOut( dragItem, folder.toDisplay( mouseLocation ) );
dragItem.dispose();
dragItem = null;
}
break;
}
}
}
};
folder.addListener( SWT.DragDetect, dragListener );
folder.addListener( SWT.MouseUp, dragListener );
shell.pack();
shell.open();
while( !shell.isDisposed() ) {
if( !display.readAndDispatch() )
display.sleep();
}
display.dispose();
}
private static void popOut( CTabItem tabItem, Point location ) {
Control control = tabItem.getControl();
tabItem.setControl( null );
Shell itemShell = new Shell( tabItem.getParent().getShell(), SWT.DIALOG_TRIM | SWT.RESIZE );
itemShell.setLayout( new FillLayout() );
control.setParent( itemShell );
control.setVisible( true ); // control is hidden by tabItem.setControl( null ), make visible again
itemShell.pack();
itemShell.setLocation( location );
itemShell.open();
}
While this example uses a CTabFolder it should also be possible to use the (native) TabFolder instead.
What is certainly missing is visual feedback while dragging an item and a means to abort a drag operation (e.g. Esc key), and probably some more things...

How do I change the "root" directories name in JTree?

I have a simple implementation of JTree:
tree1 = new JTree(LibObj.collectionToStringArray(LibObj.books));
tree1.setRootVisible(true);
scrollPane2 = new JScrollPane(tree1);
scrollPane2.setPreferredSize(new Dimension(350, 300));
panel.add(scrollPane2);
LibObj.collectionToStringArray(LibObj.books) is a method in another class that takes a collection and turns it into an array of strings
Everything is displaying as expected but the root directory is named "Root". How do I change the name? (I want it to be called Books)
Using the constructor JTree(TreeNode node) would give you the chance to create your own root node.
Just like this:
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root node name");
for( String book : booksArray ) {
DefaultMutableTreeNode bookNode = new DefaultMutableTreeNode(book);
rootNode.add(bookNode);
}
tree1 = new JTree(rootNode);
tree1.setRootVisible(true);
[...]

Categories

Resources