Hot questions for Using JTextField in jcombobox

Question:

I am using JCombobox and just below that there is a panel which contains JTextFields. Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself. I don't know what to do. I am unable to post a pic of the problem here because i am a new user and my reputation is below 10.

public class MainClass {
public static void main(String args[]){
    Form form = new Form();
    int width = 400;
    int height = 400;
    form.setSize(width, height);
    form.setVisible(true);
    form.setTitle("Create Network");
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    form.setLocation((screenSize.width-width)/2, (screenSize.height-height)/2);
}
}

This is the form class

public class Form extends JFrame {

private JLabel ipAddress, networkTopo, numNodes;
private JTextField nodes;
private JButton addIp;
private JButton removeIp;
private JButton next, back;
private JPanel jPanel, jPanel1, jPanel2, commonPanel;
private JComboBox<String> dropDown;

private String[] topologies = { "Grid", "Diagnol Grid", "Bus", "Ring",
        "Star" };

public Form() {
    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
    setResizable(false);
    this.getContentPane().setBackground(Color.WHITE);

    // add(Box.createRigidArea(new Dimension(0,10)));
    GridLayout commonPanelLayout = new GridLayout(0, 2);
    commonPanelLayout.setVgap(10);
    commonPanel = new JPanel(commonPanelLayout);
    commonPanel.setVisible(true);
    commonPanel.setAlignmentX(commonPanel.LEFT_ALIGNMENT);
    commonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    commonPanel.setBackground(Color.white);

    numNodes = new JLabel("Number of Nodes");
    commonPanel.add(numNodes);

    nodes = new JTextField(20);
    commonPanel.add(nodes);

    networkTopo = new JLabel("Network Topology");
    commonPanel.add(networkTopo);

    dropDown = new JComboBox<String>(topologies);
    dropDown.setBackground(Color.WHITE);
    commonPanel.add(dropDown);

    add(commonPanel);

    add(Box.createRigidArea(new Dimension(0, 10)));
    ipAddress = new JLabel("IP Addresses");
    ipAddress.setAlignmentX(ipAddress.LEFT_ALIGNMENT);
    ipAddress.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
    add(ipAddress);

    add(Box.createRigidArea(new Dimension(0, 10)));
    jPanel = new JPanel(new FlowLayout());
    jPanel.setVisible(true);
    jPanel.setAlignmentX(jPanel.LEFT_ALIGNMENT);
    jPanel.setBackground(Color.WHITE);
    // jPanel1.setAutoscrolls(true);
    add(jPanel);

    GridLayout layout = new GridLayout(0, 1);
    jPanel1 = new JPanel();
    layout.setVgap(10);
    // jPanel1.setBackground(Color.WHITE);
    jPanel1.setVisible(true);

    JScrollPane scroll = new JScrollPane();
    scroll.setViewportView(jPanel1);
    scroll.setAutoscrolls(true);
    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.setPreferredSize(new Dimension(300, 150));
    jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width,
            Integer.MAX_VALUE));
    jPanel.add(scroll);

    jPanel2 = new JPanel(new GridLayout(0, 1, 10, 10));
    jPanel2.setBackground(Color.WHITE);
    jPanel2.setVisible(true);
    jPanel.add(jPanel2);

    addIp = new JButton("Add");
    jPanel2.add(addIp);

    removeIp = new JButton("Remove");
    jPanel2.add(removeIp);

    JPanel savePanel = new JPanel(new FlowLayout());
    savePanel.setVisible(true);
    savePanel.setAlignmentX(savePanel.LEFT_ALIGNMENT);
    savePanel.setBackground(Color.white);

    back = new JButton("Back");
    back.setAlignmentX(next.LEFT_ALIGNMENT);
    back.setEnabled(false);
    savePanel.add(back);

    next = new JButton("Next");
    next.setAlignmentX(next.LEFT_ALIGNMENT);
    savePanel.add(next);

    add(savePanel);

    AddIPEvent addIPEvent = new AddIPEvent();
    addIp.addActionListener(addIPEvent);

    RemoveIPEvent removeIPEvent = new RemoveIPEvent();
    removeIp.addActionListener(removeIPEvent);

}

