JButton appears after selection of value in JList - java

I have a JList with some elements and I want to have a JButton appears only when the user select a value in the list. This is what I have tried :
public void itemStateChanged(ItemEvent event) {
int choice = avDevBox.getSelectedIndex();
if (choice = 0) {
list = new JList(listModel1);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent ev1) {
if (!ev1.getValueIsAdjusting()) {
String outputext = list.getSelectedValue().toString();
itemDetails.setText(outputext);
}
}
});
add(list);
add(itemDetails);
add(but1);
}
Is there any way to do this ?
Thanks in advance.

You can have a JButton already on your GUI already but make it invisible via myButton.setVisible(false). Then within your JList's ListSelectionListener call myButton.setVisible(true). You'll then want to call revalidate() and repaint() on the container (often a JPanel) that holds the now-visible JButton.
Note that for future questions you will want to create and post more pertinent code, preferably a Minimal, Complete, and Verifiable Example Program, as this would allow us to see why your current code is not working and would help us to answer well and with confidence.
For an example of an MCVE:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
#SuppressWarnings("serial")
public class McveExample extends JPanel {
private static final String[] DATA = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
private static final int PREF_W = 400;
private static final int PREF_H = 250;
private JList<String> list = new JList<>(DATA);
private JButton myButton = new JButton();
public McveExample() {
myButton.setVisible(false); // **** make button invisible
list.setVisibleRowCount(4);
list.addListSelectionListener(new ListListener()); // listener that does the dirty work
JScrollPane scrollPane = new JScrollPane(list);
// add a JButton that resets myButton back to being invisible
add(new JButton(new ResetAction("Reset", KeyEvent.VK_R)));
add(scrollPane);
add(myButton);
}
// make sure things are big enough
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class ResetAction extends AbstractAction {
public ResetAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
list.clearSelection();
myButton.setVisible(false);
McveExample.this.revalidate();
McveExample.this.repaint();
}
}
private class ListListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
JList<String> lst = (JList<String>) e.getSource();
String selection = lst.getSelectedValue();
if (selection != null) {
myButton.setText(selection);
myButton.setVisible(true);
McveExample.this.revalidate();
McveExample.this.repaint();
}
}
}
}
private static void createAndShowGui() {
McveExample mainPanel = new McveExample();
JFrame frame = new JFrame("McveExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Related

One MouseListener for many JLabel components

I have 17 JLabel components and I want to add same handler for all these labels. Actually I have have to increase the size of the label when mouse hovers over it. Code is here:
private void lblBackupMouseEntered(java.awt.event.MouseEvent evt) {
lblBackup.setSize(lblBackup.getWidth()+5,lblBackup.getHeight()+5);
}
private void lblChangePasswordMouseEntered(java.awt.event.MouseEvent evt) {
lblChangePassword.setSize(lblChangePassword.getWidth()+5,lblChangePassword.getHeight()+5);
}
private void lblAddEmployeeMouseEntered(java.awt.event.MouseEvent evt) {
lblAddEmployee.setSize(lblAddEmployee.getWidth()+5,lblAddEmployee.getHeight()+5);
}
private void lblAddCustomerMouseEntered(java.awt.event.MouseEvent evt) {
lblAddCustomer.setSize(lblAddCustomer.getWidth()+5,lblAddCustomer.getHeight()+5);
}
Now I want to avoid this repetition of same handler.
It's simple -- you can use the same mouse handler class, and can assign it to multiple JLabels, and then get the current involved JLabel via the MouseEvent#getSource() method.
#Override
public void mouseEntered(MouseEvent evt) {
// assuming that you only add this MouseListener to JLabels...
JLabel currentLabel = (JLabel)evt.getSource();
// do what needs to be done with currentLabel
}
For example:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class ManyLabelExample extends JPanel {
private static final int SIDES = 8;
private static final int GAP = 15;
public static final Color HOVER_COLOR = Color.pink;
private List<JLabel> labels = new ArrayList<>();
public ManyLabelExample() {
setLayout(new GridLayout(SIDES, SIDES));
MyMouseHandler myMouseHandler = new MyMouseHandler();
for (int i = 0; i < SIDES * SIDES; i++) {
String text = String.format("[%d, %d]", i % SIDES + 1, i / SIDES + 1);
JLabel label = new JLabel(text);
label.setOpaque(true);
label.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
label.addMouseListener(myMouseHandler);
labels.add(label);
add(label);
}
}
private class MyMouseHandler extends MouseAdapter {
#Override
public void mouseEntered(MouseEvent evt) {
JLabel source = (JLabel) evt.getSource();
for (JLabel label : labels) {
if (label == source) {
label.setBackground(HOVER_COLOR);
} else {
label.setBackground(null);
}
}
}
}
private static void createAndShowGui() {
ManyLabelExample mainPanel = new ManyLabelExample();
JFrame frame = new JFrame("ManyLabelExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Unable to resize JPanel in java Swing

I just started using Java Swing, and I was going through the following post: Dynamic fields addition in java/swing form.
I implement the code in this post with some modification, and it worked fine. As mentioned in the post, JPanel is not resizing itself when we add more rows. Can someone throw more light on this issue with easy to understand explanation that how can we resize JPanel as soon as we hit +/- button? Here is the code :
Row class
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class Row extends JPanel {
private JTextField quantity;
private JTextField item;
private JTextField price;
private JButton plus;
private JButton minus;
private RowList parent;
public Row(String initialQuantity, String initalPrice, String initialItem, RowList list) {
this.parent = list;
this.plus = new JButton(new AddRowAction());
this.minus = new JButton(new RemoveRowAction());
this.quantity = new JTextField(10);
this.item = new JTextField(10);
this.price = new JTextField(10);
this.quantity.setText(initialQuantity);
this.price.setText(initalPrice);
this.item.setText(initialItem);
add(this.plus);
add(this.minus);
add(this.quantity);
add(this.item);
add(this.price);
}
public class AddRowAction extends AbstractAction {
public AddRowAction() {
super("+");
}
public void actionPerformed(ActionEvent e) {
parent.cloneRow(Row.this);
}
}
public class RemoveRowAction extends AbstractAction {
public RemoveRowAction() {
super("-");
}
public void actionPerformed(ActionEvent e) {
parent.removeItem(Row.this);
}
}
public void enableAdd(boolean enabled) {
this.plus.setEnabled(enabled);
}
public void enableMinus(boolean enabled) {
this.minus.setEnabled(enabled);
}
}
RowList class
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class RowList extends JPanel{
private List<Row> rows;
public RowList() {
this.rows = new ArrayList<Row>();
Row initial = new Row("1","0.00","", this);
//addHeaders();
//addGenerateBillButton();
addItem(initial);
}
public void addHeaders(){
JLabel qty = new JLabel("Quantity");
//qty.setBounds(10, 0, 80, 25);
add(qty);
JLabel item = new JLabel("Item");
//item.setBounds(70, 0, 80, 25);
add(item);
JLabel price = new JLabel("Price");
//price.setBounds(120, 0, 80, 25);
add(price);
}
public void addGenerateBillButton(){
JButton billGenerationButton = new JButton("Generate Bill");
add(billGenerationButton);
}
public void cloneRow(Row row) {
Row theClone = new Row("1","0.00","", this);
addItem(theClone);
}
private void addItem(Row row) {
rows.add(row);
add(row);
refresh();
}
public void removeItem(Row entry) {
rows.remove(entry);
remove(entry);
refresh();
}
private void refresh() {
revalidate();
repaint();
if (rows.size() == 1) {
rows.get(0).enableMinus(false);
}
else {
for (Row e : rows) {
e.enableMinus(true);
}
}
}
}
Main class
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Enter Items");
RowList panel = new RowList();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You can call the pack() of the frame again.
Try this: Add this in your Row class
public class AddRowAction extends AbstractAction
{
public AddRowAction()
{
super("+");
}
public void actionPerformed(ActionEvent e)
{
parent.cloneRow(Row.this);
((JFrame) SwingUtilities.getRoot(parent)).pack(); // <--- THIS LINE
}
}
public class RemoveRowAction extends AbstractAction
{
public RemoveRowAction()
{
super("-");
}
public void actionPerformed(ActionEvent e)
{
parent.removeItem(Row.this);
((JFrame) SwingUtilities.getRoot(parent)).pack(); // <--- THIS LINE
}
}
You can get the root component (JFrame) using the SwingUtilities.getRoot(comp) from the child component and call the pack() method after your new Row is added to your RowList.
This would resize your JPanel. But your RowList will be horizontal. This is where LayoutManager comes into play.
You can know more about different LayoutManagers here.
To fix this problem, in your RowList panel, set your layout to:
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Within your refresh method call doLayout() method after revalidate()

JComboBox ActionEvent performs with multiple comboboxes?

I am performing actions for 2 combo boxes which involves in changing the background color of JLabel. Here is my code,
public class JavaApplication8 {
private JFrame mainFrame;
private JLabel signal1;
private JLabel signal2;
private JPanel s1Panel;
private JPanel s2Panel;
public JavaApplication8()
{
try {
prepareGUI();
} catch (ClassNotFoundException ex) {
Logger.getLogger(JavaApplication8.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws
ClassNotFoundException
{
JavaApplication8 swingControl = new JavaApplication8();
swingControl.showCombobox1();
}
public void prepareGUI() throws ClassNotFoundException
{
mainFrame = new JFrame("Signal");
mainFrame.setSize(300,200);
mainFrame.setLayout(new GridLayout(3, 0));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
signal1 = new JLabel("Signal 1",JLabel.LEFT);
signal1.setSize(100,100);
signal1.setOpaque(true);
signal2 = new JLabel("Signal 2",JLabel.LEFT);
signal2.setSize(100,100);
signal2.setOpaque(true);
final DefaultComboBoxModel light = new DefaultComboBoxModel();
light.addElement("Red");
light.addElement("Green");
final JComboBox s1Combo = new JComboBox(light);
s1Combo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s1Combo.getSelectedIndex() == 0)
{
signal1.setBackground(Color.RED);
}
else
{
signal1.setBackground(Color.GREEN);
}
}
});
final JComboBox s2Combo1 = new JComboBox(light);
s2Combo1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s2Combo1.getSelectedIndex() == 0)
{
signal2.setBackground(Color.RED);
}
else
{
signal2.setBackground(Color.GREEN);
}
}
});
s1Panel = new JPanel();
s1Panel.setLayout(new FlowLayout());
JScrollPane ListScrollPane = new JScrollPane(s1Combo);
s1Panel.add(signal1);
s1Panel.add(ListScrollPane);
s2Panel = new JPanel();
s2Panel.setLayout(new FlowLayout());
JScrollPane List1ScrollPane = new JScrollPane(s2Combo1);
s2Panel.add(signal2);
s2Panel.add(List1ScrollPane);
mainFrame.add(s1Panel);
mainFrame.add(s2Panel);
String[] columnNames = {"Signal 1","Signal 2"};
Object[][] data = {{"1","1"}};
final JTable table = new JTable(data,columnNames);
JScrollPane tablepane = new JScrollPane(table);
table.setFillsViewportHeight(true);
mainFrame.add(tablepane);
mainFrame.setVisible(true);
}
}
When Executed, If I change the item from combo box 1, the 2nd combo box also performs the change. Where did I go wrong?
Yours is a simple solution: don't have the JComboBoxes share the same model. If they share the same model, then changes to the selected item of one JComboBox causes a change in the shared model which changes the view of both JComboBoxes.
I wold use a method to create your combo-jlabel duo so as not to duplicate code. For instance:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class App8 extends JPanel {
private static final int COMBO_COUNT = 2;
private static final String SIGNAL = "Signal";
private List<JComboBox<ComboColor>> comboList = new ArrayList<>();
public App8() {
setLayout(new GridLayout(0, 1));
for (int i = 0; i < COMBO_COUNT; i++) {
DefaultComboBoxModel<ComboColor> cModel = new DefaultComboBoxModel<>(ComboColor.values());
JComboBox<ComboColor> combo = new JComboBox<>(cModel);
add(createComboLabelPanel((i + 1), combo));
comboList.add(combo);
}
}
private JPanel createComboLabelPanel(int index, final JComboBox<ComboColor> combo) {
JPanel panel = new JPanel();
final JLabel label = new JLabel(SIGNAL + " " + index);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
label.setOpaque(true);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ComboColor cColor = (ComboColor) combo.getSelectedItem();
label.setBackground(cColor.getColor());
}
});
panel.add(label);
panel.add(combo);
return panel;
}
private static void createAndShowGui() {
App8 mainPanel = new App8();
JFrame frame = new JFrame("App8");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
enum ComboColor {
RED("Red", Color.RED),
GREEN("Green", Color.GREEN);
private String text;
private Color color;
public String getText() {
return text;
}
public Color getColor() {
return color;
}
private ComboColor(String text, Color color) {
this.text = text;
this.color = color;
}
#Override
public String toString() {
return text;
}
}

Custom JComboBox editor

i got stuck at adding a button to a JComboBox editor, I succeeded to add a button but I got some issues like when I first enter to the editor an action perform event gets fired which is unacceptable and the other is I can't get the text typed.
Result:
Problems:
#Override
public Component getEditorComponent() {
return panel;
}
This is the problem, if I return panel.jtexfield I only get a text field without a button, so what's the trick here?
Here is my code
import Store.util.DatabaseHelper;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicComboBoxEditor;
import org.hibernate.HibernateException;
import org.netbeans.lib.awtextra.AbsoluteLayout;
public class NewComboTest extends JFrame {
private ArrayList<Object> shopCart = new ArrayList<Object>();
private JComboBox cb;
private static final Object[] comboContents = {
"First", "Second", "Third", "Fourth", "Fifth"
};
public NewComboTest() {
super("New Combo Test");
setLayout(null);
cb = new JComboBox();
cb.setRenderer(new NewComboRenderer());
cb.setEditor(new NewComboEditor());
cb.setEditable(true);
cb.setSize(new Dimension(350, 100));
for (int i = 0; i < comboContents.length; i++) {
cb.addItem(comboContents[ i]);
}
cb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("_____________" + cb.getSelectedItem());
shopCart.add(cb.getSelectedItem());
System.out.println("items added" + shopCart);
}
});
cb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
System.out.println("KeyReleased" + cb.getEditor().getItem().toString());
populateModel(cb.getEditor().getItem().toString());
}
});
getContentPane().add(cb, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 200, 480, 50));
setSize(1200, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] arg) {
new NewComboTest();
}
private class NewComboEditor extends JPanel implements ComboBoxEditor {
JTextField tf;
JButton eraseButton;
textPanel panel = new textPanel();
public NewComboEditor() {
}
#Override
public void addActionListener(ActionListener l) {
tf.addActionListener(l);
}
#Override
public Component getEditorComponent() {
return panel;
}
public Component getEditorComponent2() {
return panel;
}
#Override
public Object getItem() {
return tf.getText();
}
#Override
public void removeActionListener(ActionListener l) {
tf.removeActionListener(l);
}
#Override
public void selectAll() {
tf.selectAll();
}
#Override
public void setItem(Object o) {
if (o != null) {
tf.setText(tf.getText());
} else {
tf.setText("");
}
}
private class textPanel extends JPanel {
JTextField jTextField1 = new JTextField();
JButton jButton1 = new JButton();
public textPanel() {
setLayout(new BorderLayout());
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setForeground(new java.awt.Color(0, 51, 51));
jButton1.setText("X");
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jTextField1.setText("");
}
});
add(jTextField1, BorderLayout.CENTER);
add(jButton1, BorderLayout.EAST);
}
public String getText(){
return jTextField1.getText();
}
}
}
private class NewComboRenderer extends JLabel implements ListCellRenderer {
public NewComboRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
setText(value.toString());
setBackground(isSelected ? Color.BLUE : Color.white);
setForeground(isSelected ? Color.white : Color.red);
return this;
}
}
/* public void populateModel(String text) throws HibernateException {
java.util.List l = DatabaseHelper.GetProductsBy(text);
for (Object object : l) {
cb.addItem(object);
}
ignore this its unnecessary.
*/
}
}
I also wish to set the text font and size to the same as the set up at the combo box.
The first set of problems I can see is, you define a JTextField and JButton in the NewComboEditor, but also define a textPanel, which contains all these things any way. But instead of using the components on the textPane, you use the newly created components (in the NewComboEditor) instead...In fact, I'm not even sure how that could work, because you never initilise these components (in the NewComboEditor), so there should be a NullPointerException...
If that wasn't enough problems, the JTextField and JButton aren't added to anything anyway...
Instead...
NewComboEditor shouldn't need to extend from anything (or it could extend from textPane instead if you really wanted to).
All references to the field should be made to the text field in the textPane
As an example...
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class CustomComboBoxEditor {
public static void main(String[] args) {
new CustomComboBoxEditor();
}
public CustomComboBoxEditor() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JComboBox cb = new JComboBox();
cb.addItem("Apple");
cb.addItem("Banana");
cb.addItem("Orange");
cb.setEditable(true);
cb.setEditor(new MyComboBoxEditor());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(cb);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyComboBoxEditor implements ComboBoxEditor {
private EditorPane editorPane;
public MyComboBoxEditor() {
editorPane = new EditorPane();
}
#Override
public Component getEditorComponent() {
return editorPane;
}
#Override
public void setItem(Object anObject) {
editorPane.setText(anObject == null ? null : anObject.toString());
}
#Override
public Object getItem() {
return editorPane.getText();
}
#Override
public void selectAll() {
editorPane.selectAll();
}
#Override
public void addActionListener(ActionListener l) {
editorPane.addActionListener(l);
}
#Override
public void removeActionListener(ActionListener l) {
editorPane.removeActionListener(l);
}
}
public class EditorPane extends JPanel {
private JTextField field;
private JButton button;
public EditorPane() {
field = new JTextField(10);
button = new JButton("X");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
add(field, gbc);
gbc.weightx = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.gridx++;
add(button, gbc);
}
#Override
public void addNotify() {
super.addNotify();
field.requestFocusInWindow();
}
public void selectAll() {
field.selectAll();
}
public void setText(String text) {
field.setText(text);
}
public String getText() {
return field.getText();
}
public void addActionListener(ActionListener listener) {
field.addActionListener(listener);
}
public void removeActionListener(ActionListener listener) {
field.removeActionListener(listener);
}
}
}
Now, if you want to set the field's properties to be the same as the combo box, I would simply pass a reference of the combo box to the editor and allow it to extract the properties you need (i.e. font, color, etc.)

combo getSelectedItem but then

Simple question for you , i input this code and i see the combobox and the label, but after the selection of the combo the label should be with an image. This does not happen ... Surely i forgot something
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChooseFrame extends JFrame
{
public ChooseFrame()
{
labelLeagueImage = new JLabel("Liga");
comboLeague = createComboLeague();
class ChooseListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String league = (String)comboLeague.getSelectedItem();
if (league.equals("Italia - Serie A"))
{
ImageIcon icon = new ImageIcon("Italia - Serie A.png");
labelLeagueImage.setIcon(icon);
}
}
}
listener = new ChooseListener();
leaguePanel = new JPanel();
leaguePanel.add(comboLeague);
leaguePanel.add(labelLeagueImage);
add(leaguePanel);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public JComboBox createComboLeague()
{
JComboBox combo = new JComboBox();
combo.addItem("Select a league");
combo.addItem("Italia - Serie A");
combo.addItem("Italia - Serie B");
combo.addActionListener(listener);
return combo;
}
private JPanel leaguePanel;
private JComboBox comboLeague;
private JLabel labelLeagueImage;
private ActionListener listener;
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 600;
}
At the time you create the combo box and assign the listener, in createComboLeague(), the listener is still null. It's initialized only after the createComboLeague() method has been called.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ChooseFrame extends JFrame
{
private JPanel leaguePanel;
private JComboBox comboLeague;
private JLabel labelLeagueImage;
private ActionListener listener;
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 600;
public ChooseFrame()
{
labelLeagueImage = new JLabel("Liga");
comboLeague = createComboLeague();
// listener = new ChooseListener();
leaguePanel = new JPanel();
leaguePanel.add(comboLeague);
leaguePanel.add(labelLeagueImage);
add(leaguePanel);
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public JComboBox createComboLeague()
{
JComboBox combo = new JComboBox();
combo.addItem("Select a league");
combo.addItem("Italia - Serie A");
combo.addItem("Italia - Serie B");
combo.addActionListener(listener);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
String league = (String)comboLeague.getSelectedItem();
if (league.equals("Italia - Serie A"))
{
ImageIcon icon = new ImageIcon("Italia - Serie A.png");
labelLeagueImage.setIcon(icon);
}
}
});
return combo;
}
public static void main(String[] args) {
ChooseFrame cs=new ChooseFrame();
cs.setVisible(true);
}
}

Categories