I'm attempting to implement a changelistener on a JSlider. I've tried two separate methods neither has worked. The commented out section is the first attempt. The one that's implemented now would probably be the better suited for my purposes. Can anyone point out what is going wrong with this:
public class MixWindow extends JFrame implements ChangeListener{
private JPanel contentPane;
public static int uniA [] = new int [512];
ChangeListener sizeAction;
int level = 0;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MixWindow frame = new MixWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
initUni();
}
public MixWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JSlider slider = new JSlider(0,255);
slider.setOrientation(SwingConstants.VERTICAL);
slider.setBounds(66, 275, 72, 140);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(20);
slider.setValue(uniA[0]);
//slider.addChangeListener(sizeAction);
contentPane.add(slider);
final JLabel label = new JLabel("");
label.setBounds(66, 262, 61, 16);
contentPane.add(label);
/*sizeAction=new ChangeListener()
{
public void stateChanged (ChangeEvent event)
{
System.out.println("This is getting silly");
JSlider slider=(JSlider)event.getSource();
level=slider.getValue();
uniA[0] = level;
String temp = String.valueOf(level);
label.setText(temp);
}
};*/
}
public static void initUni(){
for(int i = 0; i < uniA.length; i++){
uniA[i] = 0;
}
}
#Override
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Stuff has changed");
Object source = arg0.getSource();
System.out.println(arg0 + " has Changed");
}
}
The reason the ChangeListener isn't working in your 1st approach, is that your listener reference sizeAction is null when you register the listener.
slider.addChangeListener(sizeAction);
While this won't throw an exception, it won't register the listener when it is instantiated.
Simply alllow this line to appear after you define the listener and it will start working.
If you wish to use your other ChangeListener implementation instead you can use:
slider.addChangeListener(this);
Related
I have been working on some side project involving MySQL, with will use tree different screens: 'menu, ' add breed', 'browse breed'.
At this point section initialize is getting quite large and I would like to split it into 3 different classes.
Is it possible to initialize for example JPanel outside Window class?
public class Window {
public static void setBreed()
{
for(int i=0; i<16;i++) {
breedLabels[i].setText(breedInfo[i]);
breedLabels[i].setBounds(600,100+i*30,300, 100);
breedLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(breedLabels[i]);
}
}
public static void setText()
{
for(int i=0; i<16;i++) {
textLabels[i].setText(text[i]);
textLabels[i].setBounds(300,100+i*30,300, 100);
textLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(textLabels[i]);
}
}
public static String URL = "jdbc:mysql://localhost:3306/chooseyourpuppy";
public static String user = "root";
public static String password = "";
public static String query = "select * from breeds";
static String [] breedInfo = new String[16];
static String [] text = new String[16];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
View.connect(URL, user, password, query);
}
public Window() {
initialize();
}
private JFrame frame;
public JPanel addBreed;
public static JPanel viewBreed;
public JPanel menu;
public static JLabel[] textLabels;
public static JLabel[] breedLabels;
private void initialize() {
final int WIDTH = 1280, HEIGHT = 720;
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("MyBREEDS Viewer");
frame.setResizable(false);
frame.setVisible(true);
//header
JPanel red = new JPanel();
red.setBounds(400, 0, 888, 80);
frame.getContentPane().add(red);
red.setBackground(new Color(204, 0, 0));
red.setLayout(null);
JPanel darkGrey = new JPanel();
darkGrey.setBounds(0, 0, 387, 80);
frame.getContentPane().add(darkGrey);
darkGrey.setBackground(new Color(51, 51, 51));
darkGrey.setLayout(null);
JLabel txtpnChoose = new JLabel();
txtpnChoose.setForeground(new Color(240, 240, 240));
txtpnChoose.setBounds(56, 11, 367, 63);
txtpnChoose.setFont(new Font("Verdana", Font.BOLD, 46));
txtpnChoose.setText("Choose your");
txtpnChoose.setBackground(null);
darkGrey.add(txtpnChoose);
JLabel txtpnPuppy = new JLabel();
txtpnPuppy.setBounds(5, 11, 166, 63);
txtpnPuppy.setForeground(new Color(240, 240, 240));
txtpnPuppy.setFont(new Font("Nunito-Bold", Font.BOLD, 46));
txtpnPuppy.setText("puppy");
txtpnPuppy.setBackground(null);
red.add(txtpnPuppy);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, WIDTH, HEIGHT);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
JButton btnMenu = new JButton("Back to menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(menu);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnMenu.setForeground(Color.WHITE);
btnMenu.setBackground(new Color(51, 51, 51));
btnMenu.setFont(new Font("Verdana", Font.BOLD, 18));
btnMenu.setBounds(660, 20, 180, 40);
btnMenu.setBorderPainted(false);
btnMenu.setFocusPainted(false);
red.add(btnMenu);
//menu
menu = new JPanel();
menu.setBackground(Color.WHITE);
layeredPane.add(menu, "name_410359960271086");
menu.setLayout(null);
JButton btnBrowse = new JButton("Browse breeds");
btnBrowse.setBounds(100, 300, 400, 200);
btnBrowse.setFont(new Font("Verdana", Font.PLAIN, 40));
btnBrowse.setBorder(new LineBorder(Color.DARK_GRAY));
btnBrowse.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnBrowse.setBackground(Color.WHITE);
btnBrowse.setRequestFocusEnabled(false);
btnBrowse.setVisible(true);
btnBrowse.setFocusPainted(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(viewBreed);
layeredPane.repaint();
layeredPane.revalidate();
setText();
setBreed();
}
});
btnBrowse.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnBrowse.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnBrowse.setBackground(Color.WHITE);
}
});
menu.add(btnBrowse);
addBreed = new JPanel();
layeredPane.add(addBreed, "name_410359942089403");
addBreed.setVisible(false);
addBreed.setBackground(Color.WHITE);
addBreed.setLayout(null);
//view breed window
viewBreed = new JPanel();
layeredPane.add(viewBreed, "name_410359924014670");
viewBreed.setLayout(null);
viewBreed.setVisible(false);
viewBreed.setBackground(Color.WHITE);
ImageIcon previous = new ImageIcon("src/images/previous.png");
ImageIcon previousHover = new ImageIcon("src/images/previousHover.png");
JButton prevBreed = new JButton(previous);
prevBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
prevBreed.setIcon(previousHover);
}
#Override
public void mouseExited(MouseEvent e) {
prevBreed.setIcon(previous);
}
});
prevBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(false);
}
});
prevBreed.setBounds(30, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(prevBreed);
prevBreed.setRequestFocusEnabled(false);
prevBreed.setOpaque(false);
prevBreed.setContentAreaFilled(false);
prevBreed.setBorderPainted(false);
prevBreed.setFocusPainted(false);
ImageIcon next = new ImageIcon("src/images/next.png");
ImageIcon nextHover = new ImageIcon("src/images/nextHover.png");
JButton nextBreed = new JButton(next);
nextBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
nextBreed.setIcon(nextHover);
}
#Override
public void mouseExited(MouseEvent e) {
nextBreed.setIcon(next);
}
});
nextBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(true);
}
});
nextBreed.setBounds(1140, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(nextBreed);
nextBreed.setRequestFocusEnabled(false);
nextBreed.setVisible(true);
nextBreed.setOpaque(false);
nextBreed.setContentAreaFilled(false);
nextBreed.setBorderPainted(false);
nextBreed.setFocusPainted(false);
//add breed window
JButton btnAdd = new JButton("Add new breed");
btnAdd.setBounds(780, 300, 400, 200);
btnAdd.setFont(new Font("Verdana", Font.PLAIN, 40));
btnAdd.setBorder(new LineBorder(Color.DARK_GRAY));
btnAdd.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnAdd.setBackground(Color.WHITE);
btnAdd.setRequestFocusEnabled(false);
btnAdd.setFocusPainted(false);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(addBreed);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnAdd.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnAdd.setBackground(Color.WHITE);
}
});
menu.add(btnAdd);
breedLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
breedLabels[i] = new JLabel(breedInfo[i]);
}
textLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
textLabels[i] = new JLabel(breedInfo[i]);
}
}
}
Is it possible to initialize for example JPanel outside Window class?"
Yes. A different class might contain a method that creates & returns a JPanel.
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
new Font("Verdana", Font.PLAIN, 20) Use defaults or logical fonts (E.G. Font.SERIF) unless the font is supplied with your app. as an embedded resource.
The loop and array of labels that are added to viewBreed suggest it should be a JList rather than a JPanel
layeredPane.removeAll(); .. Ugh.. Use a CardLayout as shown in this answer.
What is the purpose of the JLayeredPane? I expect it's unnecessary purely on the basis that there is so little use for them.
I want to pass a variable from a JFrame to another when I'm pressing the btnCalculeaza button.
Here is my code:
JButton btnCalculeaza = new JButton("Calculeaza");
btnCalculeaza.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int algad = Integer.parseInt(textField.getText());
int analiza = Integer.parseInt(textField_1.getText());
int be = Integer.parseInt(textField_2.getText());
int depcom = Integer.parseInt(textField_3.getText());
int engleza1 = Integer.parseInt(textField_4.getText());
int engleza2= Integer.parseInt(textField_5.getText());
int fizica= Integer.parseInt(textField_6.getText());
int grafica= Integer.parseInt(textField_7.getText());
int informatica= Integer.parseInt(textField_8.getText());
int matematici= Integer.parseInt(textField_9.getText());
int programare1= Integer.parseInt(textField_10.getText());
int programare2= Integer.parseInt(textField_11.getText());
int tpsm= Integer.parseInt(textField_12.getText());
double nota1;
nota1=(7*algad+analiza*6.0+7*be+3*depcom+2*engleza1+2*engleza2+fizica*7+grafica*3+informatica*4+matematici*6+programare1*5+programare2*4+tpsm*4)/60;
System.out.println(nota1);
new Anul2(nota1).setVisible(true);
Anul2 anul2 =new Anul2();
anul2.setVisible(true);
frame.dispose();
}
});
And the second JFrame:
public class Anul2 extends JFrame {
private double nota1;
public Anul2(double nota1) {
this.nota1 = nota1;
}
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Anul2 frame = new Anul2();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Anul2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 527, 407);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblMediaGeneralaPana = new JLabel("Media generala pana acum:");
lblMediaGeneralaPana.setBounds(12, 331, 160, 16);
contentPane.add(lblMediaGeneralaPana);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setText(Double.toString(nota1));
lblNewLabel.setBounds(171, 331, 56, 16);
contentPane.add(lblNewLabel);
}
}
I would like to pass the nota1 variable to the second JFrame(called Anul2) and then I want to convert it to a JLabel
Your real problem is that your mixing up responsibilities in your code.
You should fully separate your data processing form your UI stuff.
Meaning: you have a local variable
nota1=(7*algad+analiza*6.0+7*be+3*depcom+2*engleza1+2*engleza2+fizica*7+grafica*3+informatica*4+matematici*6+programare1*5+programare2*4+tpsm*4)/60;
and its extremely complicated computation within an action listener. Such things don't belong there.
Instead, you should have a distinct class that only holds all the parameters required for that computation. And then, that class has probably a method computeNota().
Now: in your action listener, you create an object of that class, and then you could pass on that object to new JFRame for example.
Decouple the processing of your data from showing it to the user!
Two ways,
Pass a reference of the first JFrame to the second JFrame Constructor.
Use getFrames() method along with getDeclaredFields() to get the nota1 variable value.
I've two class. Can i change a text of a button in a class "home" with an actionlistener of the combobox in a class "panelGestisciImpianti"? I don't unterstand becasue don't works.
The code is this:
//home
package s;
public class home extends JFrame {
private JPanel contentPane;
private panelImpostazioni panel5= new panelImpostazioni();
private JButton btnImpostazioni = new JButton("no"); //$NON-NLS-1$
public static void main(String[] args) {
home frame = new home();
frame.setVisible(true);
}
public home() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState( JFrame.MAXIMIZED_BOTH) ;
setBounds(0, 0, 1963, 688);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
btnImpostazioni.setBounds(0, 560, 140, 140);
contentPane.add(btnImpostazioni);
btnImpostazioni.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.add(panel5);
revalidate();
repaint();
}
});
}
public void changetext() {
btnImpostazioni.setText("yes");
}
}
//panelGestisciImpostazioni
package s;
public class panelImpostazioni extends JPanel {
private JComboBox comboboxLingua = new JComboBox();
static home h=new home();
public panelImpostazioni() {
setBounds(140, 0, 800, 560);
setLayout(null);
comboboxLingua.setBounds(100, 24, 150, 45);
comboboxLingua.setModel(new DefaultComboBoxModel(new String[] {"italiano", "inglese"}));
add(comboboxLingua);
comboboxLingua.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
h.changetext();
}
});
}
}
Thank you.
Its because when you create panel5 you have a new home created.
static home h = new home ().
So when you call changetext method you do it in a new invisible frame.
In order to make this work (it is really really bad) you have to pass your visible "home" as an argument to your panel5. Which means you have to initiate it in home's constructor and not as a field.
public panelImpostazioni(home h)
And in your combobox action listener
h.changetext ()
public class Sort_BenchMark extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnBubbleSort;
private JLabel label_1;
private JButton btnGenerate;
private JButton btnSelectionSort;
private JLabel lblSs;
private JLabel lblStatus;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
Sort_BenchMark frame = new Sort_BenchMark();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Sort_BenchMark()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField("Enter ");
textField.setForeground(Color.GRAY);
textField.addFocusListener(new FocusListener() {
#Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub
}
#Override
public void focusGained(FocusEvent e) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
});
textField.setBounds(29, 30, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
label_1 = new JLabel("");
label_1.setBounds(334, 20, 120, 30);
contentPane.add(label_1);
btnBubbleSort = new JButton("Bubble Sort");
btnBubbleSort.setBounds(204, 20, 120, 30);
contentPane.add(btnBubbleSort);
btnSelectionSort = new JButton("Selection Sort");
btnSelectionSort.setBounds(204, 70, 120, 30);
contentPane.add(btnSelectionSort);
lblSs = new JLabel("");
lblSs.setBounds(334, 70, 120, 30);
contentPane.add(lblSs);
lblStatus = new JLabel("");
lblStatus.setBounds(75, 87, 93, 23);
contentPane.add(lblStatus);
final JRadioButton rdbtnAvgCase = new JRadioButton("Avg Case");
rdbtnAvgCase.setBounds(29, 150, 109, 23);
contentPane.add(rdbtnAvgCase);
ButtonGroup b = new ButtonGroup();
b.add(rdbtnAvgCase);
btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
btnBubbleSort.setEnabled(true);
btnSelectionSort.setEnabled(true);
final String s = textField.getText();
if(s.contentEquals(""))
{
lblStatus.setText("Enter length");
}
else
{
lblStatus.setText("Ready");
if(rdbtnAvgCase.isSelected())
{
btnBubbleSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t1 = new Thread(new Runnable()
{
#Override
public void run()
{
btnBubbleSort.setEnabled(false);
label_1.setText("done");
btnBubbleSort.setEnabled(true);
}
});
t1.start();
}
});
btnSelectionSort.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Thread t3 = new Thread(new Runnable()
{
#Override
public void run()
{
btnSelectionSort.setEnabled(false);
lblSs.setText("done");
btnSelectionSort.setEnabled(true);
}
});
t3.start();
}
});
}
}
}
});
btnGenerate.setBounds(64, 62, 88, 25);
contentPane.add(btnGenerate);
}
}
The above code is about Swing.
The actual code how i designed is:-(In the frame)
Select the Average Case (RadioButton)
Enter any number in textfield (Enter)
click on generate
click on any sort button(Bubble Sort and Selection Sort)
Now, whats the problem is, If I click on BubbleSort the text field gets cleared. But it should not happen as per I designed. Can anyone suggest me the solution so that text field wont get clear after entered anything in it?
These lines here:
#Override
public void focusGained(FocusEvent e) {
textField.setText(""); //HERE
textField.setForeground(Color.BLACK);
}
in the focus listener code says that when you click in the textfield then set its text to a empty string.
Firstly, horrible nested ActionPerformed you've got there.
That aside, Vincent Ramdhanie is right as to where the problem is originating. The reason why it only happens when you click a certain button, is because when you disable a button, then it cannot have focus, which forces the focus to be on something else, which in the disable-btnBubbleSort's case, appears to be your textfield.
Instead of btnSelectionSort.setEnabled(false) and btnSelectionSort.setEnabled(true), try using setVisible(false) and setVisible(true).
If that doesn't work, drop the onfocus-part, and do something with a mouse-click event instead.
I've got this strange thing, I'm trying to add to the ArrayList but it does not add, it get the values and everything. Please check the code and brigthen me up.
The class where I am trying to add:
public class ManualProductGUI extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField barcodeField;
private JTextField idField;
private JTextField nameField;
private JTextField priceField;
private JTextField quantityField;
private JTextField infoField;
BasketContainer bc = new BasketContainer();
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
ManualProductGUI dialog = new ManualProductGUI();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public ManualProductGUI() {
setTitle("Product search");
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
barcodeField = new JTextField();
barcodeField.setText("Enter barcode");
barcodeField.setBounds(10, 11, 157, 20);
contentPanel.add(barcodeField);
barcodeField.setColumns(10);
barcodeField.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
barcodeField.setText("");
}
});
barcodeField.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int barcode = Integer.parseInt(barcodeField.getText());
ProductCtr prodCtr = new ProductCtr();
Product prod = prodCtr.searchProductByBarcode(barcode);
buildFields(prod);
}
});
infoField = new JTextField();
infoField.setEditable(false);
infoField.setBounds(177, 133, 86, 20);
contentPanel.add(infoField);
infoField.setColumns(10);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("Add");
okButton.setActionCommand("Add");
buttonPane.add(okButton);
okButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addToBasket();
setVisible(false);
dispose();
}
});
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
cancelButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
setVisible(false);
dispose();
}
});
buttonPane.add(cancelButton);
}
}
}
private void addToBasket()
{
int barcode = Integer.parseInt(barcodeField.getText());
ProductCtr prodCtr = new ProductCtr();
Product prod = prodCtr.searchProductByBarcode(barcode);
bc.addProduct(prod);
}
}
And here is a part of the Container class:
private ArrayList<Product> listOfItems;
public BasketContainer()
{
listOfItems = new ArrayList<>();
}
public void addProduct(Product prod)
{
listOfItems.add(prod);
}
public ArrayList<Product> getProducts()
{
return listOfItems;
}
It prints out the info on the screen, but it does not add. Am I missing something?
Thank you.
You create a new instance of BasketContainer every time, so that new instances will have a new clear ArrayList.
To fix it you should create your BasketContainer instance somewhere (maybe in an init block?) and save the reference, then use it to add the elements.
You're creating a new BasketContainer within the scope of the method.
BasketContainer bc = new BasketContainer();
bc.addProduct(prod);
The addToBasket method should call addProduct on a field of the class it's in.