I have few JFrames. Using one of them (it contains textBox) I want to transfer inputed data to the variable in another class. This variable is used to build JComboBox choose list. I try to transfer inputed data via JButton, but in the end nothing is transferred and JComboBox stays empty. Do I need to somehow refresh JComboBox or something? My code:
...
DataBase toTable = new DataBase();
...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent click) {
toTable.data[0] = textField.getText();
}
});
Variable from DataBase class:
....
String data[] = {"","","","",""};
....
And the Main Class (it contains JComboBox):
...
DataBase data0 = new DataBase();
final JComboBox list0 = new JComboBox(data0.data);
list0.setBounds(10, 61, 110, 22);
contentPane.add(list0);
That's correct. The JComboBox doesn't notice that you updated the array. You will need to use the addItem or setModel method of JComboBox.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent click) {
toTable.data[0] = textField.getText();
list0.setModel(new DefaultComboBoxModel(toTable.data));
}
});
Of course, this code won't run unless you can reference list0 in the same scope as your button. I would recommend putting button and list0 in the same class, if possible.
Related
I am currently writing a program which takes an input from a user which is a file, and an integer. Both of these fields are entered into the gui, and then when the user clicks the button I prompt them on screen with, the program should then store the two inputs into variables for later use when it comes to searching the file. The issue is that for swing, there needs to be an
ActionListener which is formatted like this:
0 JButton okButton = new JButton("OK");
1 okButton.addActionListener(new ActionListener() {
2 public void actionPerformed(ActionEvent e) {
3 //(WHERE I'M HAVING THE ISSUE)
4 }
5 });
My issue is that the user's click is registered, and then the code within the actionPerformed function (line 2-3) executes, but since it is in its own function, it cannot save to any variables which are made outside of it (which would be above line 0). It also cannot return any values since actionPerformed's return is supposed be void. Not only this, but you can't fully alter the gui inside of this function, so I cannot write the rest of the code inside of it. Is there any way for me to store the two inputs the user puts into my gui as variables which I can use for the rest of my program? For clarification, this is what I want to happen:
String userInput = null;
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//userInput = (the string the user submitted)
}
});
mainFrame.add(okButton);
mainFrame.setVisible(true);
//(And from here on use the updated user input as I need)
Overall I don't understand how to take information from a user input in my gui and store it for later.
ActionListener is a functional interface which means that, since JDK 8, you can implement it with a method reference.
Declare the GUI components, that the user uses to enter the file and the integer, as class member variables so that you can reference them from the method that implements ActionListener, for example:
public class Gui {
private javax.swing.JTextField fileTextField;
private javax.swing.JSpinner integerSpinner;
private void createAndDisplayGui() {
javax.swing.JButton button = new javax.swing.JButton("Hit me!");
button.addActionListener(this::performAction);
}
// 'ActionListener' implementation.
private void performAction(java.awt.event.ActionEvent event) {
String file = fileTextField.getText();
}
}
The name of the method that implements ActionListener interface can be any name you like. It just has to take the same parameters (as method actionPerformed) and return the same value, i.e. void in the case of method actionPerformed which is the sole method in interface ActionListener. Also note that the method need not be public.
If it were me, I'd use a JPanel and JOptionPane
JPanel p = new JPanel();
JTextField tf = new JTextField(); // For the file name. You can use a JFileChooser also
JTextField tf2 = new JTextField(); // For the number;
p.setLayout(new GridLayout(1,2));
p.add(tf);
p.add(tf2);
int result = JOptionPane.showConfirmDialog(null, p);
String fileName = null;
if (result == JOptionPane.OK_OPTION) {
fileName = tf.getText();
}
I have two buttons and in the second one I want to use a variable made in the first button. So Netbeans is generating code of the button. ActionEvent generated by netbeans is
"private void buttonActionPerformed(java.awt.event.ActionEvent evt)"
and I cant change it. I tried to change button to public in button setting. I changed it to public but in code it is still private. I dont know what to do. Anyone know where the problem might be?
Thanks.
What you want to do is, there is a blank line above the private void buttonActionPerformed(ActionEvent evt) you create your variable in that line the example: int a; now the a will turn green. This is called a global variable
JFrame jtfMainFrame;
JButton jbnButton1, jbnButton2;
JTextField jtfInput;
JPanel jplPanel;
//Declaring the string variable setText
String setText;
public JButtonDemo2() {
jtfMainFrame = new JFrame("Which Button Demo");
jtfMainFrame.setSize(50, 50);
jbnButton1 = new JButton("Button 1");
jbnButton2 = new JButton("Button 2");
jtfInput = new JTextField(20);
jplPanel = new JPanel();
jbnButton1.setMnemonic(KeyEvent.VK_I); //Set ShortCut Keys
jbnButton2.setMnemonic(KeyEvent.VK_I);
jbnButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Setting the setText variable
setText = "Do whatever you want";
}
});
jbnButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Displaying the setText variable
jtfInput.setText(setText);
}
});
jplPanel.setLayout(new FlowLayout());
jplPanel.add(jtfInput);
jplPanel.add(jbnButton1);
jplPanel.add(jbnButton2);
jtfMainFrame.getContentPane().add(jplPanel, BorderLayout.CENTER);
jtfMainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtfMainFrame.pack();
jtfMainFrame.setVisible(true);
}
Simply declare it as a global means when the class definition starts at that time declare the variable which you want to use at the two buttons click and change the value of variable according to your use.
No need to change the ActionPerformed(). All you have to do is declare the variable as a global variable and then do whatever the task inside the button's ActionPerformed().
alright.,ive already tried every trick off my sleeves..but couldnt figure out how to update the comboBox w/glazedList..if the input is coming from other class..ive tried passing the value to the methods,declaring it first to a string..and such..but none has work..tho it does work if the new item will just gonna come from same class..via click of a button..
so far ive got this code..
values = GlazedLists.eventListOf(auto);//auto is an array..
AutoCompleteSupport.install(comboSearch,values);//comboSearch is the comboBox
//"x" is the value coming from another class.
public void updateCombo(String x){
List<String> item = new ArrayList<>();
item.add(x)
value.addAll(item);
}
i hope this codes are enough to interpret what im trying to ask..
It's not possible to see how you've created your combobox and your eventlist. Therefore I'll just create a simple example application from scratch that shows you the essentials.
Just in case you're not familiar the general concepts the main take home points are:
Try and avoid using standard Java collections (eg ArrayList, Vector) and use the EventList class as soon as possible. All the goodness that comes with sorting/filtering/auto-complete relies on the EventList foundation so set one up asap and then simply manipulate (add/remove/etc) and then the GlazedLists plumbing will take care of the rest.
Once you've got your collection of objects in an EventList and you want to leverage a swing component then look in the ca.odell.glazedlists.swing module which contains everything you need. In this instance you can use an EventListComboBoxModel - pass in your eventlist, and then set your JComboBox model to use the newly created EventListComboBoxModel and from that point GlazedLists will take care of ensuring your list data structure and combobox stay in sync.
So in my example I create an empty combobox and an button. Clicking the button will add an item per click into the combobox. The magic is simply the creation of the EventList and the use of EventListComboBoxModel to link the list to the combobox.
Please note that the code below was only tested against GlazedLists 1.8. But I'm pretty sure it'll work fine with 1.9 or 1.7 too.
public class UpdateComboBox {
private JFrame mainFrame;
private JComboBox cboItems;
private EventList<String> itemsList = new BasicEventList<String>();
public UpdateComboBox() {
createGUI();
}
private void createGUI() {
mainFrame = new JFrame("GlazedLists Update Combobox Example");
mainFrame.setSize(600, 400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addButton = new JButton("Add Item");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
itemsList.add("Item " + (itemsList.size()+1));
}
});
// Use a GlazedLists EventComboBoxModel to connect the JComboBox with an EventList.
EventComboBoxModel<String> model = new EventComboBoxModel<String>(itemsList);
cboItems = new JComboBox(model);
JPanel panel = new JPanel(new BorderLayout());
panel.add(cboItems, BorderLayout.NORTH);
panel.add(addButton, BorderLayout.SOUTH);
mainFrame.getContentPane().add(panel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UpdateComboBox();
}
});
}
}
I am making a simple calculator in Java, I'm pretty new to Java but I've done a lot of work with languages like it.
The problem is, I need to have the combo box select an item and have it kept up to date, either in a place holder, or in the box itself.
This is the basic class that sets up the frame and everything.
private void initComponents()
{
//TODO:make controls here
//TODO:DONE
JFrame calculator = new JFrame("Steven Seppälä");
calculator.setLayout(new GridLayout(2, 2, 0, 0));
calculator.setSize(400,300);
//"calculator" is the holder for which all the
//items must attach to
calculator.add(new JLabel("Enter the first fraction('1/2')"));
// calculator.add(new JToolBar.Separator(new Dimension(0,10)));
calculator.add(field1);
// calculator.add(new JToolBar.Separator(new Dimension(0,10)));
//TODO: ADD COMBO BOX HERE
String[] operationList = {"+","-","*","/"};
JComboBox operationBox = new JComboBox(operationList);
calculator.add(operationBox);
/*Tried doing the following as well, but it just gave the index 0 consistantly
without changeing, regaurdless of if it did change or not */
// String thing = operationBox.getSelectedItem().toString();
// System.out.println("Selected Operation is: " + thing);
// operationCall = operationBox.getSelectedItem();
operationBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//DEBUGGING
operationBox.getSelectedItem().toString();
}
});
calculator.add(new JLabel("Enter the next fraction('3/4')\n",1));
// calculator.add(new JToolBar.Separator(new Dimension(0,0)));
calculator.add(field2);
// calculator.add(new JToolBar.Separator(new Dimension(0,0)));
JButton Cal = new JButton("Calculate");
calculator.add(Cal);
Cal.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//DEBUGGING
System.out.println("Finalizing Calculations...");
calculations();
}
});
//sets exit conditions and the visibility of the window
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calculator.setVisible(true);
calculator.add(new JLabel(results));
//TODO: add to(?) frame
//TODO:DONE
}
The action listener for the Calculate button works fine, but when I compile as it is now, I get the error message :
FractionFrame.java:53: error: local variable operationBox is accessed from within inner class; needs to be declared final
System.out.println(operationBox.getSelectedItem().toString());
^
In the ActionListener you can access the combo box by using:
JComboBox comboBox = (JComboBox)e.getSource();
Instead of:
JComboBox operationBox = new JComboBox(operationList);
Make it:
final JComboBox operationBox = new JComboBox(operationList);
I am making a Java application where I show a couple of checkboxes with relevant item from a file. Based on the selection I have to modify the original file accordingly. I have done this part.
I now realized that there might be some information that the user wants to add extra. I therefore want to show a checkbox with a JTextField hooked to it. The idea that I am trying to use is that if the value of checkbox is true, the value of JTextField associated with it, is included in the file.
I want to do something like this:
checkBoxes[i] = new Checkbox(new JTextField("enter new member e.g private int newMember"), null, false);
then
if(checkBoxes[i]==true)
{
updatefile(file, checkBoxes[i]);
}
Where updateFile is a function that adds the value of checkBoxes[i] to file
Any idea on how should I work on this?
Just create the JTextField separately, there's no need for them to be the same control.
i.e.
checkBoxes[i] = new JCheckBox("label");
textFields[i] = new JTextField("extra data");
// ...
if (checkBoxes[i].isSelected()) {
updateFile(file, textFields[i]);
}
If you want to enable/disable the textFields based on the selected state of the checkbox, do it using a listener - e.g. an ActionListener:
checkBoxes[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textFields[i].setEnabled(checkBoxes[i].isSelected());
}
You could have the JTextField as a seperate variable and have them both in a JPanel
JTextField textField = new JTextField();
JCheckBox checkBox = new JCheckbox("enter new member e.g private int newMember",false);
JPanel panel = new JPanel();
panel.add(checkBox);
panel.add(textField);
And then access it like that
if(checkBox.isSelected())
{
updatefile(file, textField.getText());
}
Hope it helps.