Using Action/Item Listener with JComboBox - java

I've been trying to make a listener (I'm not really sure whether I should be using an ItemListener or ActionListener) respond to changes in a JComboBox by changing a JLabel image next to the box.
I tried defining the actionPerformed method in the constructor of the class under the addActionListener call on the combo box, as well as outside the constructor, and the actionPerformed never seems to execute. I've added a println to each one to test whether the method is actually working when I select an item in the box, but neither one appears to output anything, leading me to believe the actionPerformed method is not executing for some reason. A lot of different answers elsewhere have defined actionListeners and actionPerformed in multiple different places, such as a separate class or in an instance variable declaration.
public class MainBattle
{
//instance variables
public MainBattle() throws FileNotFoundException,IOException
{
//creation of ArrayLists used later
for(JComboBox<String> j : party1)
{
j.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Listener active");
if(e.getSource() instanceof JComboBox)
{
JComboBox<String> cb = (JComboBox<String>)e.getSource();
String content = (String)cb.getSelectedItem();
if(party1.indexOf(cb) != -1)
{
party1Image.get(party1.indexOf(cb)).setIcon(new ImageIcon(".\\res\\sprites_small\\"
+ content.substring(0,content.indexOf(" ")) + ".png"));
}
}
selectFrame.revalidate();
selectFrame.repaint();
}
});
}
createUI();
}
public void createUI()
{
//building GUI elements and displaying
for(int i = 0; i < 6; i++)
{
party1.add(new JComboBox<String>());
party2.add(new JComboBox<String>());
}
for(int i = 0; i < 6; i++)
{
party1Image.add(new JLabel(new ImageIcon(".\\res\\sprites_small\\0.png")));
party2Image.add(new JLabel(new ImageIcon(".\\res\\sprites_small\\0.png")));
}
//building GUI elements and displaying
}
// Commented out to make sure existence of multiple methods is not problematic
/*
public void actionPerformed(ActionEvent e)
{
System.out.println("Action");
}
*/
public static void main(String[] args) throws IOException
{
new MainBattle();
}
}

Related

Passing ActionPerformed parameters in Constructor

I cannot pass the parameters of the ActionListener interface, method actionPerformed().
I have been trying to use the Runnable interface to overcome this problem, however it's method run() does not have the e.getSource() function which is key in my program!
My program creates nine buttons simultaneously in one class, than using dependency injection and getters the second class gets the information and to uses it to make the buttons functional.
The problem comes from the fact that if I want to activate this functionality I need to use the method actionPerformed(). Which parameters actionPerformed( ActionEvent e ).
I need to pass it into the constructor and than pass it's parameter which is at least for me impossible.
The next thing that I that I tried using was the Runnable interface, however it's method run() does not have the e.Source() function, which I have tried to recreate without any luck.
Class where buttons are made:
public class MakeButtons {
private Parameters p;
...
//constructor
public MakeButtons(Parameters p){
this.p = p;
...
makeNineButtons();
}
//getter
public JButton[] getButtons() {
return buttons;
}
//making the nine buttons buttons.length = 9
private void makeNineButtons() {
for (int i = 0; i < buttons.length; i++) {
panel.getGamePanel().add(buttons[i] = new JButton());
buttons[i].setFont(font);
}
}
}
Class where buttons get functions:
public class ButtonsFunctionality implements ActionListener /* OR Runnable */{
private final MakeButtons makeButtons;
...
//constructor
public ButtonsFunctionality(MakeButtons makeButtons){
this.makeButtons = makeButtons;
...
/*
actionPerformed(???);
or
run()
*/
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("yes");
for (JButton n : makeButtons.getButtons()) {
if (e.getSource() == n) {
//Code
}
}
}
// OR
#Override
public void run() {
System.out.println("yes");
for (JButton n : makeButtons.getButtons()) {
if ( ??? == n) {
//Code
}
}
}
}

One program, different on multiple computers

