This is probably a simple question, I'm not very used to Java programming. But I need to create a dialog with a CheckboxTree (a variant of JTree with checkboxes, see http://www.javaworld.com/javaworld/jw-09-2007/jw-09-checkboxtree.html)
Please note: I have created the JDialog in the graphical environment of NetBeans, so it has generated code for adding buttons etc. So I need to know how to add this tree after the creation of the main parts, so to speak... Maybe that's the problem, because if I do something like this:
JPanel panel = new JPanel();
this.setContentPane(panel);
Then I actually see the tree showing up in the dialog, but all the buttons and all are gone...
I have been able to add it to a JFrame and an optionspane, but I want it in a custom JDialog. Could anyone please explain to me in very simple terms what I need to do?
Here are my feeble attempts so far:
Constructor for the JDialog:
public MetadataUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
Container panel = getContentPane();
panel.add(getTree());
panel.repaint();
this.pack();
}
getTree method that creates the checkboxtree:
private static CheckboxTree getTree() {
DefaultMutableTreeNode root, child;
root = new DefaultMutableTreeNode("root");
child = new DefaultMutableTreeNode("Colors");
root.add(child);
child.add(new DefaultMutableTreeNode("Cyan"));
child.add(new DefaultMutableTreeNode("Magenta"));
child.add(new DefaultMutableTreeNode("Yellow"));
child.add(new DefaultMutableTreeNode("Black"));
CheckboxTree checkboxTree = new CheckboxTree(root);
checkboxTree.setVisible(true);
return checkboxTree;
}
This repainting and all that is the last attempt based on something I found Googling, but it made no difference whatsoever, so I'm guessing I'm way off.
The simplest way to add the tree and make it visible would be appreciated. It seems to work exactly as a JTree with regards to adding it, but I cannot make it work. So even if no one has experience with this particular checkboxtree plugin, the same (simplest) code for using a JTree in a JDialog would probably do!
EDIT:
In response to Andrew, here is the same thing (my best attempt) with a regular JTree:
private static JTree getTree() {
DefaultMutableTreeNode root, child;
root = new DefaultMutableTreeNode("root");
child = new DefaultMutableTreeNode("Colors");
root.add(child);
child.add(new DefaultMutableTreeNode("Cyan"));
child.add(new DefaultMutableTreeNode("Magenta"));
child.add(new DefaultMutableTreeNode("Yellow"));
child.add(new DefaultMutableTreeNode("Black"));
JTree tree = new JTree(root);
tree.setVisible(true);
return tree;
}
EDIT 2:
In response to Maxim, I'm confused. Things that are obvious to you are probably lost on me. Borrowing some stuff from your code this is the best I could come up with (doesn't work):
public MetadataUI(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
JScrollPane s = new JScrollPane();
s.getViewport().add(getTree());
getContentPane().add(s, BorderLayout.CENTER);
setVisible(true);
}
If you indeed created your JDialog with Netbeans GUI (it's a JDialog form) and the component you are trying to integrate into what you already have provides a zero argument constructor, try the following:
open your existing JDialog in Design mode
In the Navigator view right-click [JDialog] or whatever your top-level node is (should be a sibling of "Other Components") and select Add From Palette > Beans > Choose Bean
enter a fully qualified name for the class which represents your JTree component (ex. com.example.jtree.SomeJTreeComponent) and confirm. If the component is trully a JTree it will probably get added without any problems.
(optional) At this point the tree may or may not be enclosed within a JScrollPane. If it is not, you can manually achieve this by repeating parts of step 2. on your newly added component and choosing Enclose in this time around.
You will need to program other stuff by hand. I suggest you read a JTree Tutorial or refer to the documentation of your 3rd party component to help you through it.
You might also want to read more about the tool you are using to build your GUI.
Related
I have visualized relationships in my program with JGraphT's JGraphXAdapter.
Unfortunately, I need to allow user only visual modifications of the graph, i.e. moving/resizing nodes. But he still can edit something, despite the fact I disabled everything I found:
setLayout(new BorderLayout());
add(
new mxGraphComponent(
jgxAdapter = new JGraphXAdapter<Corpus, CorporaDirectory.CorporaGraphEdge>(
CorporaDirectory.getInstance().getCorporaGraphModel()
) {{
setCellsDeletable(false);
setCellsCloneable(false);
setCellsEditable(false);
setCellsDisconnectable(false);
setConnectableEdges(false);
setVertexLabelsMovable(false);
setSplitEnabled(false);
}}
)
);
specifically user still can add new edges:
UDPATE
If I set setEnablled(false) to mxGraphComponent then I get totally frozen graph.
Try using mxGraphComponent.setConnectable(false), it should disable connection handler in the graph component.
I am trying to create a JPanel to display when a user clicks a button within my main JFrame. In Netbeans I first used the wizard to add a new JPanel to my project, I then used the GUI creator to fill in all the content. I am not trying to display the JPanel with the following code
private void m_jbShowSelAccResultsActionPerformed(java.awt.event.ActionEvent evt)
{
Account selAcc = getSelectedAccount();
if(selAcc != null)
{
AccountView accPanel = new AccountView(Account.getDeepCopy(selAcc));
accPanel.setVisible(true);
}
else
ShowMessage("Please select an account to view");
}
But nothing happens, no error is thrown and the JPanel is not shown. So I then changed the JPanel to a JFrame (Netbeans didn't complain). When I try again with the same code I receive the error GroupLayout can only be used with one Container at a time.
How can I display my JPanel/JFrame?
To change views within a Swing GUI, use a CardLayout as this is a much more robust and reliable way to do this.
Don't try to blindly "change a JPanel to a JFrame". It looks like you're just guessing here.
GroupLayout can't be reused as the error message is telling you. Likely this error comes from the point above. If you avoid trying to make a JFrame out of a JPanel, the error message will likely go away. As an aside, GroupLayout is not easily used manually, especially if you're trying to add components to an already rendered GUI.
So for instance, if your program had a JPanel say called cardHolderPanel, that used a CardLayout, this held by a variable say called cardLayout, and you've already added a "card" JPanel to this holder for accounts, say called accPanel, and if the accPanel had a method to set its currently displayed account, say setAccount(Accoint a), you could easily swap views by calling the CardLayout show(...) method, something like:
private void m_jbShowSelAccResultsActionPerformed(java.awt.event.ActionEvent evt) {
Account selAcc = getSelectedAccount();
if(selAcc != null) {
accPanel.setAccount(Account.getDeepCopy(selAcc));
cardLayout.show(cardHolderPanel, "Account View");
}
else {
showErrorMessage("Please select an account to view");
}
}
I am Creating JLayeredPane (mainFrame) and add stuff to it like this:
JPanel textP= new Scribe(text); //this returns panel with xome text
textP.setVisible(true);
mainFrame.add(shakespeare, new Integer(6));/*This is important!!!*/
mainFrame.repaint();
mainFrame.validate();
Later I am trying to remove it like this
mainFrame.remove(6);
and it throws No such child: 6.
Other elements drawing images work fine:
JPanel imageP = new ImagePanel(image);
imageP.setVisible(true);
mainFrame.add(imageP, new Integer(5));
mainFrame.repaint();
mainFrame.validate();
//after a while
mainFrame.remove(5);
These panels are placed and removed from the pane with different order and timings defined by user input.
remove(int) removes the n'th component from the container, it doesn't relate to the layer the component was added to
The best thing is to try a remove the component by its reference, as it's not always possible to know that anything was added/inserted before your component since you added it
Currently I have a very basic file viewer working as follows :
- in JOptionPane I browse for files, and set some variables to display (colors, line connecting etc)
- previous windows loads a frame with drawn points
alt text http://img190.imageshack.us/img190/4443/104bu.jpg
Code :
http://paste.pocoo.org/show/220066/
Now I'd like to throw it into one window, with JMenu for selecting files and changing display parameters. How to get started ? Should I rewrite everything to JDialog ?
alt text http://img684.imageshack.us/img684/5264/lab10db.jpg
If you want the JOPtionPane as a child of the main JFrame, then add it as a child. Of course it will then cover your dots. Hence you will have to not draw your dots directly in the content pane of the main JFrame, but rather in a new JPanel that you have also added to the JFRame's content pane. Let me know if I've understood the question whatsoever.
Here's some code for how I see the setup (I'm leaving the layout problem out of this, partly because it depends on what you want to see):
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(new Dimension(400,400));
frame.getContentPane().add(new JOptionPane());
JPanel canvasForDots = new JPanel();
frame.getContentPane().add(canvasForDots);
You might also like to look at How to Use Tool Bars and How to Use Menus. ImageApp is a typical implementation that associates menu items with the corresponding Action instances.
private class ClearAction extends AbstractAction {…}
private class ImageOpenAction extends AbstractAction {}
private Action openAction = new ImageOpenAction("Open");
private Action clearAction = new ClearAction("Clear");
…
JMenu menu = new JMenu("File");
menu.add(new JMenuItem(openAction));
menu.add(new JMenuItem(clearAction));
This related example adds the file chooser directly to the main frame. Here's a more elaborate example of connecting lines and shapes using the same principles.
I create a JTree and model for it out in a class separate to the GUI class. The data for the JTree is extracted from a file.
Now in the GUI class the user can add files from the file system to an AWT list. After the user clicks on a file in the list I want the JTree to update. The variable name for the JTree is schemaTree.
I have the following code for the when an item in the list is selected:
private void schemaListItemStateChanged(java.awt.event.ItemEvent evt) {
int selection = schemaList.getSelectedIndex();
File selectedFile = schemas.get(selection);
long fileSize = selectedFile.length();
fileInfoLabel.setText("Size: " + fileSize + " bytes");
schemaParser = new XSDParser(selectedFile.getAbsolutePath());
TreeModel model = schemaParser.generateTreeModel();
schemaTree.setModel(model);
}
I've updated the code to correspond to the accepted answer. The JTree now updates correctly based on which file I select in the list.
From the Component.add API docs.
Note: If a component has been added to
a container that has been displayed,
validate must be called on that
container to display the new
component. If multiple components are
being added, you can improve
efficiency by calling validate only
once, after all the components have
been added.
You have called repaint and validate on a component that is not displayed, which will not be effective. You need to call those methods on the mainPanel after the add. Also revalidate tends to be better than validate as it effectively coalesces.
I not sure that I'm understanding your question, but I'll try...
The right thing to do should be, IMHO:
get the file
create a new TreeModel from your file
give the model to the JTree
In pseudocode, it would look like that:
File newContent = getSelectedByUser(...);
TreeModel newModel = new MyFileBasedTreeModel(newContent);
//this next part must be done in the EventDispatcherThread
myTree.setModel(newModel);
then the JTree would be updated, without any call to repaint, etc.
Hope it helps