can't change ImageIcon from anonymous class inside a JPanel - java

I'm currently building a picture sorter. I have a JList which has filenames, to the left of this I have an ImageIcon which should show the picture for the current file_chosen in the JList.
The problem is I can't find a way of updating the ImageIcon contained inside a JLabel; since the change appears inside the anonymous class where the ListSelectionListener() is.
Below is the code:
public class MemeList extends JPanel{
public MemeList(){
// load/update the file list.
updateFileList();
this.setLayout(new GridBagLayout());
JPanel east = new JPanel();
east.setLayout(new GridBagLayout());
gbc.gridx = 1;
gbc.gridy = 0;
this.add(east,gbc);
west = new JPanel();
west.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
this.add(west,gbc);
filearray = flist.toArray(new String[flist.size()]);
list = new JList(filearray);
list.addListSelectionListener(new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
file_chosen = (String) list.getSelectedValue();
System.out.println("selected = "+file_chosen);
}
}
});
meme_preview_icon = new ImageIcon(path + "/" + file_chosen); // file_chosen
label2 = new JLabel("", meme_preview_icon, JLabel.CENTER);
gbc.gridx = 0;
gbc.gridy = 0;
west.add(label2,gbc);
updateIcon();
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
pane.setPreferredSize(new Dimension(320, 340));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0,0,0,0);
east.add(pane, gbc);
}
Below here is the method for changing ImageIcon
public void updateIcon(){
//west.removeAll();
meme_preview_icon = new ImageIcon(path + "/" + file_chosen); // file_chosen
label2.setIcon(meme_preview_icon);
west.revalidate();
west.repaint();
}

I figured out the problem with my flatmate.
I just needed to call the method updateIcon() inside the ListSelectionListener(). I got confused because it told me before it had to be static and then the listener can't be static. But there it is.
list.addListSelectionListener(new ListSelectionListener()
#Override
public void valueChanged(ListSelectionEvent e)
{
if (!e.getValueIsAdjusting())
{
file_chosen = (String) list.getSelectedValue();
System.out.println("selected = "+file_chosen);
updateIcon();
}
}
});

Related

Java Swing ItemListener for CheckBox not responding to state change

