pronane
asked on
Jtrees in java ( click on a node and appear in the centre jpanel)
I am trying to create a GUI that has on the left pane a Jtree and on the right ( or centre ) of the GUI depending on what node in the tree has been clicked a jpanel with textfields, textareas etc will appear for example
lets say i have a jtree root called
+Test
- Thread creation
and within the node Thread creation there is a Jtextfield where i can enter the amount of threads I want to create. Could someone please give me some sample code, as I can only get it to work that if i click a node some text can appear in a text pane in the centre, how can i do this that i can change the configuration of the thread creation node so that if i click on another node the entered details will be there e.g sample code to test.
Thanks again,
Paul
lets say i have a jtree root called
+Test
- Thread creation
and within the node Thread creation there is a Jtextfield where i can enter the amount of threads I want to create. Could someone please give me some sample code, as I can only get it to work that if i click a node some text can appear in a text pane in the centre, how can i do this that i can change the configuration of the thread creation node so that if i click on another node the entered details will be there e.g sample code to test.
Thanks again,
Paul
Do you mean that you need a Windows-Explorer-like widget where a tree on the left panel and table or other kinds of GUI on the right hand to allow user to enter in data to fields such as JTextArea, etc.
ASKER
No like in internet explorer where frames on the left and if you click on one of the links in the frame a page will come up on the right. But in my case I would like to go further I can get this to work in the case of lets say on the left I have a node in a JTree that says FAQ:Help and if i click that node on the right in the centre of the gui app, a jeditropane will come up with a page on FAqhelp or whatever. What i want to do however is a new panel to appear so taht i can add certain values into that. If you have used Jmeter version 1.8 by apache, that is a good example, on the left they have a Jtree and depending on what node you click on a Jpanel ( for exapmle ) will appear on the right that could have a jtextfield, a list, a drop down box and that if I select particular values that they will be stored so that if i click on another node and go back to taht node later the same values will still be entered.
Thanks for your explanation. I did the similar task before which requires to display different kinds of GUI layout (including Panel, ScrollPane etc.) on the right depending on user selections on the left JTree panel.
Here is what you need to do (but not limited):
0) Create a SplitPane and assign the tree to reside on the left and an empty JScrollPane or JPanel on the right as temporary place holder
1) Create GUI widget contained in JPanel or JScrollPane for each tree node command that you have. For example, one for FAQ:Help and the other for Login. You might not dynamically allocate GUI widgets, such as JTextPane, etc., on the fly easily, so at least for simplicity on the first cut, you could just create two different such panels with GUI layout.
2) Create a Tree selection listener that implements javax.swing.event.TreeSele ctionListe ner and register it to your JTree. Let's called it MyTreeSelectionListener.
3) In this class, you create a map that you could use tree node's face value (if they are unique, otherwise, use tree node itself or some combination of paths) as the key and the GUI widget that you will display on the right as the value. When a node is clicked, your listener from 2) will be notified. Within it, you could know what tree node is clicked, which helps you lookup the map if a corresponding panel exists. If not, you could initialize one and put into the map; otherwise, you could grab that panel and put it onto the right side of the splitpane created in 0).
4) Since you use map to memorize the previous screen visited, also it will use the same instance to display on the right side of splitpane, you would see the previously entered value if switch the focus of the tree node back and forth, which I assume is what you expect.
Here is what you need to do (but not limited):
0) Create a SplitPane and assign the tree to reside on the left and an empty JScrollPane or JPanel on the right as temporary place holder
1) Create GUI widget contained in JPanel or JScrollPane for each tree node command that you have. For example, one for FAQ:Help and the other for Login. You might not dynamically allocate GUI widgets, such as JTextPane, etc., on the fly easily, so at least for simplicity on the first cut, you could just create two different such panels with GUI layout.
2) Create a Tree selection listener that implements javax.swing.event.TreeSele
3) In this class, you create a map that you could use tree node's face value (if they are unique, otherwise, use tree node itself or some combination of paths) as the key and the GUI widget that you will display on the right as the value. When a node is clicked, your listener from 2) will be notified. Within it, you could know what tree node is clicked, which helps you lookup the map if a corresponding panel exists. If not, you could initialize one and put into the map; otherwise, you could grab that panel and put it onto the right side of the splitpane created in 0).
4) Since you use map to memorize the previous screen visited, also it will use the same instance to display on the right side of splitpane, you would see the previously entered value if switch the focus of the tree node back and forth, which I assume is what you expect.
ASKER
Ya I get that here is what i did so far.
Ok here is my code:
class Test
{
public Test()
{
TreeSelectionListener listener =
new TreeSelectionListener();
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tree);
// Display it all in a window and make the window appear
contentPane.add(scrollpane , BorderLayout.WEST);
}
public void valueChanged (TreeSelectionEvent event) {
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " +
path.getLastPathComponent( ));
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t oString()+ "\n");
updateWithObject(elements[ i]);
}
System.out.println ();
}
}
Right in this example I just have it printing to the console when a particular node i selected. What I want to do however is when a node is selected a panel not an editorpane like a jpanel ( as an example with as I said earlier ) appears in ( contentpane.add(jpanel, BorderLayout.CENTER); ) the center. Have you any code that I can test to see this working with what u were saying?
Thanks
Ok here is my code:
class Test
{
public Test()
{
TreeSelectionListener listener =
new TreeSelectionListener();
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tree);
// Display it all in a window and make the window appear
contentPane.add(scrollpane
}
public void valueChanged (TreeSelectionEvent event) {
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " +
path.getLastPathComponent(
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t
updateWithObject(elements[
}
System.out.println ();
}
}
Right in this example I just have it printing to the console when a particular node i selected. What I want to do however is when a node is selected a panel not an editorpane like a jpanel ( as an example with as I said earlier ) appears in ( contentpane.add(jpanel, BorderLayout.CENTER); ) the center. Have you any code that I can test to see this working with what u were saying?
Thanks
Let's say that you have your own frame class called TestFrame, in which you have created a JSplitPane private member variable, named mySplitPane, and put it at the center of the TestFrame's contentPane. In this frame class, you create a function, maybe, called setRightPanel(Container newContainer) (note, JPanel, JScrollPane, etc. are descendents of Container, so by using this way, you make your function generically able to take any component you'd like to put onto the right side of the splitpane but at least it should be a container) something like following,
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon ent(newCon tainer);
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
In your TreeSelectionListener class (I highly recommend using different name since this is used by java and in further conversation it might be very confusing to which one being refered), say TestTreeSelectionListener' s constructor, you could take in a TestFrame parameter and suppose you have defined a member variable called myParentFrame, as following,
private TestFrame myParentFrame;
public TreeSelectionListener(Test Frame parentFrame)
{
this.myParentFrame = parentFrame;
}
Then suppose you already defined a Map member instance in the TestTreeSelectionListener class, something like this
private Map myScreenMap = new HashMap();
Then in your valueChanged (TreeSelectionEvent event) function, and after the line with "path.getLastPathComponent ());", you do following,
String command = String.valueOf(path.getLas tPathCompo nent()));
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("FAQ:Help".equals(comma nd))
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands ".equals(c ommand))
{
...
}
...
myScreenMap.put(command, container);
}
myParentFrame.setRightPane l(containe r);
...
}
Please keep in mind that in order to achieve further functionality, you should have bunch of classes that are JPanel or JScrollPanel's descendent to represent each of your screen. Also, you need couple of class to take charge of Tree Selection event and update the GUI content, acting like a controller.
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
In your TreeSelectionListener class (I highly recommend using different name since this is used by java and in further conversation it might be very confusing to which one being refered), say TestTreeSelectionListener'
private TestFrame myParentFrame;
public TreeSelectionListener(Test
{
this.myParentFrame = parentFrame;
}
Then suppose you already defined a Map member instance in the TestTreeSelectionListener class, something like this
private Map myScreenMap = new HashMap();
Then in your valueChanged (TreeSelectionEvent event) function, and after the line with "path.getLastPathComponent
String command = String.valueOf(path.getLas
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("FAQ:Help".equals(comma
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands
{
...
}
...
myScreenMap.put(command, container);
}
myParentFrame.setRightPane
...
}
Please keep in mind that in order to achieve further functionality, you should have bunch of classes that are JPanel or JScrollPanel's descendent to represent each of your screen. Also, you need couple of class to take charge of Tree Selection event and update the GUI content, acting like a controller.
ASKER
Thanks a lot for the help will close this soon enough I just want to make sure I have it working properly I will award the points as soon as I have it working! Thanks for the code
ASKER
Thanks a lot for the help will close this soon enough I just want to make sure I have it working properly I will award the points as soon as I have it working! Thanks for the code
ASKER
Ok I implemented your code just like you said, one thing I meant ask earlier why do I need to add a JSplitpane i just want to add a panel to the centre, I tested the code so that if an item was clicked when it called:
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
that within the MyFAQHelpPanel
i just had
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{
System.out.println("hello world");
}
}
This worked once, i.e if i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.
Then I tried to do the following:
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
}
}
And nothing would appear in the centre of the Frame. Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????
Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuI tem;
import javax.swing.JRadioButtonMe nuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;
import java.util.*;
/*
http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
https://www.experts-exchange.com/questions/20537023/JTree-problem.html
* This class exists solely to show you what menus look like.
* It has no menu-related event handling.
*/
public class Test extends JFrame {
JTextArea output;
JScrollPane scrollPane;
Container contentPane;
JMenuItem setLookAndfeel;
String laf;
JSplitPane mySplitPane;
public Test(String lookAndFeel) {
laf = "com.sun.java.swing.plaf.w indows.Win dowsLookAn dFeel";
String look = lookAndFeel;
String feel = "Windows";
String motif = "Motif";
look = look.trim().toLowerCase();
feel = feel.trim().toLowerCase();
motif = motif.trim().toLowerCase() ;
try
{
if(look.equals(feel))
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.window s.WindowsL ookAndFeel ");
else if(look.equals(motif))
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.motif. MotifLookA ndFeel");
else if (look.equals("Metal"))
{
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.metal. MetalLookA ndFeel");
}
else
{
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.gtk.GT KLookAndFe el");
}
}catch(Exception e){}
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JCheckBoxMenuItem cbMenuItem;
JRadioButtonMenuItem rbMenuItem;
JButton b1, b2, b3;
JPanel buttonPanel;
JViewport port;
Rectangle viewPortR;
Dimension pa;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Add regular components to the window, using the default BorderLayout.
contentPane = getContentPane();
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
JPanel panel = new JPanel();
ImageIcon firstButtonIcon = new ImageIcon("start.gif");
ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
b1 = new JButton(firstButtonIcon);
b1.setVerticalTextPosition (AbstractB utton.BOTT OM);
b1.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b1.setMnemonic(KeyEvent.VK _M);
b2 = new JButton(middleButtonIcon);
b2.setVerticalTextPosition (AbstractB utton.BOTT OM);
b2.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b2.setMnemonic(KeyEvent.VK _L);
b3 = new JButton( "Last BUtton: ");
b3.setVerticalTextPosition (AbstractB utton.BOTT OM);
b3.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b3.setMnemonic(KeyEvent.VK _J);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT ));
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
contentPane.add(buttonPane l, BorderLayout.NORTH);
JTree tree = new JTree();
//tree.setModel();
//tree.addTreeSelectionLis tener(this );
DefaultMutableTreeNode component =
new DefaultMutableTreeNode("Co mponent");
DefaultMutableTreeNode container =
new DefaultMutableTreeNode("Co ntainer");
DefaultMutableTreeNode box =
new DefaultMutableTreeNode("Bo x");
DefaultMutableTreeNode jComponent =
new DefaultMutableTreeNode("JC omponent") ;
DefaultMutableTreeNode abstractButton =
new DefaultMutableTreeNode("Ab stractButt on");
DefaultMutableTreeNode jButton =
new DefaultMutableTreeNode("JB utton");
DefaultMutableTreeNode jMenuItem =
new DefaultMutableTreeNode("JM enuItem");
DefaultMutableTreeNode jToggle =
new DefaultMutableTreeNode("JT oggleButto n");
DefaultMutableTreeNode jLabel =
new DefaultMutableTreeNode("JL abel");
DefaultMutableTreeNode etc =
new DefaultMutableTreeNode(".. .");
// Group the nodes
component.add(container);
container.add(box);
container.add(jComponent);
jComponent.add(abstractBut ton);
abstractButton.add(jButton );
abstractButton.add(jMenuIt em);
abstractButton.add(jToggle );
jComponent.add(jLabel);
jComponent.add(etc);
TreeSelectionListener listener =
new MyTreeSelectionListener(th is);
TreePanel tp = new TreePanel(component, listener);
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tp);
/*port = scrollpane.getViewport();
viewPortR = port.getViewRect();
int y = port.getViewSize().height;
int x = port.getViewSize().width;
Point p = new Point(10, 20);
port.setViewPosition(p);
*/
// Display it all in a window and make the window appear
mySplitPane = new JSplitPane();
contentPane.add(mySplitPan e, BorderLayout.CENTER);
contentPane.add(scrollpane , BorderLayout.WEST);
//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent. VK_A);
menu.getAccessibleContext( ).setAcces sibleDescr iption(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(Key Event.VK_T ); //used constructor instead
menuItem.setAccelerator(Ke yStroke.ge tKeyStroke (
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleCont ext().setA ccessibleD escription (
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.g if"));
menuItem.setMnemonic(KeyEv ent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.g if"));
menuItem.setMnemonic(KeyEv ent.VK_D);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(tru e);
rbMenuItem.setMnemonic(Key Event.VK_R );
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Anot her one");
rbMenuItem.setMnemonic(Key Event.VK_O );
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(Key Event.VK_C );
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(Key Event.VK_H );
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEve nt.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(Ke yStroke.ge tKeyStroke (
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenu Run = new JMenu("Run");
menuBar.add(Run);
JMenu options = new JMenu("Option");
menuBar.add(options);
JMenu help = new JMenu("Help");
menuBar.add(help);
setLookAndfeel = new JMenuItem("Set Look and feel");
setLookAndfeel.addActionLi stener(new MenuListener());
options.add(setLookAndfeel );
}
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon ent(newCon tainer);
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
public static void main(String[] args) {
System.out.println("Please enter the look and feel you want: (Windows, Motif, Metal) ");
String lookAndFeel = Console.readString();
Test window = new Test(lookAndFeel);
window.setTitle("MenuLookD emo");
window.setSize(450, 260);
window.setVisible(true);
}
public class MenuListener implements ActionListener
{
JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.
public void actionPerformed(ActionEven t event)
{
Object source = event.getSource();
if(source == setLookAndfeel)
{
try
{
System.out.println("got here");
String laf = "Metal";
Test p = new Test(laf);
}catch(Exception e){}
}
}
}
class MyTreeSelectionListener implements TreeSelectionListener {
private Map myScreenMap = new HashMap();
private Test myParentFrame;
public MyTreeSelectionListener(Te st parentFrame)
{
this.myParentFrame = parentFrame;
}
public void valueChanged (TreeSelectionEvent event)
{
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " + path.getLastPathComponent( ));
String command = String.valueOf(path.getLas tPathCompo nent());
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands ".equals(c ommand))
{
}
myScreenMap.put(command, container);
}
myParentFrame.setRightPane l(containe r);
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t oString()+ "\n");
updateWithObject(elements[ i]);
}
System.out.println ();
}
}
public void updateWithObject(Object o)
{
}
}
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
}
}
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
that within the MyFAQHelpPanel
i just had
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{
System.out.println("hello world");
}
}
This worked once, i.e if i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.
Then I tried to do the following:
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
}
}
And nothing would appear in the centre of the Frame. Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????
Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuI
import javax.swing.JRadioButtonMe
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;
import java.util.*;
/*
http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
https://www.experts-exchange.com/questions/20537023/JTree-problem.html
* This class exists solely to show you what menus look like.
* It has no menu-related event handling.
*/
public class Test extends JFrame {
JTextArea output;
JScrollPane scrollPane;
Container contentPane;
JMenuItem setLookAndfeel;
String laf;
JSplitPane mySplitPane;
public Test(String lookAndFeel) {
laf = "com.sun.java.swing.plaf.w
String look = lookAndFeel;
String feel = "Windows";
String motif = "Motif";
look = look.trim().toLowerCase();
feel = feel.trim().toLowerCase();
motif = motif.trim().toLowerCase()
try
{
if(look.equals(feel))
UIManager.setLookAndFeel("
else if(look.equals(motif))
UIManager.setLookAndFeel("
else if (look.equals("Metal"))
{
UIManager.setLookAndFeel("
}
else
{
UIManager.setLookAndFeel("
}
}catch(Exception e){}
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JCheckBoxMenuItem cbMenuItem;
JRadioButtonMenuItem rbMenuItem;
JButton b1, b2, b3;
JPanel buttonPanel;
JViewport port;
Rectangle viewPortR;
Dimension pa;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Add regular components to the window, using the default BorderLayout.
contentPane = getContentPane();
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
JPanel panel = new JPanel();
ImageIcon firstButtonIcon = new ImageIcon("start.gif");
ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
b1 = new JButton(firstButtonIcon);
b1.setVerticalTextPosition
b1.setHorizontalTextPositi
b1.setMnemonic(KeyEvent.VK
b2 = new JButton(middleButtonIcon);
b2.setVerticalTextPosition
b2.setHorizontalTextPositi
b2.setMnemonic(KeyEvent.VK
b3 = new JButton( "Last BUtton: ");
b3.setVerticalTextPosition
b3.setHorizontalTextPositi
b3.setMnemonic(KeyEvent.VK
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
contentPane.add(buttonPane
JTree tree = new JTree();
//tree.setModel();
//tree.addTreeSelectionLis
DefaultMutableTreeNode component =
new DefaultMutableTreeNode("Co
DefaultMutableTreeNode container =
new DefaultMutableTreeNode("Co
DefaultMutableTreeNode box =
new DefaultMutableTreeNode("Bo
DefaultMutableTreeNode jComponent =
new DefaultMutableTreeNode("JC
DefaultMutableTreeNode abstractButton =
new DefaultMutableTreeNode("Ab
DefaultMutableTreeNode jButton =
new DefaultMutableTreeNode("JB
DefaultMutableTreeNode jMenuItem =
new DefaultMutableTreeNode("JM
DefaultMutableTreeNode jToggle =
new DefaultMutableTreeNode("JT
DefaultMutableTreeNode jLabel =
new DefaultMutableTreeNode("JL
DefaultMutableTreeNode etc =
new DefaultMutableTreeNode("..
// Group the nodes
component.add(container);
container.add(box);
container.add(jComponent);
jComponent.add(abstractBut
abstractButton.add(jButton
abstractButton.add(jMenuIt
abstractButton.add(jToggle
jComponent.add(jLabel);
jComponent.add(etc);
TreeSelectionListener listener =
new MyTreeSelectionListener(th
TreePanel tp = new TreePanel(component, listener);
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tp);
/*port = scrollpane.getViewport();
viewPortR = port.getViewRect();
int y = port.getViewSize().height;
int x = port.getViewSize().width;
Point p = new Point(10, 20);
port.setViewPosition(p);
*/
// Display it all in a window and make the window appear
mySplitPane = new JSplitPane();
contentPane.add(mySplitPan
contentPane.add(scrollpane
//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.
menu.getAccessibleContext(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(Key
menuItem.setAccelerator(Ke
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleCont
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.g
menuItem.setMnemonic(KeyEv
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.g
menuItem.setMnemonic(KeyEv
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(tru
rbMenuItem.setMnemonic(Key
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Anot
rbMenuItem.setMnemonic(Key
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(Key
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another
cbMenuItem.setMnemonic(Key
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEve
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(Ke
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenu Run = new JMenu("Run");
menuBar.add(Run);
JMenu options = new JMenu("Option");
menuBar.add(options);
JMenu help = new JMenu("Help");
menuBar.add(help);
setLookAndfeel = new JMenuItem("Set Look and feel");
setLookAndfeel.addActionLi
options.add(setLookAndfeel
}
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
public static void main(String[] args) {
System.out.println("Please
String lookAndFeel = Console.readString();
Test window = new Test(lookAndFeel);
window.setTitle("MenuLookD
window.setSize(450, 260);
window.setVisible(true);
}
public class MenuListener implements ActionListener
{
JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.
public void actionPerformed(ActionEven
{
Object source = event.getSource();
if(source == setLookAndfeel)
{
try
{
System.out.println("got here");
String laf = "Metal";
Test p = new Test(laf);
}catch(Exception e){}
}
}
}
class MyTreeSelectionListener implements TreeSelectionListener {
private Map myScreenMap = new HashMap();
private Test myParentFrame;
public MyTreeSelectionListener(Te
{
this.myParentFrame = parentFrame;
}
public void valueChanged (TreeSelectionEvent event)
{
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " + path.getLastPathComponent(
String command = String.valueOf(path.getLas
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands
{
}
myScreenMap.put(command, container);
}
myParentFrame.setRightPane
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t
updateWithObject(elements[
}
System.out.println ();
}
}
public void updateWithObject(Object o)
{
}
}
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
}
}
ASKER
Ok I implemented your code just like you said, one thing I meant ask earlier why do I need to add a JSplitpane i just want to add a panel to the centre, I tested the code so that if an item was clicked when it called:
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
that within the MyFAQHelpPanel
i just had
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{
System.out.println("hello world");
}
}
This worked once, i.e if i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.
Then I tried to do the following:
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
}
}
And nothing would appear in the centre of the Frame. Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????
Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuI tem;
import javax.swing.JRadioButtonMe nuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;
import java.util.*;
/*
http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
https://www.experts-exchange.com/questions/20537023/JTree-problem.html
* This class exists solely to show you what menus look like.
* It has no menu-related event handling.
*/
public class Test extends JFrame {
JTextArea output;
JScrollPane scrollPane;
Container contentPane;
JMenuItem setLookAndfeel;
String laf;
JSplitPane mySplitPane;
public Test(String lookAndFeel) {
laf = "com.sun.java.swing.plaf.w indows.Win dowsLookAn dFeel";
String look = lookAndFeel;
String feel = "Windows";
String motif = "Motif";
look = look.trim().toLowerCase();
feel = feel.trim().toLowerCase();
motif = motif.trim().toLowerCase() ;
try
{
if(look.equals(feel))
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.window s.WindowsL ookAndFeel ");
else if(look.equals(motif))
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.motif. MotifLookA ndFeel");
else if (look.equals("Metal"))
{
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.metal. MetalLookA ndFeel");
}
else
{
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.gtk.GT KLookAndFe el");
}
}catch(Exception e){}
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JCheckBoxMenuItem cbMenuItem;
JRadioButtonMenuItem rbMenuItem;
JButton b1, b2, b3;
JPanel buttonPanel;
JViewport port;
Rectangle viewPortR;
Dimension pa;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Add regular components to the window, using the default BorderLayout.
contentPane = getContentPane();
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
JPanel panel = new JPanel();
ImageIcon firstButtonIcon = new ImageIcon("start.gif");
ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
b1 = new JButton(firstButtonIcon);
b1.setVerticalTextPosition (AbstractB utton.BOTT OM);
b1.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b1.setMnemonic(KeyEvent.VK _M);
b2 = new JButton(middleButtonIcon);
b2.setVerticalTextPosition (AbstractB utton.BOTT OM);
b2.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b2.setMnemonic(KeyEvent.VK _L);
b3 = new JButton( "Last BUtton: ");
b3.setVerticalTextPosition (AbstractB utton.BOTT OM);
b3.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b3.setMnemonic(KeyEvent.VK _J);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT ));
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
contentPane.add(buttonPane l, BorderLayout.NORTH);
JTree tree = new JTree();
//tree.setModel();
//tree.addTreeSelectionLis tener(this );
DefaultMutableTreeNode component =
new DefaultMutableTreeNode("Co mponent");
DefaultMutableTreeNode container =
new DefaultMutableTreeNode("Co ntainer");
DefaultMutableTreeNode box =
new DefaultMutableTreeNode("Bo x");
DefaultMutableTreeNode jComponent =
new DefaultMutableTreeNode("JC omponent") ;
DefaultMutableTreeNode abstractButton =
new DefaultMutableTreeNode("Ab stractButt on");
DefaultMutableTreeNode jButton =
new DefaultMutableTreeNode("JB utton");
DefaultMutableTreeNode jMenuItem =
new DefaultMutableTreeNode("JM enuItem");
DefaultMutableTreeNode jToggle =
new DefaultMutableTreeNode("JT oggleButto n");
DefaultMutableTreeNode jLabel =
new DefaultMutableTreeNode("JL abel");
DefaultMutableTreeNode etc =
new DefaultMutableTreeNode(".. .");
// Group the nodes
component.add(container);
container.add(box);
container.add(jComponent);
jComponent.add(abstractBut ton);
abstractButton.add(jButton );
abstractButton.add(jMenuIt em);
abstractButton.add(jToggle );
jComponent.add(jLabel);
jComponent.add(etc);
TreeSelectionListener listener =
new MyTreeSelectionListener(th is);
TreePanel tp = new TreePanel(component, listener);
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tp);
/*port = scrollpane.getViewport();
viewPortR = port.getViewRect();
int y = port.getViewSize().height;
int x = port.getViewSize().width;
Point p = new Point(10, 20);
port.setViewPosition(p);
*/
// Display it all in a window and make the window appear
mySplitPane = new JSplitPane();
contentPane.add(mySplitPan e, BorderLayout.CENTER);
contentPane.add(scrollpane , BorderLayout.WEST);
//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent. VK_A);
menu.getAccessibleContext( ).setAcces sibleDescr iption(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(Key Event.VK_T ); //used constructor instead
menuItem.setAccelerator(Ke yStroke.ge tKeyStroke (
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleCont ext().setA ccessibleD escription (
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.g if"));
menuItem.setMnemonic(KeyEv ent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.g if"));
menuItem.setMnemonic(KeyEv ent.VK_D);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(tru e);
rbMenuItem.setMnemonic(Key Event.VK_R );
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Anot her one");
rbMenuItem.setMnemonic(Key Event.VK_O );
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(Key Event.VK_C );
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(Key Event.VK_H );
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEve nt.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(Ke yStroke.ge tKeyStroke (
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenu Run = new JMenu("Run");
menuBar.add(Run);
JMenu options = new JMenu("Option");
menuBar.add(options);
JMenu help = new JMenu("Help");
menuBar.add(help);
setLookAndfeel = new JMenuItem("Set Look and feel");
setLookAndfeel.addActionLi stener(new MenuListener());
options.add(setLookAndfeel );
}
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon ent(newCon tainer);
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
public static void main(String[] args) {
System.out.println("Please enter the look and feel you want: (Windows, Motif, Metal) ");
String lookAndFeel = Console.readString();
Test window = new Test(lookAndFeel);
window.setTitle("MenuLookD emo");
window.setSize(450, 260);
window.setVisible(true);
}
public class MenuListener implements ActionListener
{
JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.
public void actionPerformed(ActionEven t event)
{
Object source = event.getSource();
if(source == setLookAndfeel)
{
try
{
System.out.println("got here");
String laf = "Metal";
Test p = new Test(laf);
}catch(Exception e){}
}
}
}
class MyTreeSelectionListener implements TreeSelectionListener {
private Map myScreenMap = new HashMap();
private Test myParentFrame;
public MyTreeSelectionListener(Te st parentFrame)
{
this.myParentFrame = parentFrame;
}
public void valueChanged (TreeSelectionEvent event)
{
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " + path.getLastPathComponent( ));
String command = String.valueOf(path.getLas tPathCompo nent());
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands ".equals(c ommand))
{
}
myScreenMap.put(command, container);
}
myParentFrame.setRightPane l(containe r);
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t oString()+ "\n");
updateWithObject(elements[ i]);
}
System.out.println ();
}
}
public void updateWithObject(Object o)
{
}
}
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
}
}
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
that within the MyFAQHelpPanel
i just had
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{
System.out.println("hello world");
}
}
This worked once, i.e if i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.
Then I tried to do the following:
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
}
}
And nothing would appear in the centre of the Frame. Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????
Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuI
import javax.swing.JRadioButtonMe
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;
import java.util.*;
/*
http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
https://www.experts-exchange.com/questions/20537023/JTree-problem.html
* This class exists solely to show you what menus look like.
* It has no menu-related event handling.
*/
public class Test extends JFrame {
JTextArea output;
JScrollPane scrollPane;
Container contentPane;
JMenuItem setLookAndfeel;
String laf;
JSplitPane mySplitPane;
public Test(String lookAndFeel) {
laf = "com.sun.java.swing.plaf.w
String look = lookAndFeel;
String feel = "Windows";
String motif = "Motif";
look = look.trim().toLowerCase();
feel = feel.trim().toLowerCase();
motif = motif.trim().toLowerCase()
try
{
if(look.equals(feel))
UIManager.setLookAndFeel("
else if(look.equals(motif))
UIManager.setLookAndFeel("
else if (look.equals("Metal"))
{
UIManager.setLookAndFeel("
}
else
{
UIManager.setLookAndFeel("
}
}catch(Exception e){}
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JCheckBoxMenuItem cbMenuItem;
JRadioButtonMenuItem rbMenuItem;
JButton b1, b2, b3;
JPanel buttonPanel;
JViewport port;
Rectangle viewPortR;
Dimension pa;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Add regular components to the window, using the default BorderLayout.
contentPane = getContentPane();
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
JPanel panel = new JPanel();
ImageIcon firstButtonIcon = new ImageIcon("start.gif");
ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
b1 = new JButton(firstButtonIcon);
b1.setVerticalTextPosition
b1.setHorizontalTextPositi
b1.setMnemonic(KeyEvent.VK
b2 = new JButton(middleButtonIcon);
b2.setVerticalTextPosition
b2.setHorizontalTextPositi
b2.setMnemonic(KeyEvent.VK
b3 = new JButton( "Last BUtton: ");
b3.setVerticalTextPosition
b3.setHorizontalTextPositi
b3.setMnemonic(KeyEvent.VK
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
contentPane.add(buttonPane
JTree tree = new JTree();
//tree.setModel();
//tree.addTreeSelectionLis
DefaultMutableTreeNode component =
new DefaultMutableTreeNode("Co
DefaultMutableTreeNode container =
new DefaultMutableTreeNode("Co
DefaultMutableTreeNode box =
new DefaultMutableTreeNode("Bo
DefaultMutableTreeNode jComponent =
new DefaultMutableTreeNode("JC
DefaultMutableTreeNode abstractButton =
new DefaultMutableTreeNode("Ab
DefaultMutableTreeNode jButton =
new DefaultMutableTreeNode("JB
DefaultMutableTreeNode jMenuItem =
new DefaultMutableTreeNode("JM
DefaultMutableTreeNode jToggle =
new DefaultMutableTreeNode("JT
DefaultMutableTreeNode jLabel =
new DefaultMutableTreeNode("JL
DefaultMutableTreeNode etc =
new DefaultMutableTreeNode("..
// Group the nodes
component.add(container);
container.add(box);
container.add(jComponent);
jComponent.add(abstractBut
abstractButton.add(jButton
abstractButton.add(jMenuIt
abstractButton.add(jToggle
jComponent.add(jLabel);
jComponent.add(etc);
TreeSelectionListener listener =
new MyTreeSelectionListener(th
TreePanel tp = new TreePanel(component, listener);
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tp);
/*port = scrollpane.getViewport();
viewPortR = port.getViewRect();
int y = port.getViewSize().height;
int x = port.getViewSize().width;
Point p = new Point(10, 20);
port.setViewPosition(p);
*/
// Display it all in a window and make the window appear
mySplitPane = new JSplitPane();
contentPane.add(mySplitPan
contentPane.add(scrollpane
//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.
menu.getAccessibleContext(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(Key
menuItem.setAccelerator(Ke
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleCont
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.g
menuItem.setMnemonic(KeyEv
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.g
menuItem.setMnemonic(KeyEv
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(tru
rbMenuItem.setMnemonic(Key
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Anot
rbMenuItem.setMnemonic(Key
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(Key
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another
cbMenuItem.setMnemonic(Key
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEve
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(Ke
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenu Run = new JMenu("Run");
menuBar.add(Run);
JMenu options = new JMenu("Option");
menuBar.add(options);
JMenu help = new JMenu("Help");
menuBar.add(help);
setLookAndfeel = new JMenuItem("Set Look and feel");
setLookAndfeel.addActionLi
options.add(setLookAndfeel
}
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
public static void main(String[] args) {
System.out.println("Please
String lookAndFeel = Console.readString();
Test window = new Test(lookAndFeel);
window.setTitle("MenuLookD
window.setSize(450, 260);
window.setVisible(true);
}
public class MenuListener implements ActionListener
{
JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.
public void actionPerformed(ActionEven
{
Object source = event.getSource();
if(source == setLookAndfeel)
{
try
{
System.out.println("got here");
String laf = "Metal";
Test p = new Test(laf);
}catch(Exception e){}
}
}
}
class MyTreeSelectionListener implements TreeSelectionListener {
private Map myScreenMap = new HashMap();
private Test myParentFrame;
public MyTreeSelectionListener(Te
{
this.myParentFrame = parentFrame;
}
public void valueChanged (TreeSelectionEvent event)
{
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " + path.getLastPathComponent(
String command = String.valueOf(path.getLas
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands
{
}
myScreenMap.put(command, container);
}
myParentFrame.setRightPane
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t
updateWithObject(elements[
}
System.out.println ();
}
}
public void updateWithObject(Object o)
{
}
}
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
}
}
ASKER
Ok I implemented your code just like you said, one thing I meant ask earlier why do I need to add a JSplitpane i just want to add a panel to the centre, I tested the code so that if an item was clicked when it called:
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
that within the MyFAQHelpPanel
i just had
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{
System.out.println("hello world");
}
}
This worked once, i.e if i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.
Then I tried to do the following:
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
}
}
And nothing would appear in the centre of the Frame. Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????
Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuI tem;
import javax.swing.JRadioButtonMe nuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;
import java.util.*;
/*
http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
https://www.experts-exchange.com/questions/20537023/JTree-problem.html
* This class exists solely to show you what menus look like.
* It has no menu-related event handling.
*/
public class Test extends JFrame {
JTextArea output;
JScrollPane scrollPane;
Container contentPane;
JMenuItem setLookAndfeel;
String laf;
JSplitPane mySplitPane;
public Test(String lookAndFeel) {
laf = "com.sun.java.swing.plaf.w indows.Win dowsLookAn dFeel";
String look = lookAndFeel;
String feel = "Windows";
String motif = "Motif";
look = look.trim().toLowerCase();
feel = feel.trim().toLowerCase();
motif = motif.trim().toLowerCase() ;
try
{
if(look.equals(feel))
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.window s.WindowsL ookAndFeel ");
else if(look.equals(motif))
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.motif. MotifLookA ndFeel");
else if (look.equals("Metal"))
{
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.metal. MetalLookA ndFeel");
}
else
{
UIManager.setLookAndFeel(" com.sun.ja va.swing.p laf.gtk.GT KLookAndFe el");
}
}catch(Exception e){}
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JCheckBoxMenuItem cbMenuItem;
JRadioButtonMenuItem rbMenuItem;
JButton b1, b2, b3;
JPanel buttonPanel;
JViewport port;
Rectangle viewPortR;
Dimension pa;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Add regular components to the window, using the default BorderLayout.
contentPane = getContentPane();
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
JPanel panel = new JPanel();
ImageIcon firstButtonIcon = new ImageIcon("start.gif");
ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
b1 = new JButton(firstButtonIcon);
b1.setVerticalTextPosition (AbstractB utton.BOTT OM);
b1.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b1.setMnemonic(KeyEvent.VK _M);
b2 = new JButton(middleButtonIcon);
b2.setVerticalTextPosition (AbstractB utton.BOTT OM);
b2.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b2.setMnemonic(KeyEvent.VK _L);
b3 = new JButton( "Last BUtton: ");
b3.setVerticalTextPosition (AbstractB utton.BOTT OM);
b3.setHorizontalTextPositi on(Abstrac tButton.CE NTER);
b3.setMnemonic(KeyEvent.VK _J);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT ));
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
contentPane.add(buttonPane l, BorderLayout.NORTH);
JTree tree = new JTree();
//tree.setModel();
//tree.addTreeSelectionLis tener(this );
DefaultMutableTreeNode component =
new DefaultMutableTreeNode("Co mponent");
DefaultMutableTreeNode container =
new DefaultMutableTreeNode("Co ntainer");
DefaultMutableTreeNode box =
new DefaultMutableTreeNode("Bo x");
DefaultMutableTreeNode jComponent =
new DefaultMutableTreeNode("JC omponent") ;
DefaultMutableTreeNode abstractButton =
new DefaultMutableTreeNode("Ab stractButt on");
DefaultMutableTreeNode jButton =
new DefaultMutableTreeNode("JB utton");
DefaultMutableTreeNode jMenuItem =
new DefaultMutableTreeNode("JM enuItem");
DefaultMutableTreeNode jToggle =
new DefaultMutableTreeNode("JT oggleButto n");
DefaultMutableTreeNode jLabel =
new DefaultMutableTreeNode("JL abel");
DefaultMutableTreeNode etc =
new DefaultMutableTreeNode(".. .");
// Group the nodes
component.add(container);
container.add(box);
container.add(jComponent);
jComponent.add(abstractBut ton);
abstractButton.add(jButton );
abstractButton.add(jMenuIt em);
abstractButton.add(jToggle );
jComponent.add(jLabel);
jComponent.add(etc);
TreeSelectionListener listener =
new MyTreeSelectionListener(th is);
TreePanel tp = new TreePanel(component, listener);
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tp);
/*port = scrollpane.getViewport();
viewPortR = port.getViewRect();
int y = port.getViewSize().height;
int x = port.getViewSize().width;
Point p = new Point(10, 20);
port.setViewPosition(p);
*/
// Display it all in a window and make the window appear
mySplitPane = new JSplitPane();
contentPane.add(mySplitPan e, BorderLayout.CENTER);
contentPane.add(scrollpane , BorderLayout.WEST);
//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent. VK_A);
menu.getAccessibleContext( ).setAcces sibleDescr iption(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(Key Event.VK_T ); //used constructor instead
menuItem.setAccelerator(Ke yStroke.ge tKeyStroke (
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleCont ext().setA ccessibleD escription (
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.g if"));
menuItem.setMnemonic(KeyEv ent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.g if"));
menuItem.setMnemonic(KeyEv ent.VK_D);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(tru e);
rbMenuItem.setMnemonic(Key Event.VK_R );
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Anot her one");
rbMenuItem.setMnemonic(Key Event.VK_O );
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(Key Event.VK_C );
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(Key Event.VK_H );
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEve nt.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(Ke yStroke.ge tKeyStroke (
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenu Run = new JMenu("Run");
menuBar.add(Run);
JMenu options = new JMenu("Option");
menuBar.add(options);
JMenu help = new JMenu("Help");
menuBar.add(help);
setLookAndfeel = new JMenuItem("Set Look and feel");
setLookAndfeel.addActionLi stener(new MenuListener());
options.add(setLookAndfeel );
}
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon ent(newCon tainer);
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
public static void main(String[] args) {
System.out.println("Please enter the look and feel you want: (Windows, Motif, Metal) ");
String lookAndFeel = Console.readString();
Test window = new Test(lookAndFeel);
window.setTitle("MenuLookD emo");
window.setSize(450, 260);
window.setVisible(true);
}
public class MenuListener implements ActionListener
{
JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.
public void actionPerformed(ActionEven t event)
{
Object source = event.getSource();
if(source == setLookAndfeel)
{
try
{
System.out.println("got here");
String laf = "Metal";
Test p = new Test(laf);
}catch(Exception e){}
}
}
}
class MyTreeSelectionListener implements TreeSelectionListener {
private Map myScreenMap = new HashMap();
private Test myParentFrame;
public MyTreeSelectionListener(Te st parentFrame)
{
this.myParentFrame = parentFrame;
}
public void valueChanged (TreeSelectionEvent event)
{
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " + path.getLastPathComponent( ));
String command = String.valueOf(path.getLas tPathCompo nent());
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands ".equals(c ommand))
{
}
myScreenMap.put(command, container);
}
myParentFrame.setRightPane l(containe r);
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t oString()+ "\n");
updateWithObject(elements[ i]);
}
System.out.println ();
}
}
public void updateWithObject(Object o)
{
}
}
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
}
}
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
that within the MyFAQHelpPanel
i just had
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{
System.out.println("hello world");
}
}
This worked once, i.e if i cliked on Box it would print hello world to the console once, and if i clicked on it again it wouldnt [print it again.
Then I tried to do the following:
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
}
}
And nothing would appear in the centre of the Frame. Also when I created the gui starts up in the centre of the frame there is a left button and right button as the jsplitpane why is this????
Here is my code ( if you want to run it just copy into a file called Test.java and compile and run ):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuI
import javax.swing.JRadioButtonMe
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.tree.*;
import java.util.*;
/*
http://www.oreilly.de/catalog/jfcnut/chapter/ch03.html#ch03_22.html
https://www.experts-exchange.com/questions/20537023/JTree-problem.html
* This class exists solely to show you what menus look like.
* It has no menu-related event handling.
*/
public class Test extends JFrame {
JTextArea output;
JScrollPane scrollPane;
Container contentPane;
JMenuItem setLookAndfeel;
String laf;
JSplitPane mySplitPane;
public Test(String lookAndFeel) {
laf = "com.sun.java.swing.plaf.w
String look = lookAndFeel;
String feel = "Windows";
String motif = "Motif";
look = look.trim().toLowerCase();
feel = feel.trim().toLowerCase();
motif = motif.trim().toLowerCase()
try
{
if(look.equals(feel))
UIManager.setLookAndFeel("
else if(look.equals(motif))
UIManager.setLookAndFeel("
else if (look.equals("Metal"))
{
UIManager.setLookAndFeel("
}
else
{
UIManager.setLookAndFeel("
}
}catch(Exception e){}
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JCheckBoxMenuItem cbMenuItem;
JRadioButtonMenuItem rbMenuItem;
JButton b1, b2, b3;
JPanel buttonPanel;
JViewport port;
Rectangle viewPortR;
Dimension pa;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Add regular components to the window, using the default BorderLayout.
contentPane = getContentPane();
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
JPanel panel = new JPanel();
ImageIcon firstButtonIcon = new ImageIcon("start.gif");
ImageIcon middleButtonIcon = new ImageIcon("stop.gif");
ImageIcon LastButtonIcon = new ImageIcon("start.jpg");
b1 = new JButton(firstButtonIcon);
b1.setVerticalTextPosition
b1.setHorizontalTextPositi
b1.setMnemonic(KeyEvent.VK
b2 = new JButton(middleButtonIcon);
b2.setVerticalTextPosition
b2.setHorizontalTextPositi
b2.setMnemonic(KeyEvent.VK
b3 = new JButton( "Last BUtton: ");
b3.setVerticalTextPosition
b3.setHorizontalTextPositi
b3.setMnemonic(KeyEvent.VK
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT
buttonPanel.add(b1);
buttonPanel.add(b2);
buttonPanel.add(b3);
contentPane.add(buttonPane
JTree tree = new JTree();
//tree.setModel();
//tree.addTreeSelectionLis
DefaultMutableTreeNode component =
new DefaultMutableTreeNode("Co
DefaultMutableTreeNode container =
new DefaultMutableTreeNode("Co
DefaultMutableTreeNode box =
new DefaultMutableTreeNode("Bo
DefaultMutableTreeNode jComponent =
new DefaultMutableTreeNode("JC
DefaultMutableTreeNode abstractButton =
new DefaultMutableTreeNode("Ab
DefaultMutableTreeNode jButton =
new DefaultMutableTreeNode("JB
DefaultMutableTreeNode jMenuItem =
new DefaultMutableTreeNode("JM
DefaultMutableTreeNode jToggle =
new DefaultMutableTreeNode("JT
DefaultMutableTreeNode jLabel =
new DefaultMutableTreeNode("JL
DefaultMutableTreeNode etc =
new DefaultMutableTreeNode("..
// Group the nodes
component.add(container);
container.add(box);
container.add(jComponent);
jComponent.add(abstractBut
abstractButton.add(jButton
abstractButton.add(jMenuIt
abstractButton.add(jToggle
jComponent.add(jLabel);
jComponent.add(etc);
TreeSelectionListener listener =
new MyTreeSelectionListener(th
TreePanel tp = new TreePanel(component, listener);
// The JTree can get big, so allow it to scroll
JScrollPane scrollpane = new JScrollPane(tp);
/*port = scrollpane.getViewport();
viewPortR = port.getViewRect();
int y = port.getViewSize().height;
int x = port.getViewSize().width;
Point p = new Point(10, 20);
port.setViewPosition(p);
*/
// Display it all in a window and make the window appear
mySplitPane = new JSplitPane();
contentPane.add(mySplitPan
contentPane.add(scrollpane
//Create the menu bar.
menuBar = new JMenuBar();
setJMenuBar(menuBar);
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.
menu.getAccessibleContext(
"The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("A text-only menu item",
KeyEvent.VK_T);
//menuItem.setMnemonic(Key
menuItem.setAccelerator(Ke
KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleCont
"This doesn't really do anything");
menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon",
new ImageIcon("images/middle.g
menuItem.setMnemonic(KeyEv
menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.g
menuItem.setMnemonic(KeyEv
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(tru
rbMenuItem.setMnemonic(Key
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Anot
rbMenuItem.setMnemonic(Key
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(Key
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another
cbMenuItem.setMnemonic(Key
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEve
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(Ke
KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenu Run = new JMenu("Run");
menuBar.add(Run);
JMenu options = new JMenu("Option");
menuBar.add(options);
JMenu help = new JMenu("Help");
menuBar.add(help);
setLookAndfeel = new JMenuItem("Set Look and feel");
setLookAndfeel.addActionLi
options.add(setLookAndfeel
}
public void setRightPanel(Container newContainer)
{
mySplitPane.setRightCompon
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
public static void main(String[] args) {
System.out.println("Please
String lookAndFeel = Console.readString();
Test window = new Test(lookAndFeel);
window.setTitle("MenuLookD
window.setSize(450, 260);
window.setVisible(true);
}
public class MenuListener implements ActionListener
{
JFileChooser fc = new JFileChooser(); //Creates a fileChooser to open & save files etc.
public void actionPerformed(ActionEven
{
Object source = event.getSource();
if(source == setLookAndfeel)
{
try
{
System.out.println("got here");
String laf = "Metal";
Test p = new Test(laf);
}catch(Exception e){}
}
}
}
class MyTreeSelectionListener implements TreeSelectionListener {
private Map myScreenMap = new HashMap();
private Test myParentFrame;
public MyTreeSelectionListener(Te
{
this.myParentFrame = parentFrame;
}
public void valueChanged (TreeSelectionEvent event)
{
TreePath path = event.getPath();
JTextArea texts = new JTextArea();
contentPane.add(texts, BorderLayout.EAST);
System.out.println ("Selected: " + path.getLastPathComponent(
String command = String.valueOf(path.getLas
Container container = (Container) myScreenMap.get(command);
if(container==null)
{
//create such container instance, for example,
if("Box".equals(command))
{
container = new MyFAQHelpPanel();
}
else if("YourOtherKindsCommands
{
}
myScreenMap.put(command, container);
}
myParentFrame.setRightPane
Object elements[] = path.getPath();
for (int i=0; i<elements.length; i++) {
System.out.print ("->" + elements[i]);
texts.append(elements[i].t
updateWithObject(elements[
}
System.out.println ();
}
}
public void updateWithObject(Object o)
{
}
}
class MyFAQHelpPanel extends JPanel
{
public MyFAQHelpPanel()
{JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
}
}
ASKER
sorry about the three previous (multiple) posts something this side I couldnt help and had to press refresh without realising!
ASKER
class MyFAQHelpPanel should look like this:
class MyFAQHelpPanel extends JPanel
{
JPanel aPanel;
public MyFAQHelpPanel()
{
aPanel = new JPanel(new BorderLayout());
System.out.println("Hello" );
JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
}
}
class MyFAQHelpPanel extends JPanel
{
JPanel aPanel;
public MyFAQHelpPanel()
{
aPanel = new JPanel(new BorderLayout());
System.out.println("Hello"
JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
}
}
Could I get back to you after this weekend? Thanks.
First, I think the GUI layout in the center of your frame should be a splitpane, in which your TreePanel resides on the left and your future displayable panel (based on user command) resides on the right.
To put your TreePanel to the left of splitpane, you call splitpane.setLeftComponent (). And your existing setRightPanel() function helps switch the display panels on the right.
Here is a revised version of the setRightPanel() that you could try if the panels do not show up when repeat toggling.
public void setRightPanel(Container newContainer)
{
Component oldRightComp = mySplitPane.getRightCompon ent();
if(oldRightComp!=null)
{
mySplitPane.remove(oldRigh tComp);
}
newContainer.setVisible(tr ue);
mySplitPane.setRightCompon ent(newCon tainer);
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
Last, you'd better put in a dummy (empty) JPanel to the right of JSplitPane when the program starts in order to avoid the "Right Button" showing on the right side of JSplitPane. Since your Tree Panel already occupies the left side of the JSplitPane during initiation, the "Left Button" sign will not display anymore.
Good luck.
To put your TreePanel to the left of splitpane, you call splitpane.setLeftComponent
Here is a revised version of the setRightPanel() that you could try if the panels do not show up when repeat toggling.
public void setRightPanel(Container newContainer)
{
Component oldRightComp = mySplitPane.getRightCompon
if(oldRightComp!=null)
{
mySplitPane.remove(oldRigh
}
newContainer.setVisible(tr
mySplitPane.setRightCompon
//following lines may or may not be necessary to force the screen refresh
mySplitPane.invalidate();
this.invalidate();
}
Last, you'd better put in a dummy (empty) JPanel to the right of JSplitPane when the program starts in order to avoid the "Right Button" showing on the right side of JSplitPane. Since your Tree Panel already occupies the left side of the JSplitPane during initiation, the "Left Button" sign will not display anymore.
Good luck.
ASKER
This must appear like spoon feeding! But I have another problem, I did waht you said, I changed it aroung as well taht i added the splitpane to the center of the contentpane and move the tree as the left hand component of the of splitpane, that works fine. But now if I click on anyhow of the nodes in the tree I get a null pointer exception!
Here it is:
Selected: Container //thats what I print out so that i know what is selected
java.lang.NullPointerExcep tion
at Test.setRightPanel(Test.ja va:408)
at Test$MyTreeSelectionListen er.valueCh anged(Test .java:482)
at javax.swing.JTree.fireValu eChanged(J Tree.java: 2402)
at javax.swing.JTree$TreeSele ctionRedir ector.valu eChanged(J Tree.java: 277
3)
at javax.swing.tree.DefaultTr eeSelectio nModel.fir eValueChan ged(Defaul tTr
eeSelectionModel.java:629)
at javax.swing.tree.DefaultTr eeSelectio nModel.not ifyPathCha nge(Defaul tTr
eeSelectionModel.java:1071 )
at javax.swing.tree.DefaultTr eeSelectio nModel.add SelectionP aths(Defau ltT
reeSelectionModel.java:406 )
at javax.swing.tree.DefaultTr eeSelectio nModel.add SelectionP ath(Defaul tTr
eeSelectionModel.java:303)
at javax.swing.JTree.addSelec tionPath(J Tree.java: 1281)
at javax.swing.JTree.setExpan dedState(J Tree.java: 2989)
at javax.swing.JTree.collapse Path(JTree .java:1769 )
at javax.swing.plaf.basic.Bas icTreeUI.t oggleExpan dState(Bas icTreeUI.j ava
:2104)
at javax.swing.plaf.basic.Bas icTreeUI.h andleExpan dControlCl ick(BasicT ree
UI.java:2080)
at javax.swing.plaf.basic.Bas icTreeUI.c heckForCli ckInExpand Control(Ba sic
TreeUI.java:2034)
at javax.swing.plaf.basic.Bas icTreeUI$M ouseHandle r.handleSe lection(Ba sic
TreeUI.java:2809)
at javax.swing.plaf.basic.Bas icTreeUI$M ouseHandle r.mousePre ssed(Basic Tre
eUI.java:2779)
at java.awt.AWTEventMulticast er.mousePr essed(AWTE ventMultic aster.java :21
8)
at java.awt.Component.process MouseEvent (Component .java:5018 )
at java.awt.Component.process Event(Comp onent.java :4818)
at java.awt.Container.process Event(Cont ainer.java :1525)
at java.awt.Component.dispatc hEventImpl (Component .java:3526 )
at java.awt.Container.dispatc hEventImpl (Container .java:1582 )
at java.awt.Component.dispatc hEvent(Com ponent.jav a:3367)
at java.awt.LightweightDispat cher.retar getMouseEv ent(Contai ner.java:3 359
)
at java.awt.LightweightDispat cher.proce ssMouseEve nt(Contain er.java:30 71)
at java.awt.LightweightDispat cher.dispa tchEvent(C ontainer.j ava:3004)
at java.awt.Container.dispatc hEventImpl (Container .java:1568 )
at java.awt.Window.dispatchEv entImpl(Wi ndow.java: 1581)
at java.awt.Component.dispatc hEvent(Com ponent.jav a:3367)
at java.awt.EventQueue.dispat chEvent(Ev entQueue.j ava:445)
at java.awt.EventDispatchThre ad.pumpOne EventForHi erarchy(Ev entDispatc hTh
read.java:191)
at java.awt.EventDispatchThre ad.pumpEve ntsForHier archy(Even tDispatchT hre
ad.java:144)
at java.awt.EventDispatchThre ad.pumpEve nts(EventD ispatchThr ead.java:1 38)
at java.awt.EventDispatchThre ad.pumpEve nts(EventD ispatchThr ead.java:1 30)
at java.awt.EventDispatchThre ad.run(Eve ntDispatch Thread.jav a:98)
And its not adding the Jpanel to the right component correctly. Im obviously not doing something right but what im not sure!! I can post the code again if you want to see and run it.
Thanks a lot for all the help, much appreciated.
Here it is:
Selected: Container //thats what I print out so that i know what is selected
java.lang.NullPointerExcep
at Test.setRightPanel(Test.ja
at Test$MyTreeSelectionListen
at javax.swing.JTree.fireValu
at javax.swing.JTree$TreeSele
3)
at javax.swing.tree.DefaultTr
eeSelectionModel.java:629)
at javax.swing.tree.DefaultTr
eeSelectionModel.java:1071
at javax.swing.tree.DefaultTr
reeSelectionModel.java:406
at javax.swing.tree.DefaultTr
eeSelectionModel.java:303)
at javax.swing.JTree.addSelec
at javax.swing.JTree.setExpan
at javax.swing.JTree.collapse
at javax.swing.plaf.basic.Bas
:2104)
at javax.swing.plaf.basic.Bas
UI.java:2080)
at javax.swing.plaf.basic.Bas
TreeUI.java:2034)
at javax.swing.plaf.basic.Bas
TreeUI.java:2809)
at javax.swing.plaf.basic.Bas
eUI.java:2779)
at java.awt.AWTEventMulticast
8)
at java.awt.Component.process
at java.awt.Component.process
at java.awt.Container.process
at java.awt.Component.dispatc
at java.awt.Container.dispatc
at java.awt.Component.dispatc
at java.awt.LightweightDispat
)
at java.awt.LightweightDispat
at java.awt.LightweightDispat
at java.awt.Container.dispatc
at java.awt.Window.dispatchEv
at java.awt.Component.dispatc
at java.awt.EventQueue.dispat
at java.awt.EventDispatchThre
read.java:191)
at java.awt.EventDispatchThre
ad.java:144)
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
at java.awt.EventDispatchThre
And its not adding the Jpanel to the right component correctly. Im obviously not doing something right but what im not sure!! I can post the code again if you want to see and run it.
Thanks a lot for all the help, much appreciated.
ASKER
Sorry just fixed that part:
it was to do with this line in the setRightPanel method
newContainer.setVisible(tr ue);
But it stilll isnt paiintin the panel its just blank. However when i click on the "box" node the right button disappears and a panel is definatley being created as its no longer a button, I dont think I am adding components to the panel correctly. Does this class look alright:
class MyFAQHelpPanel extends JPanel
{
JPanel aPanel;
public MyFAQHelpPanel()
{
aPanel = new JPanel(new BorderLayout());
System.out.println("Hello" );
JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
}
}
it was to do with this line in the setRightPanel method
newContainer.setVisible(tr
But it stilll isnt paiintin the panel its just blank. However when i click on the "box" node the right button disappears and a panel is definatley being created as its no longer a button, I dont think I am adding components to the panel correctly. Does this class look alright:
class MyFAQHelpPanel extends JPanel
{
JPanel aPanel;
public MyFAQHelpPanel()
{
aPanel = new JPanel(new BorderLayout());
System.out.println("Hello"
JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
}
}
ASKER
Just to let you know again, I tried to just set the rightcomponent in the test frame to the following:
mySplitPane.setRightCompon ent(MyFAQH elpPanel() );
it just did the same as when calling the class once the Box node in the tree is clicked, but as usual the right button didnt appear so it appears to be doing something am I adding things to the panel in that class incorrectly or what? I also tried to make myfaqhelppanel a method of type component and pass it in the parameters of the setRightComponent, but it still didnt fraw the panel, any ideas to what I am NOT doing?? When you get a chance to answer this I will be very happy!!!
Thanks again,
Paul
mySplitPane.setRightCompon
it just did the same as when calling the class once the Box node in the tree is clicked, but as usual the right button didnt appear so it appears to be doing something am I adding things to the panel in that class incorrectly or what? I also tried to make myfaqhelppanel a method of type component and pass it in the parameters of the setRightComponent, but it still didnt fraw the panel, any ideas to what I am NOT doing?? When you get a chance to answer this I will be very happy!!!
Thanks again,
Paul
ASKER
Is this post getting modified, and seen by users cause a friend of mine has gone through all the questions and cant see this one!!
anyone got any idea on this question if they have seen it???
Thanks
anyone got any idea on this question if they have seen it???
Thanks
Here is the code from your previous post. Within your MyFAQHelpPanel class you have an instance variable aPanel, and you put everything onto that panel, but you did not put it onto your instance of MyFAQHelpPanel, which means when you instantiate an instance of MyFAQHelpPanel, there is nothing on it! Two solutions. One is to add following two lines in the proper location of your following code,
this.setLayout(new BorderLayout());
this.add(aPanel, BorderLayout.CENTER);
The other is to completely abandon aPanel instance and add all GUI component directly to the MyFAQHelpPanel, so replace what you have on aPanel. to this., then it should work.
Additionally, after correcting this, you might give it try to bring "newContainer.setVisible(t rue);" back to the setRightPanel() method or add a "if(newContainer!=null)" in front of it as checking.
class MyFAQHelpPanel extends JPanel
{
JPanel aPanel;
public MyFAQHelpPanel()
{
aPanel = new JPanel(new BorderLayout());
System.out.println("Hello" );
JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true) ;
textArea.setWrapStyleWord( true);
aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
}
}
this.setLayout(new BorderLayout());
this.add(aPanel, BorderLayout.CENTER);
The other is to completely abandon aPanel instance and add all GUI component directly to the MyFAQHelpPanel, so replace what you have on aPanel. to this., then it should work.
Additionally, after correcting this, you might give it try to bring "newContainer.setVisible(t
class MyFAQHelpPanel extends JPanel
{
JPanel aPanel;
public MyFAQHelpPanel()
{
aPanel = new JPanel(new BorderLayout());
System.out.println("Hello"
JTextArea textArea = new JTextArea(
"This is an editable JTextArea " +
"that has been initialized with the setText method. " +
"A text area is a \"plain\" text component, " +
"which means that although it can display text " +
"in any font, all of the text is in the same font."
);
textArea.setFont(new Font("Serif", Font.ITALIC, 16));
textArea.setLineWrap(true)
textArea.setWrapStyleWord(
aPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
}
}
I think your friends need to search deep down the chain instead of from the first couple of pages of "Language" section in order to find this post because it is not a new one to date.
ASKER
I am not fully sure what you mean in your first solution.
You wont be able to add this because the instance is in the treeselectionlistener class and a new instance gets created every time something is clicked.
this.setLayout(new BorderLayout());
this.add(aPanel, BorderLayout.CENTER);
what am I supposed to be adding the aPanel too?
the other solution you are saying is to manually add all the components to the constructor like such:
public MyFAQHelpPAnel(Jtextarea texarea, etc)
then initialise it in hte constructor, is that correct? I tried that before but it didnt work.
Thanks.
You wont be able to add this because the instance is in the treeselectionlistener class and a new instance gets created every time something is clicked.
this.setLayout(new BorderLayout());
this.add(aPanel, BorderLayout.CENTER);
what am I supposed to be adding the aPanel too?
the other solution you are saying is to manually add all the components to the constructor like such:
public MyFAQHelpPAnel(Jtextarea texarea, etc)
then initialise it in hte constructor, is that correct? I tried that before but it didnt work.
Thanks.
ASKER
Tried both things there by setting the layout in my test class and adding components directly neither worked. I dont know if I am doing something wrong or if so what, because I know of other colleagues saying the same thing when using splitpanes, that this can be a problem. IS there something I could post to help? Tired eyes and a tired mind are failing me at this point!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Ya the hello print out was always printing to the screen that is why I thought the problem was with MyFaqHelppanel class, the second solution worked fine and dandy, thanks very much for all you put into this, I have another problem now, that the jtextarea takes up the whole screen so i have to keep resizing if you know off hand the solution I would greatly appreciate it, otherwise dont worry ill figure it out.
Ill assign the points to you soon.
Thanks again for the help and the time,
Paul
Ill assign the points to you soon.
Thanks again for the help and the time,
Paul
Your Textarea takes up all the screen because you used BorderLayout for your panel and add your textarea to it by BorderLayout.CENTER.
If you don't want to do so, you need to change the layout manger of your MyFaqHelppanel to something else or put a huge empty JPanel on the NORTH and SOUTH of MyFaqHelppanel to kind of squeeze the text area to the "center" as you want.
Good luck.
If you don't want to do so, you need to change the layout manger of your MyFaqHelppanel to something else or put a huge empty JPanel on the NORTH and SOUTH of MyFaqHelppanel to kind of squeeze the text area to the "center" as you want.
Good luck.
ASKER
Very good answer, he spent a lot of time explaining things as well. Thanks a lot