How can I add text to combobox from textfield? - java

I want to create a combobox and a textbox. And user will enter a text into the textbox, and the text will be added as an item of combobox.
How can I do it? I wrote a code, but I couldn't find what will I write in actionlistener.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox = new JComboBox();
public Q2() {
t = new JTextField("Enter text here", 20);
t.setEditable(true);
t.addActionListener(new act());
add(t);
add(combobox);
combobox.addItem(t.getText().toString());
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}

I added a button, and put the functionality on adding to the JComboBox on the button. Here's an example:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Q2 extends JFrame {
JTextField t;
JComboBox combobox;
JButton b;
public Q2() {
combobox = new JComboBox();
t = new JTextField("Enter text here", 20);
t.setEditable(true);
b = new JButton("Add");
b.addActionListener(new act()); //Add ActionListener to button instead.
add(t);
add(combobox);
add(b);
//combobox.addItem(t.getText().toString()); //Moved to ActionListener.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public class act implements ActionListener {
public void actionPerformed(ActionEvent e) {
combobox.addItem(t.getText()); //Removed .toString() because it returns a string.
}
}
public static void main(String[] args) {
Q2 test = new Q2();
}
}

private JTextComponent comboboxEditor;
Vector ComboData = new Vector();
public void addActionListners() {
//adding action listner to the NameComboBox
this.comboboxEditor = (JTextComponent) yourCombo.getEditor().getEditorComponent();
comboboxEditor.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent evt) {
int i = evt.getKeyCode();
if (i == 10) {
//combobox action on enter
ComboData.add(comboboxEditor.getText());
yourCombo.setListData(ComboData);
}
}
});
}
you have to set your editable property in comboBox to true otherwise you wont able to write on comboBox. make sure you call addActionListners() method
at the startup(constructor). i am giving the combobox the functionality of a jtext field by changing the editor of the combobox to jtextComponent. try this example

Related

getting the same ActionEvent to both adding and choosing a item in comboBox java

I have ActionListener to my Jcombobox which needs to add a new row in a table when choosing an item from the comboBox,
unfortunately, i have also an option to insert a new item to the same comboBox.
my problem is that both action have the same action event "comboBoxChanged"
here some of the code:
cmbAllMovies.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Movie movie = (Movie) cmbAllMovies.getSelectedItem();
Object [] rowData= {movie.getName(),movie.getYear(),movie.getlanguage()};
tblModel.addRow(rowData);
}
});
thanks ,
Disclaimer: Your question is kind of unclear, so the answer is based on my personal guess which is, you do not want the action listener of the combobox to be fired when you add new elements in it.
The solution is to remove the action listener of the combobox the moment you add new element in it and then restore/re-add the action listener.
SSCCE:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test extends JFrame implements ActionListener {
private JComboBox<String> comboBox;
public Test() {
super("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
String[] movies = { "Rambo 1", "Rocky 1", "Fargo", };
comboBox = new JComboBox<>(movies);
comboBox.addActionListener(this);
JTextField textField = new JTextField(10);
JButton button = new JButton("Add movie");
button.addActionListener(e -> {
String selectedMovie = textField.getText();
comboBox.removeActionListener(this);// Remove the action listener
comboBox.addItem(selectedMovie); // Add the movie without any action listener
comboBox.addActionListener(this); // Restore action listener
});
add(comboBox);
add(textField);
add(button);
setSize(300, 300);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Test().setVisible(true);
});
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(comboBox.getSelectedItem() + " is a great movie.");
}
}

How to make my button do something in a BoxLayout?

