Adding ImageIcon to JPanel - java

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

Related

Why is GridBagConstraints gathering the objects in the centre of the JPanel?

In the following code I am creating a JFrame with a JMenuBar and JPanel, the later having three JTextFields and three JLabels. However, all the components of the JPanel are gathering in the center. I've set the layout before adding components so I don't think its this issue (which I've had before). If anyone has anybody ideas how to sort this out I would be much obliged.
public class InterfaceWindow {
private static final Logger LOGGER = Logger.getLogger(DownloadWindow.class.getName());
private JButton helpJButton;
private JButton copyToClipBoardJButton;
private JButton enterJButton;
private JButton selectFileJButton;
private JLabel pathJLabel;
private JLabel jobNameJLabel;
private JLabel emailJLabel;
private JTextField pathJTextField;
private JTextField jobNameJTextField;
private JTextField emailJTextField;
private JTextArea transcriptionJTextArea;
private JMenu accountJMenu;
private JMenu jobsJMenu;
private JMenu helpJMenu;
private JMenuBar toolBarJMenuBar = new JMenuBar();
private JMenuItem uploadYouTubeJMenuItem;
private JMenuItem uploadFileJMenuItem;
private JMenuItem downloadJMenuItem;
private JMenuItem helpJMenuItem;
private GridBagConstraints panelGbc = new GridBagConstraints();
private GridBagConstraints frameGbc = new GridBagConstraints();
private JPanel interfaceJPanel = new JPanel();
private String emptyField = "default";
private String filePath = "default";
public JButton getHelpJButton() {
return helpJButton;
}
public JButton getCopyToClipBoardJButton() {
return copyToClipBoardJButton;
}
public JButton getEnterJButton() {
return enterJButton;
}
public JButton getSelectFileJButton() {
return selectFileJButton;
}
public JFrame setInterfaceWindow() {
JFrame interfaceJFrame = new JFrame();
frameGbc.fill = GridBagConstraints.HORIZONTAL;
interfaceJPanel = setInterfaceJPanel();
interfaceJFrame.getContentPane().setLayout(new GridBagLayout());
interfaceJFrame.setLayout(new GridBagLayout());
interfaceJFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
interfaceJFrame.setTitle("Audio Transcribe");
interfaceJFrame.setSize(800, 800);
interfaceJFrame.setLocationRelativeTo(null);
interfaceJFrame.setJMenuBar(setToolBar(toolBarJMenuBar));
interfaceJFrame.add(interfaceJPanel, frameGbc);
interfaceJFrame.setVisible(true);
return interfaceJFrame;
}
private JPanel setInterfaceJPanel() {
panelGbc.fill = GridBagConstraints.HORIZONTAL;
panelGbc.insets.bottom = 1;
panelGbc.insets.top = 2;
panelGbc.insets.right = 1;
panelGbc.insets.left = 1;
panelGbc.weightx = 1;
panelGbc.weighty = 1;
interfaceJPanel.setLayout(new GridBagLayout());
interfaceJPanel.setSize(800, 700);
setJobName(interfaceJPanel);
setPath(interfaceJPanel);
setEmail(interfaceJPanel);
setButtons(interfaceJPanel);
setTextArea(interfaceJPanel);
setAction();
return interfaceJPanel;
}
public JMenuBar setToolBar(JMenuBar toolBarJMenuBar) {
accountJMenu = new JMenu("Accounts");
jobsJMenu = new JMenu("Jobs");
helpJMenu = new JMenu("Help");
toolBarJMenuBar.add(accountJMenu);
toolBarJMenuBar.add(jobsJMenu);
toolBarJMenuBar.add(helpJMenu);
downloadJMenuItem = new JMenuItem("Download");
uploadFileJMenuItem = new JMenuItem("Upload file");
uploadYouTubeJMenuItem = new JMenuItem("Upload from YouTube");
helpJMenuItem = new JMenuItem("Help");
jobsJMenu.add(downloadJMenuItem);
jobsJMenu.addSeparator();
jobsJMenu.add(uploadFileJMenuItem);
jobsJMenu.addSeparator();
jobsJMenu.add(uploadYouTubeJMenuItem);
helpJMenu.add(helpJMenuItem);
return toolBarJMenuBar;
}
private void setEmail(JPanel interfaceJPanel) {
JLabel emailLabel = new JLabel("Email:");
panelGbc.gridx = 1;
panelGbc.gridy = 3;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(emailLabel, panelGbc);
emailJTextField = new JTextField();
emailJTextField.setText(emptyField);
panelGbc.gridx = 2;
panelGbc.gridy = 3;
panelGbc.gridwidth = 3;
panelGbc.gridheight = 1;
interfaceJPanel.add(emailJTextField, panelGbc);
}
private void setPath(JPanel interfaceJPanel) {
JLabel filePathLabel = new JLabel("File path:");
panelGbc.gridx = 1;
panelGbc.gridy = 0;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(filePathLabel, panelGbc);
pathJTextField = new JTextField();
pathJTextField.setText(filePath);
panelGbc.gridx = 2;
panelGbc.gridy = 0;
panelGbc.gridwidth = 2;
panelGbc.gridheight = 1;
interfaceJPanel.add(pathJTextField, panelGbc);
}
private void setJobName(JPanel interfaceJPanel) {
JLabel jobNameLabel = new JLabel("Job name:");
panelGbc.gridx = 1;
panelGbc.gridy = 2;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(jobNameLabel, panelGbc);
jobNameJTextField = new JTextField();
jobNameJTextField.setText(emptyField);
panelGbc.gridx = 2;
panelGbc.gridy = 2;
panelGbc.gridwidth = 2;
panelGbc.gridheight = 1;
interfaceJPanel.add(jobNameJTextField, panelGbc);
}
private void setAction() {
}
private void setTextArea(JPanel interfaceJPanel) {
}
private void setButtons(JPanel interfaceJPanel) {
}
}
It's because you're nesting two JPanels with GridBagLayout, and when adding the inner JPanel to the outer panel your frameGbc constraint does not have weightx or weighty set, centering the inner JPanel. The inner JPanel will size to its preferredSize, meaning, size as small as allowed, and will be centered.
Best not to do this. Instead let the JFrame continue to use BorderLayout, and add the GridBagLayout using JPanel BorderLayout.CENTER, or don't nest JPanels unnecessarily and just give the contentPane a GridBagLayout.

How do I highlight specific Label when selected from the comboBox?

So I have a database of users in my JComboBox and on the left side is a list of these users as well. What I want to do is write a program when this user is selected from the JComboBox, highlight him in the list(JLabel) on the left side. I hope I was specific enough.
public class Test2 extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panel;
private JComboBox<String> comboBox;
private JList<String> list;
public Test2() {
panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
GridBagLayout gbl_panel = new GridBagLayout();
panel.setLayout(gbl_panel);
comboBox = new JComboBox<String>();
comboBox.addItem("User1");
comboBox.addItem("User2");
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.weightx = 1.0;
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_comboBox.gridx = 0;
gbc_comboBox.gridy = 0;
panel.add(comboBox, gbc_comboBox);
DefaultListModel<String> listModel = new DefaultListModel<>();
listModel.addElement("User1");
listModel.addElement("User2");
list = new JList<String>(listModel);
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.weightx = 1.0;
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
panel.add(list, gbc_lblNewLabel);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedItem = String.valueOf(comboBox.getSelectedItem());
if (selectedItem.equals("User1"))
list.setSelectedValue("User1", true);
else if (selectedItem.equals("User2"))
list.setSelectedValue("User2", true);
}
});
}
public static void main(String[] args) {
Test2 myFrame = new Test2();
myFrame.setVisible(true);
myFrame.setSize(new Dimension(400, 500));
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Will this work for you?. I don't know why you are using JLabel inside JList. So i have changed the list from JList<JLabel> to JList<String>

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.

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.

What is the difference between setSize(), setMaximumSize(),setMinimumSize() when used with GridbagLayout

What is the difference between setSize(), setMaximumSize(),setMinimumSize() when used with GridbagLayout. When I am using setMaximumSize(), it is reducing the height of the panel.If needed I can put SSCCE
Please find the SSCCE:
public class EditUserPanel extends JPanel {
private static final long serialVersionUID = 1L;
private JLabel st_REQ_FIELDS = null;
private JCheckBox ck_ISMANAGER = null;
private JCheckBox ck_ISBPM = null;
private JComboBox cb_LANGUAGE = null;
private JList lb_TEAMS = null;
private JList lb_COUNTRY = null;
private JList lb_BRANDPM = null;
private JTextField ef_NAME = null;
private JTextField ef_USERID = null;
private JScrollPane scr_TEAMS = null;
private JScrollPane scr_COUNTRY = null;
private JScrollPane scr_BRANDPM = null;
private JPanel teamButtonPanel = null;
private JPanel countryButtonPanel = null;
private JPanel brandButtonPanel = null;
private JButton pb_ADD_TEAM = null;
private JButton pb_REMOVE_TEAM = null;
private JButton pb_ADD_COUNTRY = null;
private JButton pb_REMOVE_COUNTRY = null;
private JButton pb_ADD_BRAND = null;
private JButton pb_REMOVE_BRAND = null;
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
public EditUserPanel() {
initialize();
}
public void initialize() {
ck_ISMANAGER = new JCheckBox("Is a Manager");
ck_ISBPM = new JCheckBox("Brand Program Manager");
cb_LANGUAGE = new JComboBox();
lb_TEAMS = new JList();
lb_COUNTRY = new JList();
lb_BRANDPM = new JList();
ef_NAME = new JTextField();
ef_USERID = new JTextField();
scr_TEAMS = new JScrollPane(lb_TEAMS);
scr_COUNTRY = new JScrollPane(lb_COUNTRY);
scr_BRANDPM = new JScrollPane(lb_BRANDPM);
JPanel contentPane = new JPanel();
pb_ADD_TEAM = new JButton("Add Team");
pb_REMOVE_TEAM = new JButton("Remove Team");
pb_ADD_COUNTRY = new JButton("Add Country");
pb_REMOVE_COUNTRY = new JButton("Remove Country");
pb_ADD_BRAND = new JButton("Add Brand");
pb_REMOVE_BRAND = new JButton("Remove Brand");
st_REQ_FIELDS = new JLabel("* = These fields are required");
st_REQ_FIELDS.setForeground(Color.red);
setLayout(new BorderLayout());
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.LINE_AXIS));
contentPane.add(addBasicElements());
add(st_REQ_FIELDS,BorderLayout.PAGE_START);
add(contentPane, BorderLayout.CENTER);
}
private Component addBasicElements() {
// TODO Auto-generated method stub
JPanel basicPanel = new JPanel();
basicPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc= new GridBagConstraints();
gbc=createGbc(0, 0); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* Name : "),ef_NAME),gbc);
gbc=createGbc(1, 0); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* UserID : "), ef_USERID),gbc);
gbc=createGbc(0, 1); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* Language : "), cb_LANGUAGE),gbc);
gbc=createGbc(1, 1); basicPanel.add(addFormPanel(new JPanel(), new JLabel(" "),ck_ISMANAGER),gbc);
gbc=createGbc(0, 2); basicPanel.add(addFormPanel(new JPanel(),new JLabel("Brand Manager : "),(JPanel)addBrandManagerPanel()),gbc);
gbc=createGbc(1, 2); basicPanel.add(addFormPanel(new JPanel(),new JLabel("* Country : "),(JPanel)addCountryPanel()),gbc);
gbc=createGbc(0, 3); basicPanel.add(addFormPanel(new JPanel(), new JLabel("* Team : "), (JPanel)addTeamPanel()),gbc);
basicPanel.setSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2,
(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()));
basicPanel.setBorder(BorderFactory.createEtchedBorder());
return basicPanel;
}
private GridBagConstraints createGbc(int x, int y) {
// TODO Auto-generated method stub
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x; gbc.gridy = y;
gbc.gridwidth = 1; gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
private Component addFormPanel(JComponent jPanel, JComponent label,
JComponent textField) {
// TODO Auto-generated method stub
jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.X_AXIS));
jPanel.add(label);
jPanel.add(textField);
// jPanel.setBorder(BorderFactory.createEtchedBorder());
return jPanel;
}
private Component addTeamPanel() {
// TODO Auto-generated method stub
JPanel teamPanel = new JPanel();
teamPanel.setLayout(new BoxLayout(teamPanel, BoxLayout.Y_AXIS));
teamPanel.add(scr_TEAMS);
teamPanel.add(addTeamButtonPanel());
return teamPanel;
}
private Component addTeamButtonPanel() {
// TODO Auto-generated method stub
teamButtonPanel = new JPanel();
teamButtonPanel.setLayout(new BoxLayout(teamButtonPanel,BoxLayout.X_AXIS));
teamButtonPanel.add(pb_ADD_TEAM);
teamButtonPanel.add(pb_REMOVE_TEAM);
return teamButtonPanel;
}
private Component addCountryPanel() {
// TODO Auto-generated method stub
JPanel countryPanel = new JPanel();
countryPanel.setLayout(new BoxLayout(countryPanel, BoxLayout.Y_AXIS));
countryPanel.add(scr_COUNTRY);
countryPanel.add(addCountryButtonPanel());
return countryPanel;
}
private Component addCountryButtonPanel() {
// TODO Auto-generated method stub
countryButtonPanel = new JPanel();
countryButtonPanel.setLayout(new BoxLayout(countryButtonPanel,BoxLayout.X_AXIS));
countryButtonPanel.add(pb_ADD_COUNTRY);
countryButtonPanel.add(pb_REMOVE_COUNTRY);
return countryButtonPanel;
}
private Component addBrandManagerPanel() {
// TODO Auto-generated method stub
JPanel brandmanagerPanel = new JPanel();
brandmanagerPanel.setLayout(new BoxLayout(brandmanagerPanel, BoxLayout.Y_AXIS));
brandmanagerPanel.add(scr_BRANDPM);
brandmanagerPanel.add(addBrandButtonPanel());
return brandmanagerPanel;
}
private Component addBrandButtonPanel() {
// TODO Auto-generated method stub
brandButtonPanel = new JPanel();
brandButtonPanel.setLayout(new BoxLayout(brandButtonPanel,BoxLayout.X_AXIS));
brandButtonPanel.add(ck_ISBPM);
brandButtonPanel.add(pb_ADD_BRAND);
brandButtonPanel.add(pb_REMOVE_BRAND);
return brandButtonPanel;
}
public static void main(String[] args){
EditUserPanel panel = new EditUserPanel();
JFrame frame = new JFrame("SSCCE for stack overflow");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.setSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),
(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()));
frame.setVisible(true);
}
} /* EditUserPanel */
I have removed all the unused field. Please also find the image when use setSize() and setMaximumSize() with the panel at this line
basicPanel.setSize(new Dimension((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2,
(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()));
basicPanel.setBorder(BorderFactory.createEtchedBorder());
return basicPanel;
Result with setSize():
Result with setMaximumSize():
Question:
1.How to display them nicely because I am not able to achieve it either with setSize() or setMaximumSize()
More Information:
I can use pack() on JFrame to make it correct in this above but in my actual code this panel is appearing inside other panel and so far I could not find the place to use pack. If there is anything equivalent to pack for JPanel I would be happy to use that.
With setSize() you define the size of your grid. With setMaximumSize() you tell the grid that if the user enlarges his window, the grid won't increase more than the given size. With setMinimumSize(), it is the equivalent for shrinking the window.

Categories