This question already has answers here:
Java ActionListener error: incompatible types
(4 answers)
Closed 4 years ago.
I've just recently started learning code in Java. I encountered a problem with adding a listener.I have been struggling with this problem for an hour but I couldn't find the solution.Could someone make a look and see whats wrong please. Here's my code:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ItemEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MultiListenerFrame extends JFrame {
JPanel panel;
JLabel label;
JCheckBox button1;
JCheckBox button2;
JCheckBox button3;
public MultiListenerFrame() throws HeadlessException {
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setSize(600,500);
panel = new JPanel();
panel.setLayout(new FlowLayout());
add(BorderLayout.NORTH, panel);
button1 = new JCheckBox("button1");
button2 = new JCheckBox("button2");
button3 = new JCheckBox("button3");
panel.add(button1);
panel.add(button2);
panel.add(button3);
button1.addActionListener(this); // here is my problem
}
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if(source == button1) {
label.setText("Hello");
} else if (source == button2) {
label.setText("world");
} else if(source == button23) {
label.setText("!!!");
}
}
public static void main(String[] args) {
MultiListenerFrame frame = new MultiListenerFrame();
frame.setVisible(true);
}
}
You're not adding an ActionListener. this refers to your MultiListenerFrame class.
Define a listener somewhere and add that:
this.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO something
}
});
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I'm trying to use the actionPerformed method to print a message to the corresponding buttons (in this case b1/b2/b3). I have no idea where exactly in the code the issue lies.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class B_HangMan implements ActionListener {
JButton b1;
JButton b2;
JButton b3;
public static void main(String[] args) {
JPanel mainPanel = new JPanel();
JFrame frame1 = new JFrame();
frame1.setSize(900, 500);
frame1.setLocation(500, 200);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.add(mainPanel);
mainPanel.setLayout(null);
// button 1
JButton b1 = new JButton("1");
b1.setBounds(20, 20, 90, 90);
b1.addActionListener(new B_HangMan());
mainPanel.add(b1);
// button 2
JButton b2 = new JButton("2");
b2.setBounds(130, 20, 90, 90);
b2.addActionListener(new B_HangMan());
mainPanel.add(b2);
// button 3
JButton b3 = new JButton("3");
b3.setBounds(240, 20, 90, 90);
b3.addActionListener(new B_HangMan());
mainPanel.add(b3);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
System.out.println("button 1 was clicked");
}
if (e.getSource() == b2) {
System.out.println("button 2 was clicked");
}
if (e.getSource() == b3) {
System.out.println("button 3 was clicked");
}
}
}
The console should display which one was pressed when clicking on the different buttons. Nothing happens instead.
The comment, by #MadProgrammer, is telling you why nothing happens when you click on any of the buttons, namely that your code contains shadowing (not to be confused with hiding). In other words, you have local variables with the same declaration as member variables.
I don't know how you are learning Swing but it is a vast API and the quintessential tutorial is this one:
Creating a GUI With Swing
which is part of Oracle's Java tutorials.
There are also several books devoted entirely to Swing.
mainPanel.setLayout(null);
You usually don't need to use a null layout. I believe that FlowLayout is appropriate for displaying your buttons.
Also, since Java 8, you can implement ActionListener with a method reference.
Here is my rewrite of your code which aims to show you several other features of Swing, apart from fixing your problem whereby clicking on any of the buttons does nothing.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class HangmanB {
private void buildAndShowGui() {
JFrame frame = new JFrame("Hangman");
URL url = getClass().getResource("hangman16.png");
try {
Image img = ImageIO.read(url);
frame.setIconImage(img);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonsPanel(), BorderLayout.PAGE_START);
frame.setSize(900, 500);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JButton createButton(String text, int mnemonic, ActionListener listener) {
JButton b = new JButton(text);
b.setPreferredSize(new Dimension(90, 90));
b.setMnemonic(mnemonic);
b.addActionListener(listener);
return b;
}
private JPanel createButtonsPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING, 20, 5));
panel.setBorder(BorderFactory.createEmptyBorder(12, 8, 0, 0));
panel.add(createButton("1", KeyEvent.VK_1, this::handleButton1));
panel.add(createButton("2", KeyEvent.VK_2, this::handleButton2));
panel.add(createButton("3", KeyEvent.VK_3, this::handleButton3));
return panel;
}
private void handleButton1(ActionEvent event) {
System.out.println("button 1 was clicked");
}
private void handleButton2(ActionEvent event) {
System.out.println("button 2 was clicked");
}
private void handleButton3(ActionEvent event) {
System.out.println("button 3 was clicked");
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new HangmanB().buildAndShowGui());
}
}
Here is a screen capture of the GUI when I run the above code:
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.
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
Im learning about Java Swing components and I want to do that when I push button, Java Swing would add label from another class into JFrame screen. Its just simple example for start.
I want to learn how to use and add swing components from another class.
There can be some stupid mistakes, but dont judge me, im new ^^
Frame class add button
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame{
private JButton btn;
private boolean regCompl = false;
public Frame(){
super("The title Macas");
setLayout(new FlowLayout());
btn = new JButton("Push for Registration");
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
regCompl = true;
}
}
);
add(btn);
if(regCompl == true){
RegComplete regObj = new RegComplete(this);
}
}// end of constructor
}
RegComplete Class add label to screen after button are pressed.
import javax.swing.JButton;
import javax.swing.JLabel;
public class RegComplete {
Frame frame;
private JLabel label;
public RegComplete(Frame fm){
this.frame = fm;
label = new JLabel("Hello world Mac4s");
fm.add(label);
}
}
You have to create Object inside the action Listener
btn = new JButton("Push for Registration");
btn.addActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
RegComplete regObj = new RegComplete(Frame.this);
}
}
);
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a pretty strange behavior which I can only conclude must be a Java bug somewhere.
I changed one line in my constructor
super(parent, "Production Plan Export", ModalityType.MODELESS);
to
super(parent, "Production Plan Export", ModalityType.APPLICATION_MODAL);
and suddenly when I click on the button to open my JDialog, it opens it twice, the first time, its not responsive at all. I need to click the X button to close the window, and then when I do, then the same JDialog appears, and suddenly all my buttons opens.
Has anyone seen this behavior before?
I am using Java 1.6.0_33
Edit
What is very very strange, is when I try to debug it in eclipse and setting a break point at my constuctor, and I go to next line, then it suddenly jumps to my variable in the class and starts to go through my variables instead of the next line in the constructor.
I have tried to restart my computer and eclipse, but that didn't work.
I will see if I can create a small test case
Edit2:
Ok, so I have created a small application that can reproduce it for me.
Please note that I have tried to remove the part of the code that is not relevant, so there is alot of code that isn't valid for this test case.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class ProductionPlanExportDialog extends JDialog {
private JProgressBar progressbar;
private JLabel message;
private JButton exportButton;
private JButton helpButton;
private int state = JOptionPane.CANCEL_OPTION;
private final Action closeAction = new CloseAction();
private final Action enableExport = new EnableExport();
private boolean updating = false;
private JButton closeButton;
public ProductionPlanExportDialog(Window parent) {
super(parent, "Test", ModalityType.APPLICATION_MODAL); //The JDialog is not centered, and the close button doesn't work
// super(parent, "Test", ModalityType.MODELESS); //The close button works and the jdialog is centered
initGUI();
bindModel();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
close();
}
});
}
public static void main(String args[]) {
new ProductionPlanExportDialog(null);
}
public void initGUI() {
JTabbedPane mainTabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel yAxisPanel = new JPanel();
yAxisPanel.setLayout(new BoxLayout(yAxisPanel, BoxLayout.Y_AXIS));
JPanel progressPanel = new JPanel(new FlowLayout());
progressPanel.add(getProgressbar());
yAxisPanel.add(progressPanel);
yAxisPanel.add(getMessage());
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(getExportButton());
closeButton = new JButton("Close");
buttonPanel.add(closeButton);
buttonPanel.add(getHelpButton());
yAxisPanel.add(buttonPanel);
setSize(937, 605);
getContentPane().add(yAxisPanel);
setVisible(true);
setLocationRelativeTo(null);
}
private void bindModel() {
closeButton.setAction(closeAction);
}
public int getExitStatus() {
return state;
}
private JProgressBar getProgressbar() {
if (progressbar == null) {
progressbar = new JProgressBar();
progressbar.setPreferredSize(new Dimension(1000, 22));
progressbar.setName("progressbar");
progressbar.setStringPainted(true);
progressbar.setVisible(false);
}
return progressbar;
}
private JLabel getMessage() {
if (message == null) {
message = new JLabel();
message.setName("message");
}
return message;
}
private void setUIState() {
updating = true;
assert SwingUtilities.isEventDispatchThread();
try {
closeButton.setEnabled(false);
} finally {
updating = false;
}
}
private void setTextFieldValue(JFormattedTextField textField, long value) {
if(value == Long.MAX_VALUE || value == -Long.MAX_VALUE) {
textField.setText("");
} else {
textField.setValue(value);
}
}
public JButton getExportButton() {
if (exportButton == null) {
exportButton = new JButton();
exportButton.setToolTipText("Preview production plan");
exportButton.setName("exportButton");
exportButton.setText("Preview");
exportButton.setBounds(305, 640, 72, 21);
exportButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
}
return exportButton;
}
private JButton getHelpButton() {
if (helpButton == null) {
helpButton = new JButton();
helpButton.setBounds(470, 640, 72, 21);
helpButton.setName("helpButton");
helpButton.setText("Help");
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String helpText = "This dialog is used to preview and export a production plan.<br/>" +
"<h1>Preview</h1>"
+ "After pressing 'Export', the production plan will be generated. This can take a few minutes.";
JEditorPane helpEditorPane = new JEditorPane("text/html", helpText);
helpEditorPane.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
helpEditorPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(helpEditorPane,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
helpEditorPane.setCaretPosition(0);
scrollPane.setPreferredSize(new Dimension(640,445));
JOptionPane.showMessageDialog(helpButton, scrollPane, "Production Plan Export Dialog Help", JOptionPane.INFORMATION_MESSAGE);
}
});
}
return helpButton;
}
private final class EnableExport extends AbstractAction {
#Override
public void actionPerformed(final ActionEvent e) {
if(isAllCheckboxSelected()) {
getExportButton().setText("Export");
getExportButton().setToolTipText("Export production plan");
} else {
getExportButton().setText("Preview");
getExportButton().setToolTipText("Preview production plan");
}
}
}
boolean enableExport() {
return isAllCheckboxSelected();
}
boolean isAllCheckboxSelected() {
return false;
}
private final class CloseAction extends AbstractAction {
public CloseAction() {
super("Close");
}
#Override
public void actionPerformed(final ActionEvent e) {
close();
}
}
private void close() {
state = JOptionPane.OK_OPTION;
setVisible(false);
dispose();
}
}
not able to ...., can you please (descriptions about Bug) to test
import java.awt.Cursor;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(new Dimension(500, 500));
final JDialog dialog = new JDialog(frame, "Production Plan Export",
ModalityType.MODELESS);
dialog.setSize(300, 300);
final JDialog dialog1 = new JDialog(dialog, "Production Plan Export",
ModalityType.APPLICATION_MODAL);
dialog1.setSize(200, 200);
frame.add(new JButton(new AbstractAction("Dialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Runnable doRun = new Runnable() {
public void run() {
dialog.setVisible(true);
dialog1.setVisible(true);
}
};
SwingUtilities.invokeLater(doRun);
}
}));
frame.setVisible(true);
}
}
I found the problem.
It was because I had setVisible(true) twice. Once in my initGUI() method, and once where I initialize my JDialog.
Also thanks to MKorbel, I moved the setAction call in my initGUI() which made the button work when having APPLICATION_MODAL