Мне нужно напечатать выбранный элемент при нажатии кнопки «Поиск», но он печатает начальное значение, а не выбранное. Это должно быть связано с наследованием между выбором и данными, но что именно я не понимаю. Из-за чего это происходит?
Буду очень рад всем полезным советам.
public class Selection extends JFrame {
JLabel currency;
protected JComboBox currencies;
JButton search = new JButton("Search");
public Selection() {
final GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
final GridBagConstraints c = new GridBagConstraints();
currency = new JLabel("Currency:");
String[] cur = {"USD", "EUR"};
currencies = new JComboBox(cur);
currencies.setBackground(Color.WHITE);
search.setBackground(Color.ORANGE);
search.setFocusPainted(false);
search.setForeground(Color.WHITE);
search.setFont(new Font("Times New Roman", Font.BOLD, 23));
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.fill = GridBagConstraints.NONE;
c.gridheight = 1;
c.gridwidth = 1;
c.insets = new Insets(10, 10, 0, 0);
c.gridx = GridBagConstraints.HORIZONTAL;
gbl.setConstraints(currency, c);
add(currency);
gbl.setConstraints(currencies, c);
add(currencies);
gbl.setConstraints(search, c);
add(search);
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Data data = new Data();
data.print();
}
});
}
protected String getCurrency() {
return String.valueOf(currencies.getSelectedItem());
}
}
public class Data extends Selection {
public void print() {
System.out.println(getCurrency());
}
}
public class MainClass {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame selection = new Selection();
selection.setExtendedState(Frame.MAXIMIZED_BOTH);
selection.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
selection.setVisible(true);
selection.getContentPane().setBackground(Color.WHITE);
}
});
}
}