First of all, I want to ask you to ask as much information as possible to me to be able to help me out.
I've been creating an automatic reminder system which is able to create the reminder in PDF then automatically send it to the clients which you've chosen to be reminded.
The program is working perfectly fine, but once I try to start it on another computer, it does not work anymore. The following problems occur:
On one computer in Eclipse it does not even open the frame which handles the user input (telling the program which clients have to be reminded). The code is given below. An interesting point here is that I've tried to print a line if the actionPerformed method is running. It does NOT appear at all. So for some reason it is not listening to that whole method.
if(starter.getAccess().equals("admin") || starter.getAccess().equals("god")){
menu = new JMenu("Aanmaningen");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Debiteuren aanmanen");
menuBar.add(menu);
menu.addSeparator();
ButtonGroup group2 = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("Pyxis Distribution B.V.");
rbMenuItem.setSelected(false);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group2.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem.addActionListener(new ActionListener() {
#SuppressWarnings("static-access")
#Override
public void actionPerformed(ActionEvent arg0) {
chosenComp = true;
f.getContentPane().add(new Main());
f.revalidate();
f.repaint();
Distrscherm obj = new Distrscherm();
obj.plannerJTable();
}
});
On the other computers it was jarred and did open the menu, but did the JComboBox did not automatically complete the searchterms. It neither sent the mail. When clicking on the button save and send it didn't do anything. The codes are shown below.
This is the code which handles automatic completion (pretty basic code)
public AutoComboBox() {
setModel(new DefaultComboBoxModel(myVector));
setSelectedIndex(-1);
setEditable(true);
JTextField text = (JTextField) this.getEditor().getEditorComponent();
text.setFocusable(true);
text.setText("");
text.addKeyListener(new ComboListener(this, myVector));
setMyVector();
}
/**
* set the item list of the AutoComboBox
* #param patternExamples an String array
*/
public static void setKeyWord(Object[] patternExamples) {
AutoComboBox.keyWord = patternExamples;
setMyVectorInitial();
}
private void setMyVector() {
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
}
private static void setMyVectorInitial() {
myVector.clear();
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
This is the code which handles the SAVE button
#Override
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("unused")
Writer obj1 = new Writer(getTableData(table), "./planningdagelijks/week.csv");
for(int i =0; i < model.getRowCount(); i++) {
Datareader.Runner(model.getValueAt(i, 0));
internalfile obj2 = new internalfile();
obj2.intern();
try {
maildata.Reader((String)model.getValueAt(i, 0));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Pdfgenerator.Filegenerator((String)model.getValueAt(i, 0));
}
}
});

How to escape from mouseListener?

I have:
class extended from JFrame;
an list of JTextField's elements - JTextField[] pix.
When clicking on pix[i] - JFrame must iconified and next click at any point of screen must changes exactly that textField (pix[i]) without any influence on another textFields, then frame must normalized and any mouseClicks after that (not on textField) couldn't influenced on that elements.
Clicks outside of JFrame processed with jnativehook library.
That part of code here:
for (int i = 0; i < pix.length; i++){
int tmp = i;
pix[i].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
}
});
}
});
P.S.: I've tried to use
GlobalScreen.removeNativeMouseListener(new NativeMouseAdapter() {
public void nativeMouseClicked(NativeMouseEvent e) {
}
});
but don't actually know how to use this correctly.
P.S.[2]: if you have another solution of that question, you are welcome to type it into the answers - it will be great :>
EDIT!
I was buisy and now I'm here with solution:
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
GlobalScreen.removeNativeMouseListener(this);
}
};
MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(adapter);
}
};
pix[i].addMouseListener(listener);
Add (after the setState) code to remove the MouseListener.
setState(Frame.NORMAL);
for (int i = 0; i < pix.length; i++){
pix[i].removeMouseListener(MouseAdapter::this);
}
pix must be effectively final, and I hope MouseAdapter::this works for the anonymous MouseListener.
MouseAdapter::this fails
Instead of
pix[i].addMouseListener(new MouseAdapter() {
hold the MouseListener in its own variable:
MouseListener cat = new MouseAdapter() { ... };
pix[i].addMouseListener(cat);
And later do in the inner callback do
pix[i].removeMouseListener(cat);
In the code where you create the mouse listener, you need to keep a reference.
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
}
}
GlobalScreen.addNativeMouseListener(adapter);
Then when you want to remove it, you use that reference.
GlobalScreen.removeNativeMouseListener(adapter);
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
GlobalScreen.removeNativeMouseListener(this);
}
};
MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(adapter);
}
};
pix[i].addMouseListener(listener);

How to deal with multiple jcheckbox and one jbutton JAVA

