This is my first post and I think I am doing it right.
I have a program that takes the user input from a AutoComplete jComboBox and then send's the input to be stored into a text file.(AutoComplete is done using the library glazedlists_java15/1.8.0).
After using the Autocomplet feature I had to set the jComboBox to DefaultComboBoxModel.
When the user presses the Enter key, the jComboBox should update the list with the new Item typed from the keyboard, so the user can see the last typed item in the jComboBox list.
This is done by removing all the items from the jComboBox and then inserting them again .
The problem is that before having the AutoComplete feature I could just say jComboBox1.removeAllItems(); but now because of the model I have to do it with model.removeAllElements();
public class Test {
final static DefaultComboBoxModel model = new DefaultComboBoxModel();
static JComboBox c = new JComboBox(model);
private static final long serialVersionUID = 1L;
private static JButton b = new JButton();
static JFrame f = new JFrame();
/**
* #param args
*/
public static void TestFrame() {
String[] a = {"hi1" , "hi2", "hi3", "hi4","hi5"};
AutoCompleteSupport support = AutoCompleteSupport.install(c,
GlazedLists.eventListOf(a));
JPanel test = new JPanel();
test.add(b);
test.add(c);
model.addElement(a);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.removeAllElements();
}
});
f.add(test);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(500,500);
}
The problem is that model.removeAllElements(); and model.addElement(s); is not working so I can not update the jComboBox. Can you please take your time and help me find a solution. Thanks!
Edit:
I don´t know where your problem is, this is totally working for me
final DefaultComboBoxModel model = new DefaultComboBoxModel();
JComboBox c = new JComboBox(model);
private static final long serialVersionUID = 1L;
private JButton b = new JButton();
public TestFrame() {
JPanel test = new JPanel();
test.add(b);
test.add(c);
model.addElement("hi");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.removeAllElements();
}
});
this.add(test);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setSize(500,500);
}
maybe you don´t reach your keylistener
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.JPanel;
import javax.swing.SwingUtilities;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.swing.AutoCompleteSupport;
public class TestFrame
{
private static JComboBox c = new JComboBox();
private static JButton b = new JButton();
private static JFrame f = new JFrame();
private static String[] a = {"hi1", "hi2", "hi3", "hi4", "hi5"};
public static void TestFrame()
{
final EventList<String> items = GlazedLists.eventListOf(a);
AutoCompleteSupport.install(c, items);
JPanel test = new JPanel();
test.add(b);
test.add(c);
c.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
c = (JComboBox) e.getSource();
if (e.getActionCommand().equals("comboBoxEdited"))
{
items.clear();
}
}
});
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
items.clear();
}
});
f.add(test);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
f.setSize(500, 500);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
TestFrame();
}
});
}
}
Related
The GUI has a search bar that when the user types a book and click search, it pops up on the JList. But I don't know how to write the code for it.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == searchButton) {
// Action for the SEARCH button
Keep the original unfiltered data in a structure (e.g an ArrayList) and add a DocumentListener to the search textfield in order to know whether the search text has been changed. Then, filter the original data and removeAllElements() from JList's model. Finally add the the filtered data to the model of JList.
Example:
public class SearchInJList extends JFrame implements DocumentListener {
private static final long serialVersionUID = -1662279563193298340L;
private JList<String> list;
private List<String> data;
private DefaultListModel<String> model;
private JTextField searchField;
public SearchInJList() {
super("test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
searchField = new JTextField();
searchField.getDocument().addDocumentListener(this);
add(searchField, BorderLayout.PAGE_START);
createData();
list = new JList<>(model = new DefaultListModel<>());
data.forEach(model::addElement);
add(new JScrollPane(list), BorderLayout.CENTER);
setSize(500, 500);
setLocationByPlatform(true);
}
private void createData() {
data = new ArrayList<String>();
for (int i = 0; i < 1000; i++) {
String s = "String: " + i + ".";
data.add(s);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SearchInJList example = new SearchInJList();
example.setVisible(true);
});
}
#Override
public void insertUpdate(DocumentEvent e) {
search();
}
#Override
public void removeUpdate(DocumentEvent e) {
search();
}
#Override
public void changedUpdate(DocumentEvent e) {
search();
}
private void search() {
List<String> filtered = data.stream().filter(s -> s.toLowerCase().contains(searchField.getText().toLowerCase()))
.collect(Collectors.toList());
model.removeAllElements();
filtered.forEach(model::addElement);
}
}
It does not work with a button, but I guess this is something you can do. I mean add the search() method into button's action listener.
So for every button press you can:
Fill a DefaultListModel with the strings that match the search criteria.
Create a new JList with the model of the previous step.
Pop a JOptionPane with the list of the previous step as its message.
Example code:
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Main {
public static void main(final String[] args) {
final String[] data = new String[]{"abcdef", "ABCdEF", "defGhi", "DEFghi"};
final JTextField textField = new JTextField(20);
final JButton searchButton = new JButton("Search");
searchButton.addActionListener(e -> {
final String searchText = textField.getText().toLowerCase();
final DefaultListModel<String> model = new DefaultListModel<>();
for (final String str: data)
if (str.toLowerCase().contains(searchText))
model.addElement(str);
final JList<String> list = new JList<>(model);
JOptionPane.showMessageDialog(searchButton, list);
});
final JPanel panel = new JPanel();
panel.add(textField);
panel.add(searchButton);
final JFrame frame = new JFrame("Search form");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
import java.awt.FlowLayout;
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;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.
Okay I can get text fields and normal text and even images to show but I can not get a button to show. I am not sure what I am doing wrong because I have done the same steps for the rest. Any help would be great thanks!
package EventHandling2;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import EventHandling.GUITest;
public class EventMain extends JFrame{
private JLabel label;
private JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
//gui.setSize(600, 300);
gui.setVisible(true);
gui.setTitle("Button Test");
}
public void EventMain(){
setLayout(new FlowLayout());
button = new JButton ("click for text");
add(button);
label = new JLabel ("");
add(label);
Events e = new Events();
button.addActionListener(e);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
The problem is with the method: void EventMain()
Constructor has NO return type. Just remove "void". The code will work just fine.
Your actionListener(e) contains a minor control structure error:
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
Change to:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("Now you can see words");
}
}
First off, you have to remove void keyword in EventMain's constructor. Then, creating JPanel and add components into it, then add the JPanel to the JFrame.contentPane.
The following code should work:
public class EventMain extends JFrame {
private final JLabel label;
private final JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x
// close program
gui.setSize(600, 300);
gui.setTitle("Button Test");
gui.setVisible(true);
}
public EventMain() {
// setLayout(new FlowLayout());
JPanel panel = new JPanel(new FlowLayout());
button = new JButton("click for text");
panel.add(button);
label = new JLabel("");
panel.add(label);
Events e = new Events();
button.addActionListener(e);
this.getContentPane().add(panel);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
I have 2 windows. one got an empty JList and the other one got a button. So I want to add the value to the list whenever I press the button. Here is my code but not completed:
Window 1
final DefaultListModel<String> favouriteNames = new DefaultListModel<String>();
JList namesList = new JList(favouriteNames);
Window 2
public class button extends JFrame {
private JList namesList;
private DefaultListModel<String> favouriteNames;
this.namesList = namesList;
JButton addThis = new JButton("Add");
addThis.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
favouriteNames.addElement("Jack");
}
});
}
}
Pass an instance of your DefaultListModel to Window 2 in the constructor.
Edited to add: Here's how you pass an instance in a constructor.
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.SwingUtilities;
public class ButtonFrame implements Runnable {
private JFrame frame;
private DefaultListModel favouriteNames;
public ButtonFrame(final DefaultListModel favouriteNames) {
this.favouriteNames = favouriteNames;
}
#Override
public void run() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addThis = new JButton("Add");
addThis.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
favouriteNames.addElement("Jack");
}
});
frame.add(addThis);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new ButtonFrame(new DefaultListModel()));
}
}
I made a simpler version of my program, but still have a problem, I believe the ActionPerformed sends the data but the JList does not recognise it or or basically did not expect to receive it. So here is what I have done so far. So it is a bit more of my research and attempts, maybe it gives more details about the problem.
Main Window:
public class main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new ClassA();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
ClassA:
public class ClassA extends JFrame {
DefaultListModel<String> myList;
JList list;
public ClassA() {
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
myList = new DefaultListModel<String>();
list = new JList(myList);
//ClassB sendsText = new ClassB(myList, list);
JButton find = new JButton("Find");
find.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new ClassB().setVisible(true);
}
});
add(panel);
panel.add(find);
panel.add(list);
}
}
ClassB:
public class ClassB extends JFrame {
DefaultListModel<String> myList;
JList list;
public ClassB(DefaultListModel<String> myList, JList list){
this.myList = myList;
this.list = list;
}
public ClassB() {
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,1));
JButton addMe = new JButton("Add Me");
addMe.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
myList.addElement("Danial");
}
});
add(panel);
panel.add(addMe);
}
}
I am trying to create a way to update a JComboBox so that when the user enters something into the text field, some code will process the entry and update the JComboBox accordingly.The one issue that I am having is I can update the JComboBox, but the first time it is opened, the box has not refresh the length of the options in it and as seen in the code below it displays extra white space. I do not know if there is a better different way to do this, but this is what I came up with.
Thanks for the help,
Dan
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Catch{
public static JComboBox dropDown;
public static String dropDownOptions[] = {
"Choose",
"1",
"2",
"3"};
public static void main(String[] args) {
dropDown = new JComboBox(dropDownOptions);
final JTextField Update = new JTextField("Update", 10);
final JFrame frame = new JFrame("Subnet Calculator");
final JPanel panel = new JPanel();
frame.setSize(315,430);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Update.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent arg0) {
}
public void focusLost(FocusEvent arg0) {
dropDown.removeAllItems();
dropDown.insertItemAt("0", 0);
dropDown.insertItemAt("1", 1);
dropDown.setSelectedIndex(0);
}
});
panel.add(Update);
panel.add(dropDown);
frame.getContentPane().add(panel);
frame.setVisible(true);
Update.requestFocus();
Update.selectAll();
}
}
1) JTextField listening for ENTER key from ActionListener
2) remove FocusListener
3) example about add new Item as last Item from JTextField to the JList, only you have to modify for JComboBox and add method insertItemAt() correctly
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ListBottom2 {
private static final long serialVersionUID = 1L;
private JFrame frame = new JFrame();
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JTextField textField = new JTextField("Use Enter to Add");
private JPanel panel = new JPanel(new BorderLayout());
public ListBottom2() {
model.addElement("First");
list.setVisibleRowCount(5);
panel.setBackground(list.getBackground());
panel.add(list, BorderLayout.SOUTH);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(new Dimension(200, 100));
frame.add(scrollPane);
frame.add(textField, BorderLayout.NORTH);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTextField textField = (JTextField) e.getSource();
DefaultListModel model = (DefaultListModel) list.getModel();
model.addElement(textField.getText());
int size = model.getSize() - 1;
list.scrollRectToVisible(list.getCellBounds(size, size));
textField.setText("");
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ListBottom2 frame = new ListBottom2();
}
});
}
}