I made a BoxLayout GUI and i'm wondering how i'd use an actionlistener to make the button close the window. If I try to put in RegisterNew.setVisible(false); in an actionlistener, it gives me an error
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RegisterNew extends JFrame
{
public RegisterNew(int axis){
// creates the JFrame
super("BoxLayout Demo");
Container con = getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(new JTextField());
con.add(new JLabel("Enter your password"));
con.add(new JTextField());
con.add(new JButton("Create Account"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[])
{
RegisterNew newDemo = new RegisterNew(BoxLayout.Y_AXIS);
}
}
I'm also trying to link this to ANOTHER GUI so that when you press a button, this one appears, but it gives me the same error as if i put
RegisterNew.setVisible(true); into the action listener
If that's a subordinate dialog window, then use a JDialog, not a JFrame.
If your ActionListener is an inner class then use RegisterNew.this.close();
Else you can get the window ancestor for the JButton using SwingUtilities.getWindowAncestor(button) and call close() or better dispose() on the Window returned.
Note that BoxLayout and layout managers in general have nothing to do with your current problem.
e.g.,
Test class that shows the new register dialog and that extracts information from it.
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestRegistration extends JPanel {
private JTextArea textArea = new JTextArea(30, 60);
public TestRegistration() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ShowRegisterNewAction()));
textArea.setFocusable(false);
textArea.setEditable(false);
setLayout(new BorderLayout());
add(new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
add(bottomPanel, BorderLayout.PAGE_END);
}
private class ShowRegisterNewAction extends AbstractAction {
private RegisterNew registerNew = null;
public ShowRegisterNewAction() {
super("Show Register New Dialog");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
if (registerNew == null) {
JButton btn = (JButton) e.getSource();
Window window = SwingUtilities.getWindowAncestor(btn);
registerNew = new RegisterNew(window, BoxLayout.PAGE_AXIS);
}
registerNew.setVisible(true);
String userName = registerNew.getUserName();
String password = new String(registerNew.getPassword());
textArea.append("User Name: " + userName + "\n");
textArea.append("Password: " + password + "\n");
textArea.append("\n");
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestRegistration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestRegistration());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
New Register class that holds the dialog and has code for displaying it and for extracting information from it. Uses BoxLayout.
import java.awt.Container;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class RegisterNew {
private JDialog dialog = null;
private JTextField nameField = new JTextField(10);
private JPasswordField passField = new JPasswordField(10);
public RegisterNew(Window window, int axis) {
dialog = new JDialog(window, "Register New", ModalityType.APPLICATION_MODAL);
Container con = dialog.getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(nameField);
con.add(new JLabel("Enter your password"));
con.add(passField);
con.add(new JButton(new AcceptAction()));
dialog.pack();
dialog.setLocationRelativeTo(window);
}
public char[] getPassword() {
return passField.getPassword();
}
public String getUserName() {
return nameField.getText();
}
public void setVisible(boolean b) {
dialog.setVisible(b);
}
private class AcceptAction extends AbstractAction {
public AcceptAction() {
super("Accept");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
}
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
}
}

Java Swing method addActionListener error

I am new to Java and trying to create a simple Swing program with two buttons, but I'm getting an error with addActionListener.
public class swingEx1
{
JFrame f;
JPanel p;
JLabel l;
JButton b1,b2;
public swingEx1()
{
f = new JFrame("Swing Example");
p = new JPanel();
l = new JLabel("Initial Label");
b1 = new JButton("Clear");
b2 = new JButton("Copy");
}
public void launchFrame()
{
p.add(b1,BorderLayout.SOUTH);
p.add(b2,BorderLayout.EAST);
p.add(l,BorderLayout.NORTH);
p.setSize(200,300);
f.getContentPane().add(p);
b1.addActionListener(new ClearButton());
b2.addActionListener(new CopyButton());
f.pack();
f.setVisible(true);
}
public static void main(String args[])
{
swingEx1 swObj1 = new swingEx1();
swObj1.launchFrame();
}
}
class ClearButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button b1 = (Button) e.getSource();
b1.setLabel("It it Clear Button");
}
}
class CopyButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Button b2 = (Button) e.getSource();
b2.setLabel("It it Copy Button");
}
}
Line b1.addActionListener(new ClearButton()) produces error:
The method addActionListener(ActionListener) in the type
AbstractButton is not applicable for the arguments (ClearButton)
Line b2.addActionListener(new CopyButton()) produces error:
The method addActionListener(ActionListener) in the type
AbstractButton is not applicable for the arguments (CopyButton)
In your two inner classes you should be using JButton and you are using Button. This is probably why you are getting your exception. I ran your code with the recommended changes and I got no error.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class swingEx1 {
JFrame f;
JPanel p;
JLabel l;
JButton b1, b2;
public swingEx1() {
f = new JFrame("Swing Example");
p = new JPanel();
l = new JLabel("Initial Label");
b1 = new JButton("Clear");
b2 = new JButton("Copy");
}
public void launchFrame() {
p.add(b1, BorderLayout.SOUTH);
p.add(b2, BorderLayout.EAST);
p.add(l, BorderLayout.NORTH);
p.setSize(200, 300);
f.getContentPane().add(p);
b1.addActionListener(new ClearButton());
b2.addActionListener(new CopyButton());
f.pack();
f.setVisible(true);
}
public static void main(String args[]) {
swingEx1 swObj1 = new swingEx1();
swObj1.launchFrame();
}
}
class ClearButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton b1 = (JButton) e.getSource();
b1.setLabel("It it Clear Button");
}
}
class CopyButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
JButton b2 = (JButton) e.getSource();
b2.setLabel("It it Copy Button");
}
}
I adjusted your ActionListener class (which is a separate defaulted-access class in your code) to an inner class and changed Button to JButton. It works.
class ClearButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton b1 = (JButton) e.getSource();
b1.setLabel("It it Clear Button");
}
}
The GUI appears as follows:
1. Before clicking:
Panel before clicking
2.After clicking:
panel after clicking
I changed my imports from:
import javax.swing.*;
import java.awt.*;
to:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
This fixed the problem. Not sure why the original imports didn't work.

