Solved

Selecting Checkbox Menu items Programmatically

Posted on 2015-01-31
3
107 Views
Last Modified: 2015-02-04
This is how the screen with main() method looks like:
This shows the startup JFrame with the checkbox menu items
I would like to programmatically select JCheckBoxMenuItem jMenuTroubleshooting in the following program.
It is part of a ButtonGroup troubleshootOptionsGroup.

If the program doesn't find the folder "C:\\goepel\\CAS4WIN_\\Sys\\Bin\\" on your computer it should automatically do the change of selection code:  (directoryExists => false)

                if (directoryExists){
                    jbtnOpenProject.setText("Open Project");
                    jlstProjectList.setEnabled(true);
                    }
                else{
                    jbtnOpenProject.setText("Continue");
                    jlstProjectList.setEnabled(false);
                    jMenuTroubleshooting.setSelected(true);
                    jMenuTroubleshooting.setState(true);   // why doesn't it select it?????
                    jMenuTroubleshooting.doClick();  // why doesn't it select it?????
                    jMenuBSTesting.setEnabled(false);
                    }
                

Open in new window


No matter what else I tried it doesn't change the selection.

The full code:

Main Class 'SelectProject ' , with the selection:
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class SelectProject extends JFrame {
	
	// Variables declaration 
	private JLabel jlblSelectTest;
	private JScrollPane scrollPane1;
        private DefaultListModel model; 
	private JList jlstProjectList;
	private JButton jbtnOpenProject;
	// End of variables declaration 
        
        private String selectionLine = "";
        private static String[] commandLineArguments;
        private String combinedCommandLineArgumentsString = "";
        private ArrayList<String> listOfAllProjectsInFolder = new ArrayList<String>();
        
        // Menu related objects:
        private JMenuBar menuBar1 = new JMenuBar(); 
    
        // Top level menu Load for Troublehooting or testing, testing
        // is  default:
           private JMenu mnuTopLevel_OperationMode = new JMenu();
           private JCheckBoxMenuItem jMenuBSTesting = new JCheckBoxMenuItem();
           private JCheckBoxMenuItem jMenuTroubleshooting = new JCheckBoxMenuItem();
           
           // Making menus mutually exclusive:
           private ButtonGroup troubleshootOptionsGroup = new ButtonGroup();
        
        SecondScreen casconMainScreen;
        
        // Default: cascon is installed:
        private boolean directoryExists = true;
        private boolean troubleshootOnly = false;  // Testing and troubleshooting allowed
        
	public SelectProject() {
	    try {
	        // Set the look and feel for the current OS (Windows) Scheme
	        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	                initComponents();
            } catch (Exception e) {
                e.printStackTrace();
	                    }
            this.setSize(388,396);
	    this.setResizable(false);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
	    this.setJMenuBar(menuBar1);
	    jMenuBSTesting.setText("Boundary Scan Testing");
	    jMenuBSTesting.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jMenuBSTesting_ActionPerformed(e);
			}
		});
            
	    jMenuTroubleshooting.setText("Troubleshoot PCB");
	    jMenuTroubleshooting.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jMenuTroubleshooting_ActionPerformed(e);
			}
		});
                
	    mnuTopLevel_OperationMode.setText("Operation Mode");
	    mnuTopLevel_OperationMode.add(jMenuBSTesting);
	    mnuTopLevel_OperationMode.add(jMenuTroubleshooting);
            
	    troubleshootOptionsGroup = new ButtonGroup();
	    troubleshootOptionsGroup.add(jMenuBSTesting);
	    troubleshootOptionsGroup.add(jMenuTroubleshooting);
	    jMenuBSTesting.setSelected(true);
            
	    menuBar1.add(mnuTopLevel_OperationMode);
	    
            // Make the Project Selector JFrame visible if no command line
            // argument:
            
            if(commandLineArguments.length == 0)
                this.setVisible(true);
            else{   // Project Selector JFrame invisible, command line argument used:
                combinedCommandLineArgumentsString = combineArguments(commandLineArguments);
                
                if(listOfAllProjectsInFolderContainsString(combinedCommandLineArgumentsString,listOfAllProjectsInFolder)){
                    this.setVisible(false);
                    System.out.println("Open project from command line: " + combinedCommandLineArgumentsString);
                    // Creating Child Window Instances:
                    casconMainScreen = new SecondScreen( combinedCommandLineArgumentsString, listOfAllProjectsInFolder);
                    casconMainScreen.setSize(565, 412);
                    casconMainScreen.setVisible(true);
                    casconMainScreen.setResizable(false);
                    casconMainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }
                else{
                    JOptionPane.showMessageDialog(null, "Parameter is not contained in list of projects. Please make a selection of test project to run.", " Unknown Project Name", JOptionPane.WARNING_MESSAGE);
                    this.setVisible(true);
                }
            } 
	}

	private void initComponents() {
		
		// See if Cascon Galaxy was installed on computer
		// if not list is un-clickable, and set class level false:
		   if(!(doesCasconFolderExists()) ){   
                            directoryExists = false;
		   }
                   
	    // Component initialization
                   
		jlblSelectTest = new JLabel();
		scrollPane1 = new JScrollPane();
                model = new DefaultListModel();
                jlstProjectList = new JList(model);
                
		jbtnOpenProject = new JButton();

		//======== this ========
		Container contentPane = getContentPane();
		contentPane.setLayout(null);

		//---- jlblSelectTest ----
		jlblSelectTest.setText("Select Test Project to Open:");
		jlblSelectTest.setFont(new Font("Tahoma", Font.BOLD, 14));
		jlblSelectTest.setHorizontalAlignment(SwingConstants.CENTER);
		contentPane.add(jlblSelectTest);
		jlblSelectTest.setBounds(50, 10, 260, 25);

		//======== scrollPane1 ========
		{
			scrollPane1.setViewportView(jlstProjectList);
		}
		contentPane.add(scrollPane1);
		scrollPane1.setBounds(20, 45, 340, 245);


		//---- jbtnOpenProject ----
                if (directoryExists){
                    jbtnOpenProject.setText("Open Project");
                    jlstProjectList.setEnabled(true);
                    }
                else{
                    jbtnOpenProject.setText("Continue");
                    jlstProjectList.setEnabled(false);
                    jMenuTroubleshooting.setSelected(true);
                    jMenuTroubleshooting.setState(true);   // why doesn't it select it?????
                    jMenuTroubleshooting.doClick();  // why doesn't it select it?????
                    jMenuBSTesting.setEnabled(false);
                    }
                
		jbtnOpenProject.setFont(new Font("Tahoma", Font.BOLD, 12));
		jbtnOpenProject.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {
				jbtnOpenProject_ActionPerformed(e);
			}
		});
		contentPane.add(jbtnOpenProject);
		jbtnOpenProject.setBounds(125, 305, 120, jbtnOpenProject.getPreferredSize().height);

		{ // compute preferred size
			Dimension preferredSize = new Dimension();
			for(int i = 0; i < contentPane.getComponentCount(); i++) {
				Rectangle bounds = contentPane.getComponent(i).getBounds();
				preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
				preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
			}
			Insets insets = contentPane.getInsets();
			preferredSize.width += insets.right;
			preferredSize.height += insets.bottom;
			contentPane.setMinimumSize(preferredSize);
			contentPane.setPreferredSize(preferredSize);
		}
		pack();
		setLocationRelativeTo(getOwner());
            
	    // Add a list selection listener anonymous instance to JList control:
            // (implementing valueChanged() method)
	                     ListSelectionListener lListener = new ListSelectionListener() {
	                         public void valueChanged(ListSelectionEvent e) {
	                             if (e.getValueIsAdjusting() == false) // it will prevent double firing when  valueChanged() is called
	                             {
	                                 JList list = (JList) e.getSource();
	                                 if (!(list.isSelectionEmpty())) {
	                                     selectionLine = (String) list.getSelectedValue();

	                                     System.out.println("Selected: " + selectionLine);
	                                     
	                                 }
	                             }
	                         }
	                     };

	                     jlstProjectList.addListSelectionListener(lListener);

                            String dirName = readINIFileToLoadProjectsDirectory();
             
             if (!(dirName.equals("")))
                    listFoldersInFolder(dirName);
             
		// End of component initialization  
	}
        

    public static void main(String[] args) {
                        
                    // Save the command line arguments in a static String array:
                      commandLineArguments = args;
          
                  // The static utility method invokeLater(Runnable) is intended to execute a new runnable
                  // thread from a Swing application without disturbing the normal sequence of event dispatching
                  // from the GUI.
          
       SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                 try {
                                     // Set the look and feel for the current OS (Windows) Scheme and
                                     // all subsequent jFrames will also have the same look and feel
                                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                                     SelectProject selectProject = new SelectProject();
                                     selectProject.setLocationRelativeTo(null);
                                     
                                 } catch (Exception e) {
                                     e.printStackTrace();
                                 }
                            }
                        });
                  }  
      

    private void jbtnOpenProject_ActionPerformed(ActionEvent e) {
            System.out.println("Open project Button Clicked");
            if (selectionLine.equals("") && jMenuBSTesting.isSelected()){
                    JOptionPane.showMessageDialog(null, "       Select project to load ", "No Selection Made", JOptionPane.WARNING_MESSAGE);
                    }
            else{
                    System.out.println("Open project: " + selectionLine);
                   
                    if(troubleshootOnly)  // Clear any previous selection
                        selectionLine = "";
                        
                    // Creating Child Window Instance:
                    casconMainScreen = new SecondScreen( selectionLine, listOfAllProjectsInFolder);    // line crashing
                    this.setVisible(false);
                    casconMainScreen.setSize(565, 412);
                    casconMainScreen.setVisible(true);
                    casconMainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                }  
    }
    
    // This will create a list of foldernames and add it
    // to the LList in the JFrame:
    public void listFoldersInFolder(String pathName)
       {
           model.clear();
           File [] paths;
           File file=new File(pathName);
           if(file.isDirectory()){
             paths = file.listFiles();  
                for (int i=0; i<paths.length; i++)
                {
                    if (paths[i].isDirectory()){
                    System.out.println(paths[i].getPath());
                    
                        listOfAllProjectsInFolder.add(paths[i].getPath());
                        
                        String pathNameString = paths[i].getName();
                        
                        // Folder 'CasconMainScreen_Executable' contains the
                        // executable program. Don't show a folder with that name:
                        if(!(pathNameString.equals("CasconMainScreen_Executable")))
                                model.addElement(paths[i].getName());
                    }
                }
           }
       }
    
    // This method will load the first uncommented line from
    // 'StartUp.ini' and return it as the projects directory
    private String readINIFileToLoadProjectsDirectory(){
        String directoryName = "";
            try {
                    // Open the file
                    FileInputStream fstream =new FileInputStream("StartUp.ini");
                
                    // Get the object of DataInputStream
                    DataInputStream in = new DataInputStream(fstream);
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));
                    String strLine;
                                      
                        //Read File Line By Line
                        while ((strLine = br.readLine()) != null) {
                                
                            if(!(strLine.startsWith("REM"))) {
                                if(!(strLine.trim().equals(""))){
                                    directoryName = strLine.trim();
                                        break;
                                             }
                                      }
                        } 
                    //Close the input stream
                    in.close();                   
                }
                    catch (Exception e) {
                    System.err.println("Error: " + e.getMessage());
                    e.printStackTrace();
        }
        return directoryName;
    }
    
    // Method for combining command line arguments into a single string:
    private String combineArguments(String [] commandLineArguments){
        String combinedString = "";
        for (int i =0; i< commandLineArguments.length; i++){
            combinedString = combinedString + " " + commandLineArguments[i];
        }
        return combinedString.trim(); //Take off heading " " (space) character
    }
    
    