public class AddIPEvent implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        JPanel subPanel = new JPanel(new FlowLayout());
        // subPanel.setBackground(Color.WHITE);
        subPanel.setVisible(true);
        JCheckBox jCheckBox = new JCheckBox();
        // jCheckBox.setBackground(Color.WHITE);
        subPanel.add(jCheckBox);

        JTextField ip = new JTextField(12);
        subPanel.add(ip);

        JTextField nodesInIp = new JTextField(6);
        nodesInIp.setVisible(false);
        subPanel.add(nodesInIp);

        jPanel1.add(subPanel);
        jPanel1.repaint();
        jPanel1.revalidate();
    }
}

public class RemoveIPEvent implements ActionListener {

    public void removeIP(Container container) {
        for (Component c : container.getComponents()) {
            if (c instanceof JCheckBox) {
                if (((JCheckBox) c).isSelected()) {
                    jPanel1.remove(container);
                    jPanel.revalidate();
                    jPanel1.repaint();
                }
            } else if (c instanceof Container) {
                removeIP((Container) c);
            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        removeIP(jPanel1);
    }
}
}

After Clicking on the Add button and then clicking on the JComboBox will make portion of JTextField dissapear. Could someone pls point out the mistake?


Answer:

Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself.

//jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width, Integer.MAX_VALUE));

Don't set the preferred size of components. The layout manager will determine the preferred size as components are added/removed. Then scrollbars will appear as required.

jPanel1.repaint();
jPanel1.revalidate();

The order should be:

jPanel1.revalidate(); 
jPanel1.repaint(); 

The revalidate() first invokes the layout manager before it is repainted.

//form.setSize(width, height);
form.pack();

Again, don't try to set the size. Let the layout managers do their jobs. The pack() will size the frame based on the sizes of the components added to the frame.

Question:

I've come across a very weird problem. I had a JPanel which contains JTextFields and JComboBoxes. I can change the JComboBox's when the JPanel loads but as soon as I touch or edit one of the JTextFields it doesn't let me change any of the combobox's...

Here is an MCVE that works. You can use it straight away and you'll see the error.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;


public class Main extends JFrame{

    private static JTextField s;
    private static JTabbedPane tabbedPane;
    private static JPanel config;
    private static JComboBox<Object> dns;
    private static JComboBox<Object> dnsmm;
    private static JButton save;
    private static String interval;
    private static String dnsen;
    private static String dnsm;
    private static JPanel server;
    static JPanel contentPane;

    public static void main(String[] args) throws InterruptedException {

            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        Main frame = new Main();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    }


    public Main() throws IOException {

        setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 655, 470);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(1, 1));
        setContentPane(contentPane);

        tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        contentPane.add(tabbedPane, BorderLayout.CENTER);

        setResizable(false);

        server = new JPanel();
        server.setLayout(new BorderLayout(0, 0));

