Java 组合框上的操作侦听器在文本字段中显示所选内容

Java 组合框上的操作侦听器在文本字段中显示所选内容,java,swing,combobox,Java,Swing,Combobox,我有一个包含选项的组合框。我正在尝试应用actionListener在文本字段上显示选定的字符串。我不知道如何完成这一点,我所读到的一切让我更加困惑 以下是组合框的代码: JComboBox comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(new String[] {"Select Something", "Selection 1", "Selection 2", "Selection

我有一个包含选项的组合框。我正在尝试应用actionListener在文本字段上显示选定的字符串。我不知道如何完成这一点,我所读到的一切让我更加困惑

以下是组合框的代码:

JComboBox comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(new String[] {"Select Something", "Selection 1", "Selection 2", "Selection 3", "Selection 4"}));
        panelTop.add(comboBox);
        comboBox.setPreferredSize(new Dimension(160, 20));
        comboBox.addItem("Select Something");
文本字段代码:

textField = new JTextField();
        panelTop.add(textField);
        textField.setColumns(40);
到目前为止,我对actionListener的了解:

public void actionPerformed(ActionEvent e) {
            JComboBox comboBox = (JComboBox)e.getSource();
            String newSelection = (String)comboBox.getSelectedItem();
            currentPattern = newSelection;

        }
完整代码:

package SwingAssign2;

import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;

import java.awt.BorderLayout;

import javax.swing.JComboBox;
import javax.swing.JTextField;

import java.awt.FlowLayout;

import javax.swing.SwingConstants;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.DefaultComboBoxModel;

public class SwingAssign2 {

    private JFrame frame;
    private JTextField textField;

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

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

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setSize(600, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panelTop = new JPanel();
        FlowLayout fl_panelTop = (FlowLayout) panelTop.getLayout();
        fl_panelTop.setAlignment(FlowLayout.LEFT);
        frame.getContentPane().add(panelTop, BorderLayout.NORTH);
        //panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

        final JComboBox comboBox = new JComboBox();
        comboBox.setModel(new DefaultComboBoxModel(new String[] {"Select Something", "Selection 1", "Selection 2", "Selection 3", "Selection 4"}));
        panelTop.add(comboBox);
        comboBox.setPreferredSize(new Dimension(160, 20));
        comboBox.addItem("Select Something");


        textField = new JTextField();
        panelTop.add(textField);
        textField.setColumns(40);

        JPanel panelBottom = new JPanel();
        frame.getContentPane().add(panelBottom, BorderLayout.SOUTH);
        panelBottom.setLayout(new BorderLayout(0, 0));

        JLabel status = new JLabel("Status");
        status.setHorizontalAlignment(SwingConstants.CENTER);
        panelBottom.add(status, BorderLayout.SOUTH);
        status.setBorder(BorderFactory.createLoweredBevelBorder());

        JTextPane txtpnSomeContentOn_B = new JTextPane();
        txtpnSomeContentOn_B.setText("Some content on the bottom panel\r\nMore content\r\nSome more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content");
        JScrollPane jScrollPane3 = new JScrollPane(txtpnSomeContentOn_B);
        jScrollPane3.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane3.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        panelBottom.add(jScrollPane3, BorderLayout.NORTH);
        jScrollPane3.setPreferredSize(new Dimension(200, 200));
        //bText.setBorder(BorderFactory.createLoweredBevelBorder());

        JPanel panelCenter = new JPanel();
        frame.getContentPane().add(panelCenter, BorderLayout.CENTER);
        panelCenter.setLayout(new GridLayout(0, 2, 0, 0));

        JTextPane txtpnSomeContentOn_0 = new JTextPane();
        txtpnSomeContentOn_0.setText("Some content on the left panel\r\nMore content\r\nSome more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content");
        JScrollPane jScrollPane1 = new JScrollPane(txtpnSomeContentOn_0);
        jScrollPane1.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        panelCenter.add(jScrollPane1);

        JTextPane txtpnSomeContentOn = new JTextPane();
        txtpnSomeContentOn.setText("Some content on the right panel\r\nMore content\r\nSome more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content\r\nMore and more content");
        JScrollPane jScrollPane2 = new JScrollPane(txtpnSomeContentOn);
        jScrollPane2.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane2.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        panelCenter.add(jScrollPane2);

        comboBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(e.getStateChange() == ItemEvent.SELECTED) {
                    textField.setText((String) comboBox.getSelectedItem());
                }
            }
        });


    }

}