// This method will determine if inputString is contained in a substring 
// of ArrayList<String> strings.
    private boolean  listOfAllProjectsInFolderContainsString(String inputString, ArrayList<String> listOfStrings){
        boolean stringContained = false;
        Iterator it = listOfStrings.iterator();
        
        while(it.hasNext()){
            String lineString = (String) it.next();
            System.out.println(lineString);
            if (lineString.contains(inputString)){
                stringContained = true;
                break;
            }
        }
        return stringContained;
    }

    private void jMenuBSTesting_ActionPerformed(ActionEvent e){
        System.out.println("Boundary Scan Testing Clicked");
        this.jbtnOpenProject.setText("Open Project");
        this.jlstProjectList.setEnabled(true);
        troubleshootOnly = false;
        this.repaint();
    }

    private void jMenuTroubleshooting_ActionPerformed(ActionEvent e){
        System.out.println("Troubleshoot PCB Clicked");
        this.jbtnOpenProject.setText("Continue");
        this.jlstProjectList.setEnabled(false);
        troubleshootOnly = true;
        this.repaint();
    }
   
    
    // This will determine if Cascon Galaxy has been
    // installed on your machine, only works on Java 1.7 and above:
    private boolean doesCasconFolderExists(){
        boolean casconFolderExistsLocal = false;
            Path path = Paths.get("C:\\goepel\\CAS4WIN_\\Sys\\Bin\\");
            if (Files.exists(path)) {
            casconFolderExistsLocal = true;
            }
        return casconFolderExistsLocal;     
    }
}

Open in new window


The other class required for running the code:  

import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;

public class SecondScreen extends JFrame {
    
      
	public SecondScreen(String testNameSelected, ArrayList<String> listOProjectsInFolder) {
            
            super("Test name selected:  " + testNameSelected + "   List Size: " + listOProjectsInFolder.size());
            
	   
            
	}  //     ------------------       End of constructor here 
        
        
	private void initComponents() {
            
		//======== this ========
		Container contentPane = getContentPane();
		contentPane.setLayout(null);
                
		
		{ // compute preferred size
			Dimension preferredSize = new Dimension();
			for(int i = 0; i < contentPane.getComponentCount(); i++) {
				Rectangle bounds = contentPane.getComponent(i).getBounds();
				preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
				preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
			}
			Insets insets = contentPane.getInsets();
			preferredSize.width += insets.right;
			preferredSize.height += insets.bottom;
			contentPane.setMinimumSize(preferredSize);
			contentPane.setPreferredSize(preferredSize);
		}
		pack();
		setLocationRelativeTo(getOwner());
		// End of component initialization  
              
	}

    
        }  // End of file

Open in new window


Thanks for your help.
0
Comment
Question by:AttilaB
  • 2
3 Comments
 
LVL 37

Accepted Solution

by:
zzynx earned 500 total points
ID: 40585685
>> No matter what else I tried it doesn't change the selection
The reason is this code:

        troubleshootOptionsGroup = new ButtonGroup();
        troubleshootOptionsGroup.add(jMenuBSTesting);
        troubleshootOptionsGroup.add(jMenuTroubleshooting);
        jMenuBSTesting.setSelected(true);      // <<<<<<<<<<<<<<< this is the reason

