简体   繁体   English

Java Swing-如何使组件成为Combobox或JtextField

[英]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. 请耐心等待,但是我对Java swing非常陌生,并且花了数天时间试图弄清楚这一点。 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). 当框架最初出现时,第二个面板显示一个空的JCombobox,JCombobox为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. 目的是让用户选择“新建”或“打开”,如果用户按下“新建”,第二个面板中的组件将转换为JTextField,或者如果用户按下“打开”,则保留为JComboBox。 The items of the JComboBox is populated from a database, populating the Combobox is working. JComboBox的项目是从数据库中填充的,正在填充Combobox。 My problem is trying figure out how to convert the component in the second panel to be either JTextField or JCombobox. 我的问题是尝试弄清楚如何将第二个面板中的组件转换为JTextField或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. 我尝试通过使用removeallItems并将setPopupVisible设置为false来使组合框看起来像JTextField,但这似乎不起作用。 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. 我想禁止下拉菜单显示空行,或将组件转换为简单的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). 在使用CardLayout的JPanel中有一个JTextField和JComboBox(因此,一次只显示一个)。 When it's time to switch, tell the layout of the panel to switch the displayed component. 当需要切换时,告诉面板布局以切换显示的组件。

Use the secondPanel 使用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. 我将GroupLayout用于单个JPanel卡。 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();
        }
    });
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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