考虑将
itemstener
添加到
JComboBox
并检查
ItemEvent
状态是否为
ItemEvent.SELECTED
。您可以在
itemStateChanged
方法中设置文本字段的文本:

comboBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {
            textField.setText((String) comboBox.getSelectedItem());
        }
    }
});

考虑将
itemstener
添加到
JComboBox
并检查
ItemEvent
状态是否为
ItemEvent.SELECTED
。您可以在
itemStateChanged
方法中设置文本字段的文本:

comboBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {
            textField.setText((String) comboBox.getSelectedItem());
        }
    }
});

你在正确的轨道上。我不确定您现有的actionListener的上下文是什么,但有一种方法可以做到这一点:

comboBox.addItemListener(new ItemListener() {
   @Override
   public void itemStateChanged(ItemEvent arg0) { // picks up changes to combobox selection
      if (arg0.getStateChange() == ItemEvent.SELECTED) {
         String newSelection = comboBox.getSelectedItem(); // takes the selected item
         textField.setText(newSelection); // publishes to the textfield
      }
   }
});

你在正确的轨道上。我不确定您现有的actionListener的上下文是什么,但有一种方法可以做到这一点:

comboBox.addItemListener(new ItemListener() {
   @Override
   public void itemStateChanged(ItemEvent arg0) { // picks up changes to combobox selection
      if (arg0.getStateChange() == ItemEvent.SELECTED) {
         String newSelection = comboBox.getSelectedItem(); // takes the selected item
         textField.setText(newSelection); // publishes to the textfield
      }
   }
});
我正在尝试应用actionListener在文本字段上显示所选字符串

JComboBox
上添加
ActionListener
JTextField
中添加并设置文本

示例代码:

final JTextField jTextField = new JTextField();

final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] { 
    "Select Something", "Selection 1", "Selection 2",   
    "Selection 3", "Selection 4" }));

// set first one selected
comboBox.setSelectedIndex(0);

comboBox.addActionListener(new ActionListener() {
    
    @Override
    public void actionPerformed(ActionEvent ae) {
        // check whether there is any selection
        if(comboBox.getSelectedIndex()!=-1){
            jTextField.setText(comboBox.getSelectedItem().toString());
        }
    }
});
我正在尝试应用actionListener在文本字段上显示所选字符串

JComboBox
上添加
ActionListener
JTextField
中添加并设置文本

示例代码:

final JTextField jTextField = new JTextField();

final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setModel(new DefaultComboBoxModel<String>(new String[] { 
    "Select Something", "Selection 1", "Selection 2",   
    "Selection 3", "Selection 4" }));

// set first one selected
comboBox.setSelectedIndex(0);

comboBox.addActionListener(new ActionListener() {
    
    @Override
    public void actionPerformed(ActionEvent ae) {
        // check whether there is any selection
        if(comboBox.getSelectedIndex()!=-1){
            jTextField.setText(comboBox.getSelectedItem().toString());
        }
    }
});

在组合框中添加一个
ActionListener
,其中覆盖
actionPerformed
方法。请参见下面的工作示例