Open in new window


So, previously you have set jMenuTroubleshooting selected by executing this line:
jMenuTroubleshooting.setSelected(true);

Open in new window

Remark:
You can leave out these lines:
jMenuTroubleshooting.setState(true);
jMenuTroubleshooting.doClick();

Open in new window


but now you are creating a button group, to which you add both jMenuTroubleshooting and jMenuBSTesting.
Meaning when you select one the other will be unselected.
Then with the last line you select jMenuBSTesting. Meaning... you unselect jMenuTroubleshooting
0
 

Author Closing Comment

by:AttilaB
ID: 40587561
Well, you are right, this is where the problem was. I thought that I could initialize the menu multiple times including in opposing ways. But that did not work. You are right, if I take out the initial initialization, and just select whichever
want I want ONCE at the point where you can tell which menu is needed to be selected, it will actually work either the folder exists or not, and then according to user selection too.

So:          
        if (directoryExists){
                    jbtnOpenProject.setText("Open Project");
                    jlstProjectList.setEnabled(true);
                   [b] jMenuBSTesting.setSelected(true);[/b]         <<<<<<<<<<<<<<<<<<<
                    }
                else{
                    jbtnOpenProject.setText("Continue");
                    jlstProjectList.setEnabled(false);
                   [b] jMenuTroubleshooting.setSelected(true);[/b]         <<<<<<<<<<<<<<<<<<<
                    jMenuBSTesting.setEnabled(false);
                    }

Open in new window


This will work under any condition.

Thanks.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 40588061
You're welcome.
Thanx 4 axxepting
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
What is JNDI datasource in spring 1 39
Running Jira on Raspberry PI 2? 3 139
github account with ecipse 1 20
Java Timer (static) 9 19
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now