        ServerPanel();
    }

    public static void ServerPanel() throws IOException{ 

        tabbedPane.addTab("Manage Server", server);
        InputStream in = new FileInputStream("config.dedserver");
        Properties p = new Properties();
        p.load(in);
        in.close();
        String saveInt = p.getProperty("saveInterval");
        String dnse = p.getProperty("enableDns");
        String dnsmo = p.getProperty("serverMode");

        config = new JPanel();
        server.add(config, BorderLayout.CENTER);    
        config.setLayout(new BoxLayout(config, BoxLayout.PAGE_AXIS));


        //saveint
        Panel panel_6 = new Panel();
        config.add(panel_6);
        JLabel sl = new JLabel("Save Interval (milliseconds):    ");
        panel_6.add(sl);
        s = new JTextField(saveInt);
        panel_6.add(s);
        s.setColumns(10);

        //dnsenabled
        Panel panel_9 = new Panel();
        config.add(panel_9);
        JLabel dnsl = new JLabel("DNS Enabled:    ");
        panel_9.add(dnsl);
        String[] dnsS = { "true", "false" };
        dns = new JComboBox<Object>(dnsS);
        dns.setSelectedItem(dnse);
        dns.addActionListener(dns);
        panel_9.add(dns);


        //dnsmode
        Panel panel_10 = new Panel();
        config.add(panel_10);
        JLabel dnsml = new JLabel("DNS Server Mode:    ");
        panel_10.add(dnsml);
        String[] dnsm = { "local", "remote" };
        dnsmm = new JComboBox<Object>(dnsm);
        dnsmm.setSelectedItem(dnsmo);
        dnsmm.addActionListener(dnsmm);
        panel_10.add(dnsmm);

        JPanel panel_7= new JPanel();
        config.add(panel_7);
        save = new JButton("Save");
        panel_7.add(save);
        save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                errorCheck();       
            }
        });
    }

    public static void errorCheck(){
        interval = s.getText();
        dnsen = (String) dns.getSelectedItem();
        dnsm = (String) dnsmm.getSelectedItem();

        interval = checkValues(interval, "60000", "save interval");
        saveValues();
    }

    public static String checkValues(String value, String def, String name){
        String val;
        try{
            Long.parseLong(value);
            val = ""+value+"";
        }catch(NumberFormatException e){
            JOptionPane.showMessageDialog(null, "You did not enter a valid number for the "+ name + " field! It has been set to the default.");
            val = def;
        }
        return val;
    }

    public static void saveValues(){
        try {
                Properties props = new Properties();
                props.setProperty("saveInterval", interval);
                props.setProperty("serverMode", dnsm);
                props.setProperty("enableDns", dnsen);

                File f = new File("config.dedserver");
                OutputStream out = new FileOutputStream(f);
                props.store(out, "");

            JOptionPane.showMessageDialog(null, "Saved Config Values!");

            }
            catch (Exception e ) {
                e.printStackTrace();
                }

        }
}

For it to work you will also need to make a config.dedserver in the root of the project and add the following stuff into it:

#
#Thu Jul 09 08:29:33 BST 2015
saveMethod=h2
startingGems=9999999999
enableDns=true
startingGold=9999999999
startingDarkElixir=9999999999
startingElixir=9999999999
serverMode=remote
saveInterval=30000
maxNameChanges=100

For the entire ServerPanel.java code it is here: http://pastebin.com/tvBENHQa

I'm not sure why this isn't working. Does anyone have any ideas?

Thank you!


Answer:

Replace Panel with JPanel you are mixing awt Component with Swing that's causing the issue.

Swing components are "lightweight" (rendered by Java) while AWT components are "heavyweight" (implemented as components in the host platform) - this means you will have problems if you put AWT components inside Swing components (the other way round is fine)

//saveint
   // Panel panel_6 = new Panel();// replace as below
    JPanel panel_6 = new JPanel();

//dnsenabled
   // Panel panel_9 = new Panel();
   JPanel panel_9 = new JPanel();

//dnsmode
    //Panel panel_10 = new Panel();
    JPanel panel_10 = new JPanel();

And also remove action listener as said by @KDM

Question:

I want to creat a palet with many JComboBox. like that :

for(int x=0; x<MAX; x++){
    box[x] = new JComboBox(new String[]{"op1", "op2", "op3");
}

at the right of each JComboBox i want to create many JTextField. So, in my palet i will have some think like that:

myJComboBox1          myJTextField
                      anotherJTextField
                      anotherJTextField



myJComboBox2          myJTextField
                      anotherJTextField
                      anotherJTextField
...

How can i do that please ? I tried by setBounds and other layout like FlowLayout and GridLayout but without success.


Answer:

GridBagLayout is the best solution. However, if you are new to Swing, it might be a bit over complicated. In that case:

  1. Use GridLayout(0, 2) for the main panel.
  2. Wrap the combobox in a Panel with a border layout and add it to north. Add it to the main panel.
  3. Use another panel with GridLayout(0,1) add your text fields to it and add it to the main panel.

and loop...

Adding sample code:

package snippet;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class BorderLayoutTest extends JFrame {

    static private int MAX = 10 ;

    public BorderLayoutTest() {
        super(BorderLayoutTest.class.getName());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents();
    }

    private void initComponents() {
        setLayout(new GridLayout(0, 2));
        for(int i = 0; i < MAX; i++) {
            add(createComboPanel());
            add(createPanelWithTextFields());
        }
        pack();
    }

    public Component createComboPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JComboBox<>(new String[] { "First Option", "Second Option", "Third Option" }), BorderLayout.NORTH);
        return panel;
    }

    private Component createPanelWithTextFields() {
        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.add(new JTextField(30));
        panel.add(new JTextField(30));
        panel.add(new JTextField(30));
        return panel;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override public void run() {
                new BorderLayoutTest().setVisible(true);
            }
        });
    }

}