How to allow user to continuously input elements into JList

I want to be able to allow the user to continuously add elements to JList. The program allows the user to input an element into the textfield and when the user presses the JButton, it will add it into the list. I was able to do so but my program would only allow me to override the previous element instead of adding a new element.
private JList list;
private JTextField textField;
private JButton followUser() {
JButton btnNewButton = new JButton("Follow User");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultListModel DLM = new DefaultListModel();
String input = textField.getText();
DLM.addElement(input);
list.setModel(DLM);
}
});
return btnNewButton;
}
Your problem in next: you always recreate DefaultListModel in actionPerformed, but you need to use model from your JList and adding elements to it. Try next example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class TestFrame extends JFrame {
private DefaultListModel<String> model;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
final JTextField field = new JTextField(10);
JButton add = new JButton("add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = field.getText();
model.addElement(text);
}
});
JPanel p = new JPanel();
p.add(field);
p.add(add);
JList<String> l = new JList<>(model = new DefaultListModel<>());
add(new JScrollPane(l));
add(p,BorderLayout.SOUTH);
}
public static void main(String args[]) {
new TestFrame();
}
}

How to use a JComboBox to add a JTextField

I need to know how to add a JTextField if one of the JComboBox options is selected, and if the other one is selected I don't want to have that text field there any more.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame{
//Not sure if this code is correct
private JTextField text;
private JComboBox box;
private static String[] selector = {"Option 1", "Option 2"};
public GUI(){
super("Title");
setLayout(new FlowLayout());
box = new JComboBox(selector);
add(box);
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(){
//what should be in the if statement and what should i type down here to add the
//JTextField to the JFrame?
}
}
}
);
}
}
Try next example, that should help you:
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFrame extends JFrame {
public TestFrame(){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
});
}
private void init() {
final JComboBox<String> box = new JComboBox<String>(new String[]{"1","2"});
final JTextField f = new JTextField(5);
box.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
f.setVisible("1".equals(box.getSelectedItem()));
TestFrame.this.revalidate();
TestFrame.this.repaint();
}
}
});
add(box,BorderLayout.SOUTH);
add(f,BorderLayout.NORTH);
}
public static void main(String... s){
new TestFrame();
}
}

Categories