What I am after is I would like for whenever someone checks a checkbox, the text for which the box they selected is output to the right panel(I have a split pane). Right now it is not responding so I don't think my BoxHandler is working properly(implements ItemListener). My function addBoxListeners is supposed to add item listeners for each checkbox that I have and the function I overrode in BoxHandler, function itemStateChanged should add text to the right panel, and I know that addText is working because I tested it outside of the itemListener stuff.
void addText(String s) { // adds text to the right panel, adds string s
JLabel temp = new JLabel();
temp.setText(s);
temp.setBorder(border1);
rightPanel.add(temp);
}
void addBoxes() {
int i = 0;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (i = 0; i < 10; i++) {
JCheckBox tempBox = new JCheckBox("word " + i);
boxes.add(tempBox);
leftPanel.add(tempBox, gbc);
//leftPanel.add(new JCheckBox("word" + i), gbc);
}
}
private class BoxHandler implements ItemListener{
public void itemStateChanged(ItemEvent event) {
for (JCheckBox checkBox : boxes) {
if (checkBox.isSelected() ) {
addText(checkBox.getText());
}
}
}
}
void addBoxListeners() { // add listeners to all the boxes in the arraylist
BoxHandler handler = new BoxHandler();
int i = 0;
for ( i = 0; i < boxes.size(); i++) {
boxes.get(i).addItemListener(handler);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CheckBox2 cb = new CheckBox2();
cb.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cb.pack();
cb.setLocationRelativeTo(null);
cb.addBoxListeners();
cb.setVisible(true);
}
Below is part of my class declaration:
public class CheckBox2 extends JFrame {
private ArrayList<JCheckBox> boxes = new ArrayList<JCheckBox>();
JSplitPane splitPane;
EmptyBorder border1 = new EmptyBorder(5, 5, 5, 5);
private JPanel leftPanel = new JPanel();
private JPanel rightPanel = new JPanel();
JLabel labelOne = new JLabel();
JLabel labelTwo = new JLabel();
...

JFrame doesn't dispose()

So, I have a login JFrame which shows up when I run the code. The problem is if the user enters the correct userName and password this login frame needs to be disposed when the other frame is shown up but it doesn't. I tried dispose(), setVisible = false, but still no chance to be hidden or disposed.
class LoggingWindow extends JFrame {
static JFrame loginFrame = new JFrame();
JPanel loginPanel = new JPanel();
JTextField loginNameFld = new JTextField(10);
JPasswordField loginPassFld = new JPasswordField(10);
JTextField statusFld = new JTextField(11);
String userName = "user";
String password = "password";
//Initialize loginFrame
public static void initLoginFrame() {
JFrame loginWindow = new LoggingWindow();
//loginFrame.setTitle("\"Moflo Registration\"");
loginWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginWindow.setResizable(false);
loginWindow.setUndecorated(true);
loginWindow.setVisible(true);
loginWindow.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
loginWindow.setSize(new Dimension(220, 290));
loginWindow.setLocationRelativeTo(null);
loginWindow.pack();
LoggingWindow() {
loginFrame.add(loginPanel);
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints gbb = new GridBagConstraints();
gbb.insets = new Insets(1, 1, 1, 1);
gbb.anchor = GridBagConstraints.CENTER;
JPanel loginNameAndPasswordPanel = new JPanel();
loginPanel.add(loginNameAndPasswordPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 2;
loginNameAndPasswordPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(0,0,0,0);
JLabel loginNameLab = new JLabel("Нэр : ");
gbc.gridx = 0;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameLab, gbc);
JLabel loginPassLab = new JLabel("Нууц үг : ");
gbc.gridx = 0;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassLab, gbc);
loginNameFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 0;
loginNameAndPasswordPanel.add(loginNameFld, gbc);
loginPassFld.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 1;
loginNameAndPasswordPanel.add(loginPassFld, gbc);
statusFld.setEditable(false);
loginNameAndPasswordPanel.add(statusFld, gbc);
statusFld.setHorizontalAlignment(JTextField.CENTER);
JPanel buttonsPanel = new JPanel();
loginPanel.add(buttonsPanel,gbb);
gbb.gridx = 0;
gbb.gridy = 3;
buttonsPanel.setLayout(new GridBagLayout());
GridBagConstraints gba = new GridBagConstraints();
gba.anchor = GridBagConstraints.LINE_END;
gba.insets = new Insets(2, 2, 2, 2);
JButton loginBtn = new JButton("Нэвтрэх");
gba.gridx = 0;
gba.gridy = 0;
buttonsPanel.add(loginBtn, gba);
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
String name = loginNameFld.getText();
String pass = loginPassFld.getText();
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
initMainFrame();
loginFrame.dispose();
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " + showDate, " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
}
});
JButton closeBtn = new JButton(" Хаах ");
gba.gridx = 1;
gba.gridy = 0;
buttonsPanel.add(closeBtn, gba);
add(loginPanel);
closeBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
//Main method
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initLoginFrame();
}
});
}
}
public class MainFrame extends JFrame {
//Initialzie mainFrame
public static void initMainFrame() {
JFrame mainFrame = new MainFrame();
mainFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
mainFrame.setMinimumSize(new Dimension(800, 600));
mainFrame.setLocationRelativeTo(null);
}
some, i think unimportant statements are not shown for the sake of brevity
I believe you confused "loginWindow" with "loginFrame". You try to use
loginFrame.dispose();
but your content is on loginWindow, not loginFrame.
I was able to get it to dispose the username window doing the following.
static JFrame loginWindow; <--- create as class variable, not local.
//loginFrame.add(loginPanel); <--- doesn't appear that this is actually used
if(event.getSource() == loginBtn){
if (name.equals(userName) && pass.equals(password)) {
MainFrame.initMainFrame();
//loginFrame.dispose(); <--- again, not used
loginWindow.dispose(); <--- want to dispose
JOptionPane.showMessageDialog(null, "Системд нэвтэрлээ. Өнөөдөр " , " ", JOptionPane.INFORMATION_MESSAGE);
} else {
statusFld.setText("Нэр эсвэл нууц үг буруу байна.");
}
}
You must also change this:
JFrame loginWindow = new LoggingWindow();
to:
loginWindow = new LoggingWindow();
You can always dispatch the "close" event to the JFrame object:
loginFrame.dispatchEvent(new WindowEvent(loginFrame, WindowEvent.WINDOW_CLOSING));
I definitely confused with loginFrame was indeed useless. I created a class variable: static JFrame loginWindow; but it results NullPointerException.

Can't add JScrollPane to JTextArea

I've searched half the internet and I can't find anybody who has had this same problem.
I've tried several different ways to add a vertical scroll bar, but in vain. Every other post I've seen describing this problem did the following:
JTextArea ta = new JTextArea();
JScrollPane sc = new JScrollPane(ta);
and that seemed to work for them. But I'm out of luck and have tried at least thirty different ways that I've found. I'm new to java and the class I'm in is killing me. Thanks for your time.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame
private JTextArea outputArea {
private JButton eastButton;
private JButton westButton;
private JButton northButton;
private JButton southButton;
private JButton helpButton;
private JButton pickupButton;
private JButton dropButton;
private JButton eatButton;
private JButton lookButton;
private JButton listButton;
private JScrollPane scroll;
Gui() {
int x = 0;
int y = 0;
int Width = 1;
int Height = 2;
int anchor;
GridBagConstraints gbc = new GridBagConstraints();
JLabel actionsLabel = null;
JLabel directionsLabel = null;
getContentPane().setBackground(Color.black);
setTitle("Castle Quest");
actionsLabel = new JLabel("Actions");
actionsLabel.setForeground(Color.red);
directionsLabel = new JLabel("Directions");
directionsLabel.setForeground(Color.red);
outputArea = new JTextArea(25, 35);
scroll = new JScrollPane(outputArea);
eastButton = new JButton("east");
eastButton.setSize(100, 30);
westButton = new JButton("west");
westButton.setSize(100, 30);
northButton = new JButton("north");
northButton.setSize(100, 30);
southButton = new JButton("south");
southButton.setSize(100, 30);
helpButton = new JButton("help");
helpButton.setSize(100, 30);
pickupButton = new JButton("pickup");
pickupButton.setSize(100, 30);
dropButton = new JButton("Drop");
dropButton.setSize(100, 30);
eatButton = new JButton("eat");
lookButton = new JButton("look");
lookButton.setSize(100, 30);
listButton = new JButton("list");
listButton.setSize(100, 30);
outputArea.setEditable(true);
GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
gbc.insets = new Insets(10, 10, 10, 10);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 2;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(actionsLabel, gbc);
gbc.gridy += 2;
add(helpButton, gbc);
gbc.gridy += 2;
add(pickupButton, gbc);
gbc.gridy += 2;
add(dropButton, gbc);
gbc.gridy += 2;
add(eatButton, gbc);
gbc.gridy += 2;
add(lookButton, gbc);
gbc.gridy += 2;
add(listButton, gbc);
gbc.gridy = 1;
gbc.gridx = 2;
gbc.gridheight = 50;
outputArea.setBackground(Color.red);
add(outputArea, gbc);
gbc.gridheight = 2;
gbc.gridx = 3;
gbc.gridy = 1;
add(directionsLabel, gbc);
gbc.gridy = 3;
add(eastButton, gbc);
gbc.gridy += 2;
add(westButton, gbc);
gbc.gridy += 2;
add(northButton, gbc);
gbc.gridy += 2;
add(southButton, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
}
public static void main(String[] args) {
Gui newGame = new Gui();
Game funTime = new Game();
newGame.setSize(400, 150);
newGame.setBackground(Color.black);
newGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newGame.pack();
newGame.setVisible(true);
newGame.outputArea.setLineWrap(true);
newGame.outputArea.setWrapStyleWord(true);
newGame.outputArea.append(funTime.getMessage() + "\n");
newGame.eastButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("east");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.westButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("west");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.northButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("north");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.southButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.move("south");
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
funTime.getHelp();
newGame.outputArea.append(funTime.getMessage() + "\n");
}
});
newGame.pickupButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (funTime.currentLocation.hasItem()) {
funTime.pickupItem();
newGame.outputArea.append(funTime.getMessage() + "\n");
}
}
});
newGame.listButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < funTime.items.size(); i++) {
System.out.println(funTime.items.get(i));
}
System.out.println(funTime.items);
System.out.println(funTime.currentLocation.getRoomItem1() + " & " + funTime.currentLocation.getRoomItem2());
}
});
}
}
The problem you're facing (the JTextArea expanding) is caused by the fact that you added the JTextArea to the container instead of the JScrollPane.
Here is the logic behind what you should do :
JTextArea is contained by JScrollPane and JScrollPane is contained by the JFrame.
Change this line
add(outputArea, gbc);
to this
add(scroll, gbc);