import java.awt.EventQueue;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JTextFieldTest extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

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

    /**
     * Create the frame.
     */
    public JTextFieldTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 298, 220);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        Vector<String> comboBoxItems=new Vector();
        comboBoxItems.add("A");
        comboBoxItems.add("B");
        comboBoxItems.add("C");
        final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
        final JComboBox comboBox = new JComboBox(model);
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {//here your actionPerformed method
                textField.setText((String) comboBox.getSelectedItem());
            }
        });

        textField = new JTextField();
        textField.setColumns(10);
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_contentPane.createSequentialGroup()
                            .addGap(110)
                            .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                        .addGroup(gl_contentPane.createSequentialGroup()
                            .addGap(83)
                            .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(103, Short.MAX_VALUE))
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGap(37)
                    .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGap(18)
                    .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(76, Short.MAX_VALUE))
        );
        contentPane.setLayout(gl_contentPane);
    }

}
导入java.awt.EventQueue;
导入java.util.Vector;
导入javax.swing.DefaultComboxModel;
导入javax.swing.GroupLayout;
导入javax.swing.GroupLayout.Alignment;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.JTextField;
导入javax.swing.border.EmptyBorder;
导入javax.swing.JComboBox;
导入java.awt.event.ActionListener;
导入java.awt.event.ActionEvent;
公共类JTextFieldTest扩展了JFrame{
私有JPanel内容窗格;
私有JTextField textField;
/**
*启动应用程序。
*/
公共静态void main(字符串[]args){
invokeLater(新的Runnable(){
公开募捐{
试一试{
JTextFieldTest帧=新的JTextFieldTest();
frame.setVisible(true);
}捕获(例外e){
e、 printStackTrace();
}
}
});
}
/**
*创建框架。
*/
公共JTextFieldTest(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
立根(100100298220);
contentPane=newjpanel();
setboorder(新的EmptyBorder(5,5,5,5));
setContentPane(contentPane);
Vector comboBoxItems=新向量();
comboBoxItems。添加(“A”);
comboBoxItems。添加(“B”);
comboBoxItems。添加(“C”);
最终DefaultComboxModel=新的DefaultComboxModel(comboBoxItems);
最终JCOMBOX组合框=新的JCOMBOX(型号);
comboBox.addActionListener(新ActionListener(){
public void actionPerformed(ActionEvent arg0){//这里是您的actionPerformed方法
textField.setText((字符串)comboBox.getSelectedItem());
}
});
textField=新的JTextField();
textField.setColumns(10);
GroupLayout gl_contentPane=新的GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(110)
.addComponent(组合框、GroupLayout.PREFERRED\u大小、GroupLayout.DEFAULT\u大小、GroupLayout.PREFERRED\u大小))
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(83)
.addComponent(textField,GroupLayout.PREFERRED\u SIZE,GroupLayout.DEFAULT\u SIZE,GroupLayout.PREFERRED\u SIZE)))
.addContainerGap(103,简称最大值))
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGap(37)
.addComponent(组合框、GroupLayout.PREFERRED\u大小、GroupLayout.DEFAULT\u大小、GroupLayout.PREFERRED\u大小)
.addGap(18)
.addComponent(文本字段、GroupLayout.PREFERRED\u大小、GroupLayout.DEFAULT\u大小、GroupLayout.PREFERRED\u大小)
.addContainerGap(76,简称最大值))
);
contentPane.setLayout(gl_contentPane);
}
}

向组合框中添加一个
ActionListener
,其中覆盖
actionPerformed
方法。请参见下面的工作示例

import java.awt.EventQueue;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JTextFieldTest extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

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

    /**
     * Create the frame.
     */
    public JTextFieldTest() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 298, 220);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);

        Vector<String> comboBoxItems=new Vector();
        comboBoxItems.add("A");
        comboBoxItems.add("B");
        comboBoxItems.add("C");
        final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
        final JComboBox comboBox = new JComboBox(model);
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {//here your actionPerformed method
                textField.setText((String) comboBox.getSelectedItem());
            }
        });

        textField = new JTextField();
        textField.setColumns(10);
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
                        .addGroup(gl_contentPane.createSequentialGroup()
                            .addGap(110)
                            .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                        .addGroup(gl_contentPane.createSequentialGroup()
                            .addGap(83)
                            .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(103, Short.MAX_VALUE))
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addGap(37)
                    .addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGap(18)
                    .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(76, Short.MAX_VALUE))
        );
        contentPane.setLayout(gl_contentPane);
    }

}
导入java.awt.EventQueue;
导入java.util.Vector;
导入javax.swing.DefaultComboxModel;
导入javax.swing.GroupLayout;
导入javax.swing.GroupLayout.Alignment;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.JTextField;
导入javax.swing.border.EmptyBorder;
导入javax.swing.JComboBox;
导入java.awt.event.ActionListener;
导入java.awt.event.ActionEvent;
公共类JTextFieldTest扩展了JFrame{
私有JPanel内容窗格;
私有JTextField textField;
/**
*启动应用程序。
*/
公共静态void main(字符串[]args){
invokeLater(新的Runnable(){
公开募捐{
T