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

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.

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();
...

Adding ImageIcon to JPanel

I'm working with a chat app and trying to integrate profile pictures into the code. For now, I'm just trying to get a simple static "smiley.png" to display in my gui. doing this:
final ImageIcon profilePicture = new ImageIcon(getClass().getResource("smiley.png"));
final JLabel profileLabel = new JLabel(profilePicture);
currentPanel.add(profileLabel);
results in a ERROR: Exception in ChatSimpleGui.run. Check log for details. (Log is nonexistent as I run this from terminal)
Please help?
Here is full code for this particular class:
package codeu.chat.client.simplegui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import codeu.chat.client.ClientContext;
import codeu.chat.common.User;
// NOTE: JPanel is serializable, but there is no need to serialize UserPanel
// without the #SuppressWarnings, the compiler will complain of no override for serialVersionUID
#SuppressWarnings("serial")
public final class UserPanel extends JPanel {
private final ClientContext clientContext;
public UserPanel(ClientContext clientContext) {
super(new GridBagLayout());
this.clientContext = clientContext;
initialize();
}
private void initialize() {
// This panel contains from top to bottom; a title bar, a list of users,
// information about the current (selected) user, and a button bar.
// Title bar - also includes name of currently signed-in user.
final JPanel titlePanel = new JPanel(new GridBagLayout());
final GridBagConstraints titlePanelC = new GridBagConstraints();
final JLabel titleLabel = new JLabel("Users", JLabel.LEFT);
final GridBagConstraints titleLabelC = new GridBagConstraints();
titleLabelC.gridx = 0;
titleLabelC.gridy = 0;
titleLabelC.anchor = GridBagConstraints.PAGE_START;
final GridBagConstraints titleGapC = new GridBagConstraints();
titleGapC.gridx = 1;
titleGapC.gridy = 0;
titleGapC.fill = GridBagConstraints.HORIZONTAL;
titleGapC.weightx = 0.9;
final JLabel userSignedInLabel = new JLabel("not signed in", JLabel.RIGHT);
final GridBagConstraints titleUserC = new GridBagConstraints();
titleUserC.gridx = 2;
titleUserC.gridy = 0;
titleUserC.anchor = GridBagConstraints.LINE_END;
titlePanel.add(titleLabel, titleLabelC);
titlePanel.add(Box.createHorizontalGlue(), titleGapC);
titlePanel.add(userSignedInLabel, titleUserC);
titlePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
// User List panel.
final JPanel listShowPanel = new JPanel();
final GridBagConstraints listPanelC = new GridBagConstraints();
final DefaultListModel<String> listModel = new DefaultListModel<>();
final JList<String> userList = new JList<>(listModel);
userList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
userList.setVisibleRowCount(10);
userList.setSelectedIndex(-1);
final JScrollPane userListScrollPane = new JScrollPane(userList);
listShowPanel.add(userListScrollPane);
userListScrollPane.setPreferredSize(new Dimension(150, 150));
//PASSWORD FIELD
final JTextField passwordField = new JTextField();
listShowPanel.add(passwordField);
passwordField.setPreferredSize(new Dimension(100, 20));
//STATUS FIELD to be implemented shortly
//final JTextField statusField = new JTextField();
//listShowPanel.add(statusField);
//statusField.setPreferredSize(new Dimension(100, 20));
// Current User panel
final JPanel currentPanel = new JPanel();
final GridBagConstraints currentPanelC = new GridBagConstraints();
final JTextArea userInfoPanel = new JTextArea();
final JScrollPane userInfoScrollPane = new JScrollPane(userInfoPanel);
currentPanel.add(userInfoScrollPane);
userInfoScrollPane.setPreferredSize(new Dimension(245, 85));
final ImageIcon profilePicture = new ImageIcon(getClass().getResource("smiley.png"));
final JLabel profileLabel = new JLabel(profilePicture);
currentPanel.add(profileLabel);
// Button bar
final JPanel buttonPanel = new JPanel();
final GridBagConstraints buttonPanelC = new GridBagConstraints();
final JButton userUpdateButton = new JButton("Update");
final JButton userSignInButton = new JButton("Sign In");
final JButton userAddButton = new JButton("Add");
buttonPanel.add(userUpdateButton);
buttonPanel.add(userSignInButton);
buttonPanel.add(userAddButton);
// Placement of title, list panel, buttons, and current user panel.
titlePanelC.gridx = 0;
titlePanelC.gridy = 0;
titlePanelC.gridwidth = 10;
titlePanelC.gridheight = 1;
titlePanelC.fill = GridBagConstraints.HORIZONTAL;
titlePanelC.anchor = GridBagConstraints.FIRST_LINE_START;
listPanelC.gridx = 0;
listPanelC.gridy = 1;
listPanelC.gridwidth = 10;
listPanelC.gridheight = 8;
listPanelC.fill = GridBagConstraints.BOTH;
listPanelC.anchor = GridBagConstraints.FIRST_LINE_START;
listPanelC.weighty = 0.8;
currentPanelC.gridx = 0;
currentPanelC.gridy = 9;
currentPanelC.gridwidth = 10;
currentPanelC.gridheight = 3;
currentPanelC.fill = GridBagConstraints.HORIZONTAL;
currentPanelC.anchor = GridBagConstraints.FIRST_LINE_START;
buttonPanelC.gridx = 0;
buttonPanelC.gridy = 12;
buttonPanelC.gridwidth = 10;
buttonPanelC.gridheight = 1;
buttonPanelC.fill = GridBagConstraints.HORIZONTAL;
buttonPanelC.anchor = GridBagConstraints.FIRST_LINE_START;
this.add(titlePanel, titlePanelC);
this.add(listShowPanel, listPanelC);
this.add(buttonPanel, buttonPanelC);
this.add(currentPanel, currentPanelC);
userUpdateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
UserPanel.this.getAllUsers(listModel);
}
});
userSignInButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (userList.getSelectedIndex() != -1) {
final String name = userList.getSelectedValue();
final String password = passwordField.getText();
if (clientContext.user.signInUser(name, password)){
userSignedInLabel.setText("Hello " + name);
} else{
userSignedInLabel.setText("User Not Found");
}
}
}
});
userAddButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final String s = (String) JOptionPane.showInputDialog(
UserPanel.this, "Enter user name:", "Add User", JOptionPane.PLAIN_MESSAGE,
null, null, "");
//CHECK VALID UNIQUE USERNAME: either here or ClientUser.java
final String password = (String) JOptionPane.showInputDialog(
UserPanel.this, "Set password:", "Add password", JOptionPane.PLAIN_MESSAGE,
null, null, "");
final String status = (String) JOptionPane.showInputDialog(
UserPanel.this, "Set status:", "Post!", JOptionPane.PLAIN_MESSAGE,
null, null, "");
if (s != null && s.length() > 0) {
clientContext.user.addUser(s, password, status);
UserPanel.this.getAllUsers(listModel);
}
}
});
userList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (userList.getSelectedIndex() != -1) {
final String data = userList.getSelectedValue();
userInfoPanel.setText(clientContext.user.showUserInfo(data));
}
}
});
getAllUsers(listModel);
}
// Swing UI: populate ListModel object - updates display objects.
private void getAllUsers(DefaultListModel<String> usersList) {
clientContext.user.updateUsers();
usersList.clear();
for (final User u : clientContext.user.getUsers()) {
usersList.addElement(u.name);
}
}
}
Try this:
Jlabel imageLogo = new JLabel();
imageLogo.setIcon(new ImageIcon("path/to/your/image"));
Hope you saved your image in your project folder

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.

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

can't change ImageIcon from anonymous class inside a JPanel

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();
}
}
});

Categories