0

I want to assign dir array to comboBox. Is there any error in my code. I tried to display the dir array it contains the values but cannot assign it comboBox. Here is the code.

import java.awt.EventQueue;


public class ExpenseManager {

private JFrame frame;
private JTextField txtUserName;
private JLabel lblNewUserName; 
private JButton btnDone;
private JButton btnLogin;
private JComboBox<?> comboBox;
private String[] dir = new String[100];
private String[] hello = {"Hii", "Hello"};

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                ExpenseManager window = new ExpenseManager();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public ExpenseManager() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
//@SuppressWarnings("unchecked")
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnNewUser = new JButton("New User");
    btnNewUser.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            lblNewUserName.setVisible(true);
            txtUserName.setVisible(true);
            btnDone.setVisible(true);
        }
    });
    btnNewUser.setBounds(23, 34, 89, 23);
    frame.getContentPane().add(btnNewUser);

    txtUserName = new JTextField();
    txtUserName.setBounds(240, 63, 134, 20);
    frame.getContentPane().add(txtUserName);
    txtUserName.setVisible(false);
    txtUserName.setColumns(10);

    lblNewUserName = new JLabel("Enter New UserName");
    lblNewUserName.setBounds(240, 38, 134, 14);
    lblNewUserName.setVisible(false);
    frame.getContentPane().add(lblNewUserName);

    btnDone = new JButton("Done");
    btnDone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String newUserName = txtUserName.getText();
            if(!newUserName.isEmpty())
            {
                File f = new File("S:/Expense/" + newUserName);
                if (f.exists() && f.isDirectory()) {
                   JOptionPane.showMessageDialog(null, "User already exists");
                   txtUserName.setText(null);
                }
                else{
                    boolean success = (new File("S:/Expense/" + newUserName)).mkdir();
                    if(!success){
                        JOptionPane.showMessageDialog(null, "Unable to register");
                    }else{
                        JOptionPane.showMessageDialog(null, "User registered Successfully");
                    }
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Kindly enter User Name", "Invalid User Name", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    btnDone.setBounds(240, 103, 89, 23);
    btnDone.setVisible(false);
    frame.getContentPane().add(btnDone);

    btnLogin = new JButton("Login");
    btnLogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            File[] directories = new File("S:/Expense/").listFiles();

            for(int i = 0; i < directories.length; i++)
            {
                dir[i] = directories[i].getName();
            }

            comboBox.setVisible(true);

        }
    });
    btnLogin.setBounds(23, 68, 89, 23);
    frame.getContentPane().add(btnLogin);

    comboBox = new JComboBox<Object>(dir);
    comboBox.setBounds(24, 138, 72, 20);
    comboBox.setSelectedIndex(1);
    comboBox.setVisible(false);
    frame.getContentPane().add(comboBox);

     }
  }
Vaibhav More
  • 994
  • 3
  • 10
  • 22
  • 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) The `dir` array is only populated after an action is detected. But it is used as a constructor for a combo box when the class is initialised (while still empty). – Andrew Thompson Jul 09 '17 at 06:49
  • Why you are using `comboBox.setVisible(true);` before you add the Items and `comboBox.setVisible(false);` after for what purpose? – Youcef LAIDANI Jul 09 '17 at 07:01

2 Answers2

2

You can use setModel with DefaultComboBoxModel which take an array instead like :

comboBox.setModel(new DefaultComboBoxModel(dir));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

Most of the code posted is not relevant to the question asked, so it should be removed (see MCVE). Review the following, note the comments:

public class ExpenseManager {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new ExpenseManager();
                } catch (Exception e) { e.printStackTrace();    }
            }
        });
    }

    public ExpenseManager() {   initialize(); }

    private void initialize() {

        JFrame frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null); //better use a layout manger

        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.setBounds(24, 138, 72, 20);
        comboBox.setVisible(false);
        frame.getContentPane().add(comboBox);

        JButton btn = new JButton("Populate combo");
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                //populate combo
                String[] dir = new String[5];

                for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}

                comboBox.setModel(new DefaultComboBoxModel<>(dir));
                comboBox.setVisible(true);
                btn.setEnabled(false); //disable button 
            }
        });
        btn.setBounds(23, 68, 89, 23);
        frame.getContentPane().add(btn);
        frame.setVisible(true);
    }
}

EDIT implementation using a layout manager :

private void initialize() {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.setVisible(false);
        frame.add(comboBox, BorderLayout.SOUTH); //using BorderLayout which is the default

        JButton btn = new JButton("Populate combo");
        btn.setPreferredSize(new Dimension(150,35));
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                //populate combo
                String[] dir = new String[5];

                for(int i = 0; i < dir.length; i++) { dir[i] = "String "+ i;}

                comboBox.setModel(new DefaultComboBoxModel<>(dir));
                comboBox.setVisible(true);
                btn.setEnabled(false); //disable button
                frame.pack();  //resize fram to fit the preferred size and layouts
            }
        });
        frame.getContentPane().add(btn, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);
    }
c0der
  • 18,467
  • 6
  • 33
  • 65