Question:

I've come across a very weird problem. I had a JPanel which contains JTextFields and JComboBoxes. I can change the JComboBox's when the JPanel loads but as soon as I touch or edit one of the JTextFields it doesn't let me change any of the combobox's...

Here is an MCVE that works. You can use it straight away and you'll see the error.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;


public class Main extends JFrame{

    private static JTextField s;
    private static JTabbedPane tabbedPane;
    private static JPanel config;
    private static JComboBox<Object> dns;
    private static JComboBox<Object> dnsmm;
    private static JButton save;
    private static String interval;
    private static String dnsen;
    private static String dnsm;
    private static JPanel server;
    static JPanel contentPane;

    public static void main(String[] args) throws InterruptedException {

            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        Main frame = new Main();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    }


    public Main() throws IOException {

        setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 655, 470);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(1, 1));
        setContentPane(contentPane);

        tabbedPane = new JTabbedPane(JTabbedPane.TOP);
        contentPane.add(tabbedPane, BorderLayout.CENTER);

        setResizable(false);

        server = new JPanel();
        server.setLayout(new BorderLayout(0, 0));

        ServerPanel();
    }

    public static void ServerPanel() throws IOException{ 

        tabbedPane.addTab("Manage Server", server);
        InputStream in = new FileInputStream("config.dedserver");
        Properties p = new Properties();
        p.load(in);
        in.close();
        String saveInt = p.getProperty("saveInterval");
        String dnse = p.getProperty("enableDns");
        String dnsmo = p.getProperty("serverMode");

        config = new JPanel();
        server.add(config, BorderLayout.CENTER);    
        config.setLayout(new BoxLayout(config, BoxLayout.PAGE_AXIS));


        //saveint
        Panel panel_6 = new Panel();
        config.add(panel_6);
        JLabel sl = new JLabel("Save Interval (milliseconds):    ");
        panel_6.add(sl);
        s = new JTextField(saveInt);
        panel_6.add(s);
        s.setColumns(10);

        //dnsenabled
        Panel panel_9 = new Panel();
        config.add(panel_9);
        JLabel dnsl = new JLabel("DNS Enabled:    ");
        panel_9.add(dnsl);
        String[] dnsS = { "true", "false" };
        dns = new JComboBox<Object>(dnsS);
        dns.setSelectedItem(dnse);
        dns.addActionListener(dns);
        panel_9.add(dns);


        //dnsmode
        Panel panel_10 = new Panel();
        config.add(panel_10);
        JLabel dnsml = new JLabel("DNS Server Mode:    ");
        panel_10.add(dnsml);
        String[] dnsm = { "local", "remote" };
        dnsmm = new JComboBox<Object>(dnsm);
        dnsmm.setSelectedItem(dnsmo);
        dnsmm.addActionListener(dnsmm);
        panel_10.add(dnsmm);

        JPanel panel_7= new JPanel();
        config.add(panel_7);
        save = new JButton("Save");
        panel_7.add(save);
        save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                errorCheck();       
            }
        });
    }

    public static void errorCheck(){
        interval = s.getText();
        dnsen = (String) dns.getSelectedItem();
        dnsm = (String) dnsmm.getSelectedItem();

        interval = checkValues(interval, "60000", "save interval");
        saveValues();
    }

    public static String checkValues(String value, String def, String name){
        String val;
        try{
            Long.parseLong(value);
            val = ""+value+"";
        }catch(NumberFormatException e){
            JOptionPane.showMessageDialog(null, "You did not enter a valid number for the "+ name + " field! It has been set to the default.");
            val = def;
        }
        return val;
    }

    public static void saveValues(){
        try {
                Properties props = new Properties();
                props.setProperty("saveInterval", interval);
                props.setProperty("serverMode", dnsm);
                props.setProperty("enableDns", dnsen);

                File f = new File("config.dedserver");
                OutputStream out = new FileOutputStream(f);
                props.store(out, "");

            JOptionPane.showMessageDialog(null, "Saved Config Values!");

            }
            catch (Exception e ) {
                e.printStackTrace();
                }

        }
}

For it to work you will also need to make a config.dedserver in the root of the project and add the following stuff into it:

#
#Thu Jul 09 08:29:33 BST 2015
saveMethod=h2
startingGems=9999999999
enableDns=true
startingGold=9999999999
startingDarkElixir=9999999999
startingElixir=9999999999
serverMode=remote
saveInterval=30000
maxNameChanges=100

For the entire ServerPanel.java code it is here: http://pastebin.com/tvBENHQa

I'm not sure why this isn't working. Does anyone have any ideas?

Thank you!


Answer:

A real MVCE would have been stripped down a lot further. It would also have included the properties instead of relying on an external file, e.g.

Properties p = new Properties();

p.put("saveMethod","h2");
p.put("startingGems","9999999999");
p.put("enableDns","true");
p.put("startingGold","9999999999");
p.put("startingDarkElixir","9999999999");
p.put("startingElixir","9999999999");
p.put("serverMode","remote");
p.put("saveInterval","30000");
p.put("maxNameChanges","100");

But apart from that, the code provided at least allowed us to reproduce the problem.

The problem is that you are mixing Swing components with AWT components. You have lines like

Panel panel_10 = new Panel();

in your program. Switch from a java.awt.Panel to a javax.swing.JPanel

JPanel panel_10 = new JPanel();

and your problem will be solved.

Question:

How do i set the value in jTextField when i click an Item in jComboBox? Like when i select Platinum in jComboBox the jTextField will display its value like 15% or Gold and set the jTextField to 10%

membox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {

    if(e.getStateChange() == ItemEvent.SELECTED) {

        jTextField6.setText((String) membox.getSelectedItem());
    }
}

});

im stuck here it only displays what i clicked in the jComboBox any help will be so much appreciated thank you in advance


Answer:

Create a class

public class ItemClass {
private String name;
private String value;

public ItemClass(String name1, String value1) {
    name = name1;
    value = value1; 
}

@Override
public String toString()
{
    return name;
}

public String getValue() {
    return value;
}
}

and add this code in yours...

    ItemClass oro = new ItemClass("gold","10%");
    ItemClass platino = new ItemClass("platinum","15%");
    JComboBox jc = new JComboBox();
    jc = membox;
    jc.addItem(oro);
    jc.addItem(platino);

membox.addItemListener(new ItemListener() {

@Override
public void itemStateChanged(ItemEvent e) {

    if(e.getStateChange() == ItemEvent.SELECTED) {
        Object obj=(Object) membox.getSelectedItem();
        ItemClass itemclass=(ItemClass)obj;
        String value = itemclass.getValue();
        jTextField6.setText(value);
    }
}

}); 

Question:

I want a JTextField to appear when user select "Extra" in JComboBox list and hidden otherwise. But the JTextField is not appearing when user is selecting "Extra" but it is appearing if i shrink the window and enlarge it again. After doing like that it is working properly, only for the first time it is not appearing. Why it is behaving like that? any solution for this?

Here is my code:

