简体   繁体   中英

Java Swing - How make a component either a Combobox or a JtextField

Please bear with me but I am very new to Java swing and have literally spent days trying to figure this out. I have a Frame with two panels. The first panel has two buttons ("I am simplifying"): "New" and "Open". The second panel displays an empty JCombobox when the frame initially appears, the JCombobox is setEnable(false). The intention is to have the user select either "New" or "Open" and the component in the second panel either convert to a JTextField, if the user presses "New" or remain as a JComboBox if the user presses Open. The items of the JComboBox is populated from a database, populating the Combobox is working. My problem is trying figure out how to convert the component in the second panel to be either JTextField or JCombobox. I tried making the combobox look like a JTextField by using removeallItems and setting setPopupVisible to false, but that does not seem to work. I keep getting a component with a pulldown arrow, which when clicked on displays a single empty row, which looks strange. I want to inhibit the pulldown from displaying an empty row, or convert the component to a simple JTextField. Any help would really be apprepriated.

    public class newButtonlistener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    clearFields();
    newButton.setEnabled(false);
    openButton.setEnabled(false);
    calcButton.setEnabled(false);
    tableButton.setEnabled(false);
    saveButton.setEnabled(false);
    textField1.setBackground(Color.WHITE);
    textField2.setBackground(Color.WHITE); 
    textField3.setBackground(Color.WHITE);
    setDisable(textField2);
    textField3.setEnabled(false);
    table.setEnabled(false);
    textField1.setEnabled(true);
    textField1.removeAllItems();
    textField1.setPopupVisible(false);
    BasicComboPopup popup = new BasicComboPopup( textField1 );
    popup.setPopupSize(0, 0);

    textField1.setEditable(true);
    textField1.requestFocus();
    }

        }

Use composition. Have a JTextField and a JComboBox in a JPanel that uses the CardLayout (and, thus, only shows one at a time). When it's time to switch, tell the layout of the panel to switch the displayed component.

Use the secondPanel

    // first proposition
    // I suppose the secondPanel contains the combobox
    secondPanel.removeAll();
    secondPanel.add(new JTextField());
    // and vice-versa

    //second proposition
    // they are both in secondPanel: toogle
    combobox.setVisible(true);
    textfield.setVisible(false);
    //and vice-versa

I think this is fairly close. I used GroupLayout for the individual JPanel cards. The only thing I cannot figure out is how to stop the components from resizing when resizing the frame. Any suggestions I would be appreciated.

    import java.awt.BorderLayout;
    import java.awt.CardLayout;
    import java.awt.Container;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import static javax.swing.GroupLayout.Alignment.BASELINE;
    import static javax.swing.GroupLayout.Alignment.LEADING;
    import java.awt.Dimension;

    public class dataTableSummaryCards implements ItemListener {
    JPanel cards; //a panel that uses CardLayout
    final static String OPENPANEL = "Open";
    final static String NEWPANEL = "New";

   public void addComponentToPane(Container pane) {
    //Put the JComboBox in a JPanel to get a nicer look.


    JPanel comboBoxPane = new JPanel(); //use FlowLayout
    String comboBoxItems[] = { OPENPANEL, NEWPANEL };
    JComboBox cb = new JComboBox(comboBoxItems);
    cb.setEditable(false);
    cb.addItemListener(this);
    comboBoxPane.add(cb);

    //Create the "cards"



    JComboBox openDataSummary = new JComboBox();
    Dimension dim=openDataSummary.getSize();
    //        openDataSummary.setMaximumSize(dim);
    openDataSummary.setPreferredSize(dim);
    openDataSummary.setMinimumSize(dim);


    JLabel label1 = new JLabel("Data Summary Name:");
    JLabel label2 = new JLabel("Data Summary Name:");
    JPanel openCard = new JPanel();
    GroupLayout layout = new GroupLayout(openCard);
    openCard.setLayout(layout);

    layout.setAutoCreateGaps(true);
    layout.setAutoCreateContainerGaps(true); 
    layout.setHorizontalGroup(layout.createSequentialGroup()  
        .addGroup(layout.createParallelGroup(LEADING)
            .addComponent(label1,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE                     ,GroupLayout.DEFAULT_SIZE))
        .addGroup(layout.createParallelGroup(LEADING)
            .addComponent(openDataSummary,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE))
    );

    layout.setVerticalGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup()    
            .addComponent(label1,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE)
            .addComponent(openDataSummary,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAU LT_SIZE,GroupLayout.DEFAULT_SIZE)))
        ;


     JTextField newDataSummary = new JTextField();
    newDataSummary.setSize(dim);
    newDataSummary.setPreferredSize(dim);
    //       newDataSummary.setMaximumSize(dim);
    newDataSummary.setMinimumSize(dim);
    JPanel newCard = new JPanel();
    GroupLayout layout2 = new GroupLayout(newCard);
    newCard.setLayout(layout2);

    layout2.setAutoCreateGaps(true);
    layout2.setAutoCreateContainerGaps(true); 
    layout2.setHorizontalGroup(layout2.createSequentialGroup()  
        .addGroup(layout2.createParallelGroup(LEADING)
            .addComponent(label2,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE))
        .addGroup(layout2.createParallelGroup(LEADING)
            .addComponent(newDataSummary,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.DEFAULT_SIZE))
    );

    layout2.setVerticalGroup(layout2.createSequentialGroup()
        .addGroup(layout2.createParallelGroup()    
            .addComponent(label2,GroupLayout.PREFERRED_SIZE,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE)
            .addComponent(newDataSummary,GroupLayout.PREFERRED_SIZE,GroupLayout.DEFAULT_SIZE,GroupLayout.DEFAULT_SIZE)))
        ;


    //Create the panel that contains the "cards".
    cards = new JPanel(new CardLayout());
    cards.add(openCard, OPENPANEL);
    cards.add(newCard, NEWPANEL);

    pane.add(comboBoxPane, BorderLayout.PAGE_START);
    pane.add(cards, BorderLayout.CENTER);

    }

    public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
    }

     /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Data Summary Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);





    //Create and set up the content pane.
    dataTableSummaryCards demo = new dataTableSummaryCards();
    demo.addComponentToPane(frame.getContentPane());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
    }

    public static void main(String[] args) {
    /* Use an appropriate Look and Feel */
    try {
        //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    } catch (UnsupportedLookAndFeelException ex) {
        ex.printStackTrace();
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
    } catch (InstantiationException ex) {
        ex.printStackTrace();
    } catch (ClassNotFoundException ex) {
        ex.printStackTrace();
    }
    /* Turn off metal's use of bold fonts */
    UIManager.put("swing.boldMetal", Boolean.FALSE);

    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM