Salve a tutti ragazzi, so che questa domanda sarà stata fatta mille volte, ma io ho provoto in tantissimi modi differenti... e non sono riusciuto.
In pratica ho un frame con 4 bottoni e cliccandone ognuno mi si deve aprire un nuovo frame.
Quindi ho pensato di utlizzare un if con getSource per trovare quale bottone ha avviato la gestione degli eventi.
Vi posto il codice: (N.B. facendo con il debug ho notato che l evento non viene gestito nel senso che non viene eseguito nessun if, in pratica ogni if di controllo che serve per determinare la sorgente dell' evento viene saltato):
public class StartView extends JPanel implements ActionListener{
private JButton additem;
private JButton addbrand;
private JButton itemlist;
private JButton brandlist;
public StartView () {
JButton additem = new JButton("Add Item");
JButton addbrand = new JButton("Add Brand");
JButton itemlist = new JButton("Item List");
JButton brandlist = new JButton("Brand List");
setLayout( new GridLayout(3,2,20,20));
additem.addActionListener(this);
add(additem);
addbrand.addActionListener(this);
add(addbrand);
itemlist.addActionListener(this);
add(itemlist);
brandlist.addActionListener(this);
add(brandlist);
add(new JLabel("contatore"));}
public void actionPerformed(ActionEvent e) {
JButton jb = (JButton) e.getSource();
if (jb == additem) {
JFrame f2 = new JFrame("Add Item");
f2.show();
f2.setLocation(300,300);
f2.setBounds(400,400,400,400);
f2.setResizable(false);
AddItemView additemview = new AddItemView();
Container ct = f2.getContentPane();
ct.add(additemview); }
else if (e.getSource() == addbrand) {
JFrame f3 = new JFrame ("Add Brand");
f3.show();
f3.setLocation(300,300);
f3.setBounds(400,400,400,400);
f3.setResizable(false);
AddBrandView addbrandview = new AddBrandView();
Container ct3 = f3.getContentPane();
ct3.add(addbrandview); }
else if (e.getSource() == brandlist) {
JFrame f4 = new JFrame ("Brand List");
f4.show();
f4.setLocation(300,300);
f4.setBounds(400,400,400,400);
f4.setResizable(false);
BrandListView brandlistview = new BrandListView ();
Container ct4 = f4.getContentPane();
ct4.add(brandlistview);}
else if (e.getSource() == itemlist) {
JFrame f5 = new JFrame ("Brand List");
f5.show();
f5.setLocation(300,300);
f5.setBounds(400,400,400,400);
f5.setResizable(false);
ItemListView itemlistview = new ItemListView ();
Container ct5 = f5.getContentPane();
ct5.add(itemlistview);}
}
}
Considerate che dentro questa classe è anche definito il main che crea il primo frame contenente i 4 bottoni, ma x brevità non l ho inserito.

Rispondi quotando