getCmbJtocsv_C_8().addActionListener(new ActionListener() { 
   public void actionPerformed(ActionEvent e) {
   {

      input3 = (String)adaptor.getCmbJtocsv_C_8().getSelectedItem();
      adaptor.getTxtJtocsv_C_8().setVisible(false);

      if(input3.equals("extra")){
          adaptor.getTxtJtocsv_C_8().setVisible(true);
      }
}

i have changed the string comparison and i'm still getting the same result.


Answer:

By default Swing components have a size of (0, 0). The size/location of a component is determined by the layout manager when the frame is packed or made visible.

So I would guess that since you start with the text field invisible the size of its parent panel does not include the text field. When you resize the frame the text field appears because its size and the size of the panel is recalculated.

Now the size of the text field has been calculated so you can toggle the visibility as required.

If this doesn't help then post a SSCCE that demonstrates the problem. That is create a frame with only a combo box and text field to demonstrate the problem. In the future all questions should contain a SSCCE since we can't guess the context of your application based on a few lines of code.

Question:

Please some one can told me why I don't have the JTextField in the same line with my JComboBox ? I need to have like that:

myJComboBox1      JTextField1
                  JTextField2
myJComboBox2      JTextField1
                  JTextField2

following this example

public class DisplayPanel extends JFrame {

    private JComboBox[] box;
JTextField[] field1, field2;

public DisplayPanel(){
    super(BorderLayoutTest.class.getName());
    setTitle("Simulation");
    setSize(1000,500);
    setResizable(false);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    createComponents();
    initComponents();
}

private void createComponents(){

    box = new JComboBox[3];
    field1 = new JTextField[4];
    field2 = new JTextField[5];     
}



private void initComponents(){
     setLayout(new GridLayout(0, 2));

     for(int i = 0; i < 3; i++) {
         JPanel panel = new JPanel(new BorderLayout());
         box[i] =new JComboBox<>(new String[] { "field1", "field2"});
         panel.add(box[i], BorderLayout.NORTH);
         add(panel);
         add(createPanelWithTextFields(panel));
         box[i].setSelectedIndex(-1);
         box[i].addActionListener(new CustomActionListener(box[i]));
        }

}

private Component createPanelWithTextFields(JPanel panel) {
  //need to keep the same layout as JComboBox
    panel.setLayout(new GridLayout(0, 1));

    for(int x=0; x<4; x++){
        field1[x] = new JTextField("field1 Name " + (x+1));
        field1[x].setVisible(false);   
        panel.add(field1[x]);
    }

    for(int x=0; x<5; x++){
        field2[x] = new JTextField("field2 Name " + (x+1));
        field2[x].setVisible(false);     
        panel.add(field2[x]);
    }

    return panel;
}


class CustomActionListener implements ActionListener {
    JComboBox b;

    public CustomActionListener(JComboBox u) {
        super();
        this.b = u;
    }

    public void actionPerformed(ActionEvent e) {
        int numChosen = b.getSelectedIndex() + 1;

        switch (numChosen){
        case 1:
            for(int x=0; x<4; x++)
                field1[x].setVisible(true);
            break;
        case 2:
            for(int x=0; x<5; x++)
                field2[x].setVisible(true);
            break;
        }

    }

}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override public void run() {
            new DisplayPanel().setVisible(true);
        }
    });
    }

Answer:

you are assigning new textfield to textfield array.but it contain only 4 textfields.but you call assigning more than 4 times.so what happening is last rextfield references get reassigning and you can't use them again.at the end of the the loop your field array contain reference to textfields of last panel.and that's why your see textfields on last panel even you select from combobox1.

how to fix ?

change this

 field1 = new JTextField[4];

to this

field1 = new JTextField[4 * 3];

and then you don't need to reassign jtextfields .you have 3 panels and you have 4 textfields for each panel.

same for field2

here is an example .

public class DisplayPanel extends JFrame {

    private JComboBox[] box;
    JTextField[] field1, field2;
    Color col[] = {Color.red, Color.GREEN, Color.blue};
    int i = 0;
    int counter = 0;
    private int boxcount;
    int field1counter = 0;
    int field2counter = 0;

    public DisplayPanel() {
        //super(BorderLayoutTest.class.getName());
        setTitle("Simulation");
        setSize(1000, 500);
        //setResizable(false);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        createComponents();
        initComponents();
    }

    private void createComponents() {

        boxcount = 3;
        box = new JComboBox[1 * boxcount];
        field1 = new JTextField[4 * boxcount];
        field2 = new JTextField[5 * boxcount];
    }

    private void initComponents() {
        setLayout(new GridLayout(0, 2));

        for (int i = 0; i < 3; i++) {
            JPanel panel = new JPanel(new BorderLayout());
            box[i] = new JComboBox<>(new String[]{"field1", "field2"});
            panel.add(box[i], BorderLayout.NORTH);
            add(panel);
            add(createPanelWithTextFields(panel));
            box[i].setSelectedIndex(-1);
            box[i].addActionListener(new CustomActionListener());
        }

    }

    private Component createPanelWithTextFields(JPanel panelc) {

        JPanel panel = new JPanel(new GridLayout(0, 1));
        panel.setBackground(col[i]);
        System.out.println("......................");
        for (int x = 0; x < 4; x++) {
            System.out.println("iterating .." + (field1counter) + "  counter  " + counter);
            field1[field1counter] = new JTextField("field1 Name " + (x + 1));
            field1[field1counter].setVisible(false);
            panel.add(field1[field1counter]);
            field1counter++;
        }

        for (int x = 0; x < 5; x++) {
            field2[field2counter] = new JTextField("field2 Name " + (x + 1));
            field2[field2counter].setVisible(false);
            panel.add(field2[field2counter]);
            field2counter++;
        }
        i++;
        counter++;
        return panel;
    }

    class CustomActionListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            JComboBox b = (JComboBox) e.getSource();
            int comboidenty = 0;
            for (int k = 0; k < box.length; k++) {
                if (box[k] == b) {
                    break;
                }
                comboidenty++;
            }
            System.out.println(((JPanel) (b.getParent())).getBackground());
            int numChosen = b.getSelectedIndex() + 1;

            System.out.println("hi " + comboidenty);
            switch (numChosen) {
                case 1:
                    for (int x = 0; x < 4; x++) {
                        System.out.println("field1  " + (comboidenty * 4 + x));
                        field1[comboidenty * 4 + x].setVisible(true);
                    }
                    break;
                case 2:
                    for (int x = 0; x < 5; x++) {
                        System.out.println("field2  " + (comboidenty * 5 + x));
                        field2[comboidenty * 5 + x].setVisible(true);
                    }
                    break;
            }

        }

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DisplayPanel().setVisible(true);
            }
        });

    }
}

