Solved

Unable to change or refresh JFrame from the ActionPerformed() methods

Posted on 2015-01-25
2
112 Views
Last Modified: 2015-01-25
Something simple-looking but very annoying here:

I would like to update the JFrame with changing text on a JButton and enable / disable a JList, on this form, per clicks of menu items captured with ActionListener ActionPerformed, on the fly, at runtime. Well, no matter what I do the update of JFrame will not happen. What is happening here? Why is it not updating like this?
What do I need to change so that the update happens, when I select each checkbox menu item?

This is what doesn't work:

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

    private void jMenuTroubleshooting_ActionPerformed(ActionEvent e){
        System.out.println("Troubleshoot PCB Clicked");
        this.jbtnOpenProject.setText("Continue");
        this.jlstProjectList.setEnabled(false);
        this.validate();
        this.repaint();
    }

Open in new window


And this is the full code for the class, if you want to try to run it:

import java.awt.*;
import java.awt.event.*;
import java.io.File;
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;
           private JCheckBoxMenuItem jMenuTroubleshooting;
           
           // Making menus mutually exclusive:
           private ButtonGroup troubleshootOptionsGroup = new ButtonGroup();
        
        // Default: cascon is installed:
        private boolean casconInstalled = true;
        
	public SelectProject() {
	   super("BST Program ITC version 1.1 - Select Project" ); 
	        initComponents();
	    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 = new JCheckBoxMenuItem();
	    jMenuTroubleshooting = new JCheckBoxMenuItem();
	    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);
                   
                }
                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() {
		
		
	    // 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 (casconInstalled){
                    jbtnOpenProject.setText("Open Project");
                    jlstProjectList.setEnabled(true);
                    }
                else{
                    jbtnOpenProject.setText("Continue");
                    jlstProjectList.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 = "c:\\";
             
             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("")){
                    JOptionPane.showMessageDialog(null, "       Select project to load ", "No Selection Made", JOptionPane.WARNING_MESSAGE);
                }
            else{
                    System.out.println("Open project: " + selectionLine);
                }  
    }
    
    // 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());
                    }
                }
           }
       }
    
    // 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;
    }

// THIS IS WHERE THE PROBLEM IS, THE ACTIONPERFORMED METHODS FOR MENUS:
// *******************************************************************
    private void jMenuBSTesting_ActionPerformed(ActionEvent e){
        System.out.println("Boundary Scan Testing Clicked");
        this.jbtnOpenProject.setText("Open Project");
        this.jlstProjectList.setEnabled(true);
        this.validate();
        this.repaint();
    }

    private void jMenuTroubleshooting_ActionPerformed(ActionEvent e){
        System.out.println("Troubleshoot PCB Clicked");
        this.jbtnOpenProject.setText("Continue");
        this.jlstProjectList.setEnabled(false);
        this.validate();
        this.repaint();
    }
}

Open in new window


Thank you for your help.
0
Comment
Question by:AttilaB
2 Comments
 
LVL 14

Accepted Solution

by:
CPColin earned 500 total points
ID: 40569497
Looks like your code is calling initComponents() twice, so the objects stored in your class's member variables aren't the same ones being shown on the screen. If you remove the first call, everything seems to work as expected.
0
 

Author Closing Comment

by:AttilaB
ID: 40569926
How did I NOT notice that?  Thank you for your help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Running Jira on Raspberry PI 2? 3 247
Error with Java/Cache JDBC Classpath 2 30
Apps blocked by Java 9 55
servlet example issue 6 29
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

932 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

18 Experts available now in Live!

Get 1:1 Help Now