For example I have 2 checkbox and 1 button my code would be like this.
private class CheckBoxHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (chckbxNewCheckBox1.isSelected() && chckbxNewCheckBox2.isSelected())
{
checkboxcheck1 = 1;
checkboxcheck2 = 1;
}
else if(chckbxNewCheckBox1.isSelected())
{
checkboxcheck1 = 1;
}
else if(chckbxNewCheckBox2.isSelected())
{
checkboxcheck2 = 1;
}
}
}
private class ButtonHandler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (checkboxcheck1 == 1 && checkboxcheck2 == 1)
{
textFieldSum.setText(String.valueOf(counter));
textFieldSum1.setText(String.valueOf(counter1));
}
else if(checkboxcheck1 == 1)
{
textFieldSum.setText(String.valueOf(counter));
}
else if (checkboxcheck2 == 1)
{
textFieldSum1.setText(String.valueOf(counter1));
}
else
{
checkboxcheck1 = 0;
}
}
}
But then what if I have more than 2 checkbox like 10 or more.It would take forever to to make the if statement in CheckBoxHandler and ButtonHandler. Anybody know how to make it work if I have more than 2 checkbox ?
My program is read the file and count the specific character in the file and then display it. The way to display it is click on the checkbox and click the yes button. But it will take forever for me to do the if statement. You guys have any idea? Thanks yall so much for help.
Declare an array of checkboxes like so
CheckBox[] checkboxes = new CheckBox[10]; // or JCheckBox if using swing
And in the constructor, create them with
String[] filenames = { ... }; // have a list of files?
for(int i=0;i<checkboxes.length;i++){
// for each box, create and add it to your panel
mypanel.add(checkboxes[i]=new CheckBox(filename[i]));
checkboxes[i].addItemListener(mylistener);
}
then in the listener, you can have
public void itemStateChanged(ItemEvent e) {
boolean state = ((CheckBox)e.getSource()).isSelected();
// do something with this state if needed
}
But notice that you don't actually need the item listeners at all.
In the button listener you can do
public void actionPerformed(ActionEvent e) {
for (int i=0;i<checkboxes.length;i++){
if(checkboxes[i].isSelected()){
// do something with file i
}
}
}
Note that if your file operation takes time, you have to do the processing in a new thread, not just in the button handler!

Java Swing button actionEvent

sorry to bother everyone.
Overall problem: I'm trying to open a dialogue box let the user enter something then close it
Issue: - A function is not being called (i think)
- The main problem is when i use debug it works fine so Its difficult for me to track down the problem
I'm having trouble with JButtons,
it works in debug but not in normal run. this was probably because i was using an infinite loop. someone online suggested i used SwingUtilities but that didn't work (at least i don't think.
/**
*
* #author Deep_Net_Backup
*/
public class butonTest extends JFrame {
String name;
boolean hasValue;
//name things
private JLabel m_nameLabel;
private JTextField m_name;
//panel
private JPanel pane;
//button
private JButton m_submit;
//action listener for the button submit
class submitListen implements ActionListener {
public void actionPerformed(ActionEvent e) {
submit();
System.out.println("Test");
}
}
//constructor
public butonTest(){
//normal values
name = null;
hasValue = false;
//create the defauts
m_nameLabel = new JLabel("Name:");
m_name = new JTextField(25);
pane = new JPanel();
m_submit = new JButton("Submit");
m_submit.addActionListener(new submitListen());
//
setTitle("Create Cat");
setSize(300,200);
setResizable(false);
//add components
pane.add(m_nameLabel);
pane.add(m_name);
pane.add(m_submit);
add(pane);
//last things
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//submit
private void submit()
{
System.out.println("submit");
name = m_name.getText();
hasValue = true;
}
//hasValue
public boolean hasValue()
{
return(hasValue);
}
//get the text name
public String getName()
{
return(name);
}
public void close()
{
setVisible(false);
dispose();
}
public static void main(String[] args)
{
/* Test 1
boolean run = true;
String ret = new String();
butonTest lol = new butonTest();
while(run)
{
if(lol.hasValue())
{
System.out.println("Done");
run = false;
ret = new String(lol.getName());
lol.close();
}
}
System.out.println(ret);*/
//Tset 2
/*
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
butonTest lol = new butonTest();
if(lol.hasValue())
{
System.out.println(lol.getName());
}
}
});*/
}
}
Edit:
How its not working: When i run Test the program will print test and submit then it should change the hasValue to true. this will (hopefully) allow the if statement to run to print done. This does not happen.
Edit 2:
I have just added a few more lines for further testing 2 prints and this seems to have solved the issue (but this is bad)
System.out.println("hasValue " + hasValue); -> to the hasValue() function
System.out.println("set to true"); -> submit() function
You are doing something far too complicated than is necessary. Instead of having the listener as a seperate class, you could have it as an anonymous class. That way you can get a handle on the outer class (butonTest.this), and call any method you want on it.
m_submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
submit();
System.out.println("Test");
butonTest.this.close();
}
});
I'm not sure what you are trying to do with the infinite loop. It would have run to completion before you show the dialog anyway.
It would help to read up a bit on how Event-Handling works in Swing :)
I am afraid your constructor butonTest() and submit() method are out of your
class (public class butonTest extends JFrame).
you need to get them inside your class:

Categories