Question:

I'm trying to retrieve data from the database and set jTextFields automatically.

Ive managed to retrieve the table column for the Name and set it to the combobox.

But now I want everything related to the selected item to show up automatically in the jTextfields.

I tried the following code but have an error on setString not being recognised:

    private void jComboBox1PopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {                                                        
        String tmp = (String)jComboBox1.getSelectedItem();
        String SQL = "select * from ROOT.\"Books\" WHERE Name=?";

         try{
    String host = "jdbc:derby://localhost:1527/books";
    String userName = "root";
    String Pass = "1234";
    Connection con = DriverManager.getConnection(host, userName, Pass); 
    Statement stmnt = (Statement) con.createStatement();
    stmnt.setString(1, tmp);
     ResultSet rs = stmnt.executeQuery(SQL);

     if (rs.next()) 
        {
            String add1 = rs.getString("Year");
            jTextField1.setText(add1);
            String add2 = rs.getString("Price");
            jTextField2.setText(add2);
        }

} catch (Exception e) {
    e.printStackTrace();
}
    }    

Answer:

The only thing I can say, is don't use a PoupMenuListener.

You should be using and ActionLIstener or an ItemListener to handle the event when the user make a selection from the combo box.

Read the section from the Swing tutorial on How to Use Combo Boxes for more information and working examples.

Question:

I have a main JFrame pane using Swing in Java with a JComboBox embedded in it with a number of selections.

Everything initiates well on opening but when I write inside the JTextField, the words in the JComboBox disappear.

I'm initiating my JComboBox in in the following way:

private static String[] options = new String[] {"Search your own pasted text" ,  "Search your own file", 
        "Search website", "Search Lyric Database", "Search Books Database"};
private static JComboBox<String> bookList = new JComboBox<>(options);

Then I initiate the JTextField in this way

private static JTextField textFieldTheme = new JTextField(50); 
private static String theme = textFieldTheme.getText();

Have no idea why they interfere with each other....everything works fine still. In fact, I can stick click the the JComboBox menu, its just that it resizes and the words disappear from it


Answer:

Per above code you wrote, all looks fine. Maybe better to add also your main frame code to see how you adding the components.

Anyway you can follow instructions How to Use Text Fields

Question:

I have a table, and I want to search/filter in it by using a JTextField. I have the code to do that, and it is working.