How to Add JTextField & JCheckBox to ArrayList Object

I'm working on my very first GUI app.
I have an ArrayList of the Parent Class Plant of which I have four child classes.
I have some JTextFields with some information and some JCheckBoxs with other information...
The JTextFields should be converted into Strings and the JCheckBoxs into boolean.
I need to add all of these components to an ArrayList and then display the list of the Plants.
How can I do that?
Example:
public class Flower extends Plant{
private boolean thorns;
private boolean smell;
public Flower(String name, String id, String color, boolean blnThorns, boolean blnSmell){
super(name, id, color);
thorns = blnThorns;
smell = blnSmell;
}
public boolean isThorns(){
return thorns;
}
public void setThorns(boolean blnThorns){
thorns = blnThorns;
}
public boolean isSmell(){
return smell;
}
public void setSmell(boolean blnSmell){
smell = blnSmell;
}
}
This is my ArrayList
ArrayList<Plant> plantList = new ArrayList<Plant>();
Here I try to add the parameters for the Flower:
private void addFlower(ArrayList<Plant> plantList){
//Adding window
JFrame addingFrame = new JFrame();
addingFrame.setTitle("Plant Database Interface");
addingFrame.setSize(600, 200);
addingFrame.setLocationRelativeTo(null);
addingFrame.setVisible(true);
//ADDING FRAME LAYOUT
addingFrame.setLayout(new BorderLayout());
//TRAITS
JPanel fields = new JPanel();
addingFrame.add(fields, BorderLayout.NORTH);
JLabel nameLabel = new JLabel("Name:");
JTextField nameField = new JTextField(15);
String name = nameField.getText();
JLabel idLabel = new JLabel("ID:");
JTextField idField = new JTextField(10);
String id = idField.getText();
JLabel colorLabel = new JLabel("Color:");
JTextField colorField = new JTextField(10);
String color = colorField.getText();
fields.add(nameLabel);
fields.add(nameField);
fields.add(idLabel);
fields.add(idField);
fields.add(colorLabel);
fields.add(colorField);
JPanel traits = new JPanel();
addingFrame.add(traits , BorderLayout.CENTER );
JCheckBox thornsBox = new JCheckBox("Thorns Present");
thornsBox.setSelected(false);
traits.add(thornsBox);
JCheckBox smellBox = new JCheckBox("Smell Present");
smellBox.setSelected(false);
traits.add(smellBox);
JPanel southPanel = new JPanel();
addingFrame.add(southPanel, BorderLayout.SOUTH);
JButton addPlantBtn = new JButton("Add Plant");
southPanel.add(addPlantBtn, BorderLayout.EAST);
JButton cancelBtn = new JButton("Cancel");
southPanel.add(cancelBtn, BorderLayout.WEST);
boolean blnThorns;
boolean blnSmell;
//I REALLY DON'T KNOW HOW TO DO THIS PART
thornsBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED){
blnThorns =true;
}
else{
blnThorns = false;
}
}
});
smellBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange() == ItemEvent.SELECTED){
blnSmell =true;
}
else{
blnSmell = false;
}
}
});
addPlantBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//plantList.add(new Flower(name, id, color, blnThorns, blnSmell)); //HOW TO DO????................
}
});
cancelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addingFrame.dispatchEvent(new WindowEvent(addingFrame, WindowEvent.WINDOW_CLOSING));
}
});
}
Use your addPlantBtn ActionListener to gather the information you need when it's called
addPlantBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Flower flower = new Flower(nameField.getText(), idField.getText(), colorField.getText(), thornsBox.isSelected(), smellBox.isSelected());
plantList.add(flower);
You would, also, find it easier, if you created a dedicated JPanel, designed to gather the user details and generate a Flower when you requested it to (from the values of the fields). You could then use this panel on some kind of dialog when ever you needed it.
Have a look at How to Make Dialogs for more details
For example...
public class FlowerPane extends JPanel {
JTextField nameField = new JTextField(15);
JTextField idField = new JTextField(10);
JTextField colorField = new JTextField(10);
JCheckBox smellBox = new JCheckBox("Smell Present");
JCheckBox thornsBox = new JCheckBox("Thorns Present");
public FlowerPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(2, 2, 2, 2);
JLabel nameLabel = new JLabel("Name:");
JLabel idLabel = new JLabel("ID:");
JLabel colorLabel = new JLabel("Color:");
add(nameLabel, gbc);
gbc.gridy++;
add(idLabel, gbc);
gbc.gridy++;
add(idLabel, gbc);
gbc.gridx++;
gbc.gridy = 0;
add(nameField, gbc);
gbc.gridy++;
add(idField, gbc);
gbc.gridy++;
add(colorField, gbc);
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(thornsBox, gbc);
gbc.gridy++;
add(smellBox, gbc);
}
public Flower create() {
return new Flower(nameField.getText(), idField.getText(), colorField.getText(), thornsBox.isSelected(), smellBox.isSelected());
}
}
Which you could then use by doing something like...
FlowerPane flowerPane = new FlowerPane();
switch (JOptionPane.showConfirmDialog(null, flowerPane, "Flower", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) {
case JOptionPane.OK_OPTION:
Flower flower = flowerPane.create();
plantList.add(flower);
break;
}
Or add it to some other container

Swing: how to get value from JTextfield in every JPanel?

My school project is to create a purchasing system for that I create a JPanel array to list out all the products information and also allow user to input something for every item. And I dont know how to get all the values from jtextfields by clicking one button. The actionPerformed() method always requires a final variable which is quite troublesome for me.
private JButton payBtn;
public void shoppingCartTab(Customer userIn){
contentPanel.removeAll();
bottomPanel.removeAll();
final Customer USER = userIn;
ArrayList<Product> pArray = new ArrayList<Product>();
pArray = loadCartFile.loadCartFile(userIn);
JLabel tabLabel = new JLabel("Shopping Cart");
JPanel cartItems = new JPanel();
cartItems.setLayout(new BoxLayout(cartItems, BoxLayout.Y_AXIS));
final JPanel CONSTANT_CART = cartItems;
JScrollPane scroller = new JScrollPane(cartItems);
if(pArray != null){
JPanel item[] = new JPanel[pArray.size()];
for(int i = 0; i< pArray.size(); i++){
item[i] = new JPanel();
final JPanel JPANEL_TO_DEL = item[i];
item[i].setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.weightx = 0.3;
item[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel icon_small = new JLabel(new ImageIcon("Icons\\" + pArray.get(i).getID() + "_small.jpg"));
JLabel itemID = new JLabel(pArray.get(i).getID());
final String CONSTANT_ID = pArray.get(i).getID();
JLabel itemName = new JLabel(pArray.get(i).getName());
JLabel itemPrice = new JLabel("$" + pArray.get(i).getPrice());
JPanel setQuantity = new JPanel();
JButton plusBtn = new JButton("+");plusBtn.setPreferredSize(new Dimension(45,30));
final JTextField QUANTITY = new JTextField("0");QUANTITY.setColumns(3);
QUANTITY.setPreferredSize(new Dimension(45,30));QUANTITY.setHorizontalAlignment(JTextField.CENTER);
JButton minusBtn = new JButton("-");minusBtn.setPreferredSize(new Dimension(45,30));
plusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())<100)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())+1));
}
});
minusBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
if(Integer.parseInt(QUANTITY.getText())>0)
QUANTITY.setText(Integer.toString(Integer.parseInt(QUANTITY.getText())-1));
}
});
setQuantity.add(plusBtn);
setQuantity.add(QUANTITY);
setQuantity.add(minusBtn);
JButton delBtn = new JButton("Delete");
delBtn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure to remove this item from your cart?", "Confirm", JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
CONSTANT_CART.remove(JPANEL_TO_DEL);
revalidate();
repaint();
ShoppingCart.removeItem(USER, CONSTANT_ID);
}
}
});
gBC.gridx = 0;
gBC.gridy = 0;
item[i].add(icon_small,gBC);
gBC.gridx = 1;
gBC.gridy = 0;
item[i].add(itemID,gBC);
gBC.gridx = 2;
gBC.gridy = 0;
item[i].add(itemName,gBC);
gBC.gridx = 3;
gBC.gridy = 0;
item[i].add(itemPrice,gBC);
gBC.gridx = 4;
gBC.gridy = 0;
item[i].add(setQuantity,gBC);
gBC.gridx = 5;
gBC.gridy = 0;
item[i].add(delBtn,gBC);
cartItems.add(item[i]);
}
contentPanel.add(tabLabel);
contentPanel.add(scroller);
payBtn = new JButton("Pay");
bottomPanel.add(payBtn); payBtn.addActionListener(this);
}else{
JLabel emptyMsg = new JLabel("Your cart is empty!");
contentPanel.add(emptyMsg);
}
revalidate();
repaint();
}
One solution would be to create a type which extends JPanel, and exposes a public property, which when called returns the value stored in the JTextField. Something like:
public class TextFieldPanel extends JPanel {
private JTextField myTextField;
public TextFieldPanel()
{
//layout init code here
}
public String getText()
{
return myTextField.getText();
}
}
Then just use this class instead of a regular JPanel. Then when your button is clicked, iterate over each of the objects in your collection, and call getText() on them to get your values.

Categories