Now, what I want to do is, by a JComboBox, select for what Column I want to search and show me the entire rows with what I searched.

This is the code I got so far:

private  void Filtro(String query){
     DefaultTableModel modelo = (DefaultTableModel) TabelaPessoal.getModel();
     TableRowSorter<DefaultTableModel> pesquisa = new TableRowSorter<DefaultTableModel>(modelo);
     TabelaPessoal.setRowSorter(pesquisa); 

     pesquisa.setRowFilter(RowFilter.regexFilter(query));             
 }

private void txt_pesquisaKeyReleased(java.awt.event.KeyEvent evt) {                                         
    String query = txt_pesquisa.getText().toLowerCase();
    Filtro(query);
} 

How I can do that?


Answer:

Try this below code

public class ColumnName {
    public String columnName;
    public int columnIndex;

    public ColumnName( String columnName, int columnIndex ) {
        this.columnName = columnName;
        this.columnIndex = columnIndex;
    }

    public String getColumnName() {
        return columnName;


    public String toString() {
        return columnName;
    }

    public int getColumnIndex() {
        return columnIndex;
    }
}

public JComboBox createComboBox( TableModel model ) {
    int count = model.getColumnCount();
    Object[] items = new Object[count];
    for( int i = 0 ;i < count;i++ ) {
        String columName = model.getColumnName(i);
        items[i] = new ColumnName( columName,i);
    }
    return new JComboBox(items);
}

JComboBox columnCombo = createComboBox( TabelaPessoal.getModel() );

private  void Filtro(String query){
    DefaultTableModel modelo = (DefaultTableModel) TabelaPessoal.getModel();
    TableRowSorter<DefaultTableModel> pesquisa = new 
    TableRowSorter<DefaultTableModel>(modelo);
    TabelaPessoal.setRowSorter(pesquisa); 

    ColumnName columnName = ( ColumnName  ) columnCombo.getSelectedItem();
    pesquisa.setRowFilter( RowFilter.regexFilter(query, columnName.getColumnIndex() ) );             
}

Question:

I have tried to use the suggested methods but unable to determine how I can use action listeners within an action listener as suggested...

I want to change the value of first combo box and want the next combo box to be updated automatically upon change, similarly text box is changed when combobox_1 is changed...

    String[] b = a.getCourseCodes();
    final List f = new ArrayList();

    final JComboBox comboBox = new JComboBox(b);
    comboBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            String item = comboBox.getSelectedItem().toString();
         }
    });

    comboBox.setEditable(true);

    comboBox.setBounds(360, 70, 86, 20);
    contentPane.add(comboBox);

    JLabel lblStudentName = new JLabel("Student Name");
    lblStudentName.setBounds(270, 149, 80, 14);
    contentPane.add(lblStudentName);

    String[] v = a.getStudentID(comboBox.getSelectedItem().toString());
    final JComboBox comboBox_1 = new JComboBox(v);
    comboBox_1.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            String item = comboBox_1.getSelectedItem().toString();
         }
    });

    comboBox_1.setBounds(360, 108, 86, 20);
    contentPane.add(comboBox_1);

    textField_3 = new JTextField();
    String y = a.getStudentName(comboBox_1.getSelectedItem().toString());
    textField_3.setText(y);
    textField_3.setEditable(false);
    textField_3.setBounds(360, 146, 86, 20);
    contentPane.add(textField_3);
    textField_3.setColumns(10);

Kindly help by editing the code so can have a clear idea... Thanks


Answer:

Rather then adding an ItemListener I would simply add an ActionListener which will be triggered every time the selected value is changed. Then you are able to just use comboBox.getSelectedItem() like so:

JComboBox comboBox_1; //you need to declare the comboBox and textField before the ActionListener.
comboBox.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        String[] v = a.getStudentID(comboBox.getSelectedItem().toString());
        comboBox_1.setModel(new DefaultComboBoxModel<String>(v));

        String y = a.getStudentName(comboBox_1.getSelectedItem().toString());
        textField_3.setText(y);
    }
});

Add you could extend this to change the values of your ComboBox or TextField within the actionPerformed method.

I think this is what you mean, though I may be wrong in the intent of your ActionListener.