I'm try to make a checkin form and i'm trying to design it well but i'm getting this error NullPointer exception.
Here's my code:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class CheckIn extends JPanel{
private String[] text = {" First Name"," Last Name"," Age"," Gender"," Contact No",
" Address"," Room Type"," Room No"," Time In"," How many days"," Payment Method"};
private JPanel designPanel,bottomRightPanel,bottomLeftPanel;
private String[] genderJCB = {"- Select Gender- ","Male","Female"};
private String[] roomJCB = {"- Select Room Type -","Classic","Deluxe","Presidential"};
private JButton submit,cancel;
private JRadioButton fullRB,depositRB;
private buttonHandler bh;
JTextField[] textFields;
private JComboBox<String> genderBox,roomTypeBox ;
public CheckIn(){
//Container settings
setLayout(null);
setBackground(new Color(70,70,70));
//title
JLabel title = new JLabel("Personal Information",SwingConstants.CENTER);
title.setBounds(0,0,300,45);
title.setForeground(Color.ORANGE);
title.setFont(new Font("Arial",Font.BOLD,13));
title.setBorder(BorderFactory.createMatteBorder(0,0,1,0,Color.BLACK));
add(designPanel());
add(title);
//fields
}
public JPanel designPanel()
{
//Sub container settings
designPanel = new JPanel( new GridLayout(12,2));
designPanel.setBounds(0,45,300,505);
designPanel.setBackground(new Color(80,80,80));
designPanel.add(bottomLeftPanel());
designPanel.add(bottomRightPanel());
return designPanel;
}
public JPanel bottomLeftPanel()
{
JPanel bottomLeftPanel = new JPanel();
bottomLeftPanel.setLayout(null);
bottomLeftPanel.setBorder(BorderFactory.createMatteBorder(1,0,0,0,Color.GRAY));
bottomLeftPanel.setBackground(new Color(70,70,70));
bottomButtons();
return bottomLeftPanel;
}
public JPanel bottomRightPanel()
{
JPanel bottomRightPanel = new JPanel();
bottomRightPanel.setLayout(null);
bottomRightPanel.setBorder(BorderFactory.createMatteBorder(1,0,0,0,Color.GRAY));
bottomRightPanel.setBackground(new Color(70,70,70));
bottomButtons();
return bottomRightPanel;
}
public void bottomButtons()
{
bh = new buttonHandler();
cancel = new JButton("Cancel");
cancel.setBounds(25,4,100,32);
cancel.addActionListener(bh);
bottomLeftPanel.add(cancel);
submit = new JButton("Submit");
submit.setBounds(25,4,100,32);
submit.addActionListener(bh);
bottomRightPanel.add(submit);
}
public void components()
{
JLabel[] labels = new JLabel[text.length];
JTextField[] textFields = new JTextField[text.length];
JPanel[] containerPanel = new JPanel[text.length];
for(int x = 0; x < text.length; x++){
//labels
labels[x] = new JLabel(text[x]);
labels[x].setForeground(Color.WHITE);
labels[x].setBorder(new CompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)));
designPanel.add(labels[x]);
containerPanel[x]= new JPanel();
containerPanel[x].setLayout(null);
containerPanel[x].setBackground(new Color(80,80,80));
containerPanel[x].setBorder(new CompoundBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.GRAY),
BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)));
designPanel.add(containerPanel[x]);
//text fields and etc
if(x==3){
genderBox = new JComboBox(genderJCB);
genderBox.setBounds(0,10,120,25);
genderBox.setBackground(Color.WHITE);
containerPanel[x].add(genderBox);
}
else if(x==6){
roomTypeBox = new JComboBox(roomJCB);
roomTypeBox.setBounds(0,10,145,25);
roomTypeBox.setBackground(Color.WHITE);
containerPanel[x].add(roomTypeBox);
}
else if(x==8){
SpinnerDateModel model = new SpinnerDateModel();
model.setCalendarField(Calendar.MINUTE);
JSpinner spinner= new JSpinner();
spinner.setModel(model);
spinner.setEditor(new JSpinner.DateEditor(spinner, "h:mm a "));
spinner.setBounds(0,10,145,25);
containerPanel[x].add(spinner);
}
else if (x==10){
ButtonGroup group = new ButtonGroup();
fullRB = new JRadioButton("Full");
fullRB.setBounds(0,10,50,25);
fullRB.setBackground(new Color(80,80,80));
fullRB.setForeground(Color.white);
depositRB = new JRadioButton("Deposit");
depositRB.setBounds(60,10,70,25);
depositRB.setBackground(new Color(80,80,80));
depositRB.setForeground(Color.white);
group.add(fullRB);
group.add(depositRB);
containerPanel[x].add(fullRB);
containerPanel[x].add(depositRB);
}
else {
textFields[x] = new JTextField();
textFields[x].setBounds(0,10,145,25);
containerPanel[x].add(textFields[x]);
}
}
}
private class buttonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == cancel){
}
else if(e.getSource() == fullRB){
}
}
}
}
Sorry if my work is such a mess. I'm trying my best to simplify it. And that's what i've come up. How can i simplify more my code? and how can i fix my error. Please help and sorry for a noob question.
And here is the stack trace:
Exception in thread "main" java.lang.NullPointerException
at CheckIn.bottomButtons(CheckIn.java:73)
at CheckIn.bottomLeftPanel(CheckIn.java:55)
at CheckIn.designPanel(CheckIn.java:45)
at CheckIn.<init>(CheckIn.java:30)
at HotelMainGUI.leftForms(HotelMainGUI.java:118)
at HotelMainGUI.leftPanel(HotelMainGUI.java:112)
at HotelMainGUI.subFrame(HotelMainGUI.java:32)
at HotelMainGUI.<init>(HotelMainGUI.java:21)
at HotelMainGUI.main(HotelMainGUI.java:189)
You NullPointerException is coming because of these sequence of code:
CheckIn.designPanel() -> bottomLeftPanel() -> bottomButtons()
Inside bottomButons(), you have have line as :
bottomRightPanel.add(submit);
At this point, you bottomRightPanel is not initialized.
Change the designPanel method as below:
public JPanel designPanel() {
//Sub container settings
designPanel = new JPanel( new GridLayout(12,2));
designPanel.setBounds(0,45,300,505);
designPanel.setBackground(new Color(80,80,80));
designPanel.add(bottomRightPanel());
designPanel.add(bottomLeftPanel());
return designPanel;
}
Moved designPanel.add(bottomRightPanel()); before designPanel.add(bottomLeftPanel());
Hope this resolves your issues.
Also there is lot of room for code restruring e.g. in your bottomRightPanel and bottomLeftPanel, below statements seems to be common or atleast similar. In that case, you can create one single methods as below:
public JPanel createPanel(){
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBorder(BorderFactory.createMatteBorder(1,0,0,0,Color.GRAY));
panel.setBackground(new Color(70,70,70));
return pannel;
}
And add the additional steps in your designPanel() method e.g.:
public JPanel designPanel() {
//Sub container settings
designPanel = new JPanel( new GridLayout(12,2));
designPanel.setBounds(0,45,300,505);
designPanel.setBackground(new Color(80,80,80));
JPanel leftPanel = createPanel();
JPanel rightPanel = createPanel();
createBottomButtons(leftPanel, rightPanel);
designPanel.add(leftPanel );
designPanel.add(rightPanel);
return designPanel;
}
If you notice I removed the bottomButtons(); from createPanel(), added that in designPanel(). Also passed leftPanel and rightPanel as argument to this method.
I hope you can perform remaining restructuring yourself. Good luck!!
Related
I have to make a scrollable list where I can add a panel with 3 labels many times.
I kind of made it work but the first panels are stretched and occupy all the area of the JScrollPane and I can't figure out how to fix this, I tried changing layouts many times but still didn't manage to fix it.
I want the added panel to occupy a fixed size but I can't figure this out. Example in this picture:
https://i.stack.imgur.com/LNznP.png
The one on the left is the one that I get and the one on the right (edited) is how I want it to work.
This is my first day of Swing so the code is very likely a mess, sorry in advance.
Here is the code:
public class MainWindow extends JFrame implements ActionListener{
private JPanel viewportPanel;
private JButton addButton,remButton;
private JScrollPane scrollPane;
private int counter = 0;
private JLabel dateLabel,dateLabel_1,dateLabel_2;
public MainWindow(boolean run) {
//BUTTONS
addButton = new JButton("Add");
addButton.setLocation(521, 11);
addButton.setSize(101, 100);
addButton.addActionListener(this);
remButton = new JButton("Remove");
remButton.setLocation(521, 122);
remButton.setSize(101, 100);
remButton.addActionListener(this);
//SCROLLPANE
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(10, 11, 501, 211);
add(scrollPane);
//PANELS
viewportPanel = new JPanel(new GridLayout(0,1));
scrollPane.setViewportView(viewportPanel);
//FRAME
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 273);
setResizable(false);
//setIconImage(new ImageIcon("epic.png").getImage());
setLayout(null);
if(run) setVisible(true);
add(addButton);
add(remButton);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addButton) {
//LABELS
dateLabel = new JLabel("DATE");
dateLabel.setFont(new Font("Tahoma", Font.BOLD, 28));
dateLabel.setSize(500,500);
dateLabel_1 = new JLabel("LABEL1");
dateLabel_1.setFont(new Font("Tahoma", Font.BOLD, 22));
dateLabel_1.setBounds(10, 45, 481, 30);
dateLabel_2 = new JLabel("LABEL2");
dateLabel_2.setFont(new Font("Tahoma", Font.ITALIC, 22));
dateLabel_2.setBounds(10, 45, 481, 30);
//PANEL WITH ALL THE STUFF
JPanel componentPanel = new JPanel();
componentPanel.setLayout(new GridLayout(3, 1));
componentPanel.setMaximumSize(new Dimension(50,50));
componentPanel.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK));
componentPanel.setBackground(Color.gray);
componentPanel.add(dateLabel);
componentPanel.add(dateLabel_1);
componentPanel.add(dateLabel_2);
viewportPanel.add(componentPanel); //add panel with labels to viewportpanel
counter++;
}
if(e.getSource() == remButton) {
Component[] componentList = viewportPanel.getComponents();
int lastElement = (componentList.length);
viewportPanel.remove(--lastElement);
--counter;
}
viewportPanel.revalidate();
viewportPanel.repaint();
}
}
Some help would be amazing!
First off, never do this:
setLayout(null);
Next, if you want things compressed at the top of a container, then use a layout that does this. such as a BorderLayout with the compressed items placed into a JPanel (perhaps one that uses a GridLayout) that is placed BorderLayout.PAGE_START
Actually, it looks as if your best solution is to us a JList, one that uses a custom renderer that places your time JLabel and two text JLabels into a JPanel and displays this in the list. So let's explore that.
First create a class to hold the data that is displayed by the JList, which looks to be a date and two lines of text:
public class ListItem {
private LocalDate date;
private String text1;
private String text2;
public ListItem(LocalDate date, String text1, String text2) {
super();
this.date = date;
this.text1 = text1;
this.text2 = text2;
}
public LocalDate getDate() {
return date;
}
public String getText1() {
return text1;
}
public String getText2() {
return text2;
}
}
Then let's create a renderer that a JList can use to display the above information in a JPanel. This is more complicated and requires that the class create a JPanel that places the labels where we want them, perhaps using a GridLayout with 1 column and 3 rows, plus some gaps between the rows: setLayout(new GridLayout(3, 1, 2 * gap, 2 * gap));. The class must implement the ListCellRenderer<T> interface which has one method: public Component getListCellRendererComponent(...). Java will pass in the paramters into this method, including a ListItem value, and we will use that value to fill in the JLabels that we add into this JPanel. Edited to highlight selected items.
import java.awt.*;
import java.time.format.DateTimeFormatter;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class ListItemRenderer extends JPanel implements ListCellRenderer<ListItem> {
private static final Color LIGHT_BLUE = new Color(204, 255, 255);
private static final Color REDDISH_GREY = new Color(205, 126, 121);
private DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
private static final int GAP = 2;
private Border emptyBorder = BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP);
private Border blackBorder = BorderFactory.createLineBorder(Color.BLACK);
private Border redBorder = BorderFactory.createLineBorder(REDDISH_GREY, 2);
private JLabel dateLabel = new JLabel();
private JLabel text1Label = new JLabel();
private JLabel text2Label = new JLabel();
public ListItemRenderer() {
dateLabel.setFont(dateLabel.getFont().deriveFont(Font.BOLD, 14f));
text1Label.setFont(text1Label.getFont().deriveFont(Font.BOLD));
text2Label.setFont(text1Label.getFont().deriveFont(Font.ITALIC));
int gap = 2;
setLayout(new GridLayout(0, 1, 2 * gap, 2 * gap));
setBorder(BorderFactory.createCompoundBorder(emptyBorder, blackBorder));
add(dateLabel);
add(text1Label);
add(text2Label);
}
#Override
public Component getListCellRendererComponent(JList<? extends ListItem> list, ListItem value, int index,
boolean isSelected, boolean cellHasFocus) {
if (value != null) {
String dateText = dateFormatter.format(value.getDate());
dateLabel.setText(dateText);
text1Label.setText(value.getText1());
text2Label.setText(value.getText2());
} else {
dateLabel.setText("");
text1Label.setText("");
text2Label.setText("");
}
if (isSelected ) {
setBackground(LIGHT_BLUE);
setBorder(BorderFactory.createCompoundBorder(emptyBorder, redBorder));
} else {
setBackground(null);
setBorder(BorderFactory.createCompoundBorder(emptyBorder, blackBorder));
}
return this;
}
}
And now the main program that puts this all together, edited to show removing items:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class MainPanel extends JPanel {
DefaultListModel<ListItem> listModel = new DefaultListModel<>();
private JList<ListItem> jList = new JList<>(listModel);
private JScrollPane scrollPane = new JScrollPane(jList);
private JButton addButton = new JButton("Add");
private JButton removeButton = new JButton("Remove");
public MainPanel() {
jList.setPrototypeCellValue(new ListItem(LocalDate.now(),
"This is text 1 for testing. This is text 1 for testing. This is text 1 for testing",
"This is text 2 for testing. This is text 2 for testing. This is text 2 for testing"));
jList.setVisibleRowCount(4);
jList.setCellRenderer(new ListItemRenderer());
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel buttonPanel = new JPanel(new GridLayout(0, 1, 3, 3));
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
addButton.setMnemonic(KeyEvent.VK_A);
removeButton.setMnemonic(KeyEvent.VK_R);
addButton.addActionListener(e -> addEvent());
removeButton.addActionListener(e -> removeEvent());
JPanel rightPanel = new JPanel();
rightPanel.add(buttonPanel);
int gap = 5;
setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
setLayout(new BorderLayout());
add(scrollPane);
add(rightPanel, BorderLayout.LINE_END);
}
private void removeEvent() {
int[] selectedIndices = jList.getSelectedIndices();
for (int i = selectedIndices.length - 1; i >= 0; i--) {
listModel.remove(selectedIndices[i]);
}
}
private void addEvent() {
// this adds random stuff to the JList
String text1 = "Some random text: " + randomText();
String text2 = "Some random text: " + randomText();
listModel.addElement(new ListItem(LocalDate.now(), text1, text2));
// TODO: change this so that it adds *real* data to the JList
}
private String randomText() {
Random random = new Random();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 2 + random.nextInt(3); i++) {
for (int j = 0; j < 3 + random.nextInt(5); j++) {
char c = (char) ('a' + random.nextInt('z' - 'a'));
builder.append(c);
}
builder.append(" ");
}
return builder.toString();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Output would look like:
I am using JCombobox and just below that there is a panel which contains JTextFields. Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself. I don't know what to do. I am unable to post a pic of the problem here because i am a new user and my reputation is below 10.
public class MainClass {
public static void main(String args[]){
Form form = new Form();
int width = 400;
int height = 400;
form.setSize(width, height);
form.setVisible(true);
form.setTitle("Create Network");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
form.setLocation((screenSize.width-width)/2, (screenSize.height-height)/2);
}
}
This is the form class
public class Form extends JFrame {
private JLabel ipAddress, networkTopo, numNodes;
private JTextField nodes;
private JButton addIp;
private JButton removeIp;
private JButton next, back;
private JPanel jPanel, jPanel1, jPanel2, commonPanel;
private JComboBox<String> dropDown;
private String[] topologies = { "Grid", "Diagnol Grid", "Bus", "Ring",
"Star" };
public Form() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
setResizable(false);
this.getContentPane().setBackground(Color.WHITE);
// add(Box.createRigidArea(new Dimension(0,10)));
GridLayout commonPanelLayout = new GridLayout(0, 2);
commonPanelLayout.setVgap(10);
commonPanel = new JPanel(commonPanelLayout);
commonPanel.setVisible(true);
commonPanel.setAlignmentX(commonPanel.LEFT_ALIGNMENT);
commonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
commonPanel.setBackground(Color.white);
numNodes = new JLabel("Number of Nodes");
commonPanel.add(numNodes);
nodes = new JTextField(20);
commonPanel.add(nodes);
networkTopo = new JLabel("Network Topology");
commonPanel.add(networkTopo);
dropDown = new JComboBox<String>(topologies);
dropDown.setBackground(Color.WHITE);
commonPanel.add(dropDown);
add(commonPanel);
add(Box.createRigidArea(new Dimension(0, 10)));
ipAddress = new JLabel("IP Addresses");
ipAddress.setAlignmentX(ipAddress.LEFT_ALIGNMENT);
ipAddress.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
add(ipAddress);
add(Box.createRigidArea(new Dimension(0, 10)));
jPanel = new JPanel(new FlowLayout());
jPanel.setVisible(true);
jPanel.setAlignmentX(jPanel.LEFT_ALIGNMENT);
jPanel.setBackground(Color.WHITE);
// jPanel1.setAutoscrolls(true);
add(jPanel);
GridLayout layout = new GridLayout(0, 1);
jPanel1 = new JPanel();
layout.setVgap(10);
// jPanel1.setBackground(Color.WHITE);
jPanel1.setVisible(true);
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(jPanel1);
scroll.setAutoscrolls(true);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setPreferredSize(new Dimension(300, 150));
jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width,
Integer.MAX_VALUE));
jPanel.add(scroll);
jPanel2 = new JPanel(new GridLayout(0, 1, 10, 10));
jPanel2.setBackground(Color.WHITE);
jPanel2.setVisible(true);
jPanel.add(jPanel2);
addIp = new JButton("Add");
jPanel2.add(addIp);
removeIp = new JButton("Remove");
jPanel2.add(removeIp);
JPanel savePanel = new JPanel(new FlowLayout());
savePanel.setVisible(true);
savePanel.setAlignmentX(savePanel.LEFT_ALIGNMENT);
savePanel.setBackground(Color.white);
back = new JButton("Back");
back.setAlignmentX(next.LEFT_ALIGNMENT);
back.setEnabled(false);
savePanel.add(back);
next = new JButton("Next");
next.setAlignmentX(next.LEFT_ALIGNMENT);
savePanel.add(next);
add(savePanel);
AddIPEvent addIPEvent = new AddIPEvent();
addIp.addActionListener(addIPEvent);
RemoveIPEvent removeIPEvent = new RemoveIPEvent();
removeIp.addActionListener(removeIPEvent);
}
public class AddIPEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel subPanel = new JPanel(new FlowLayout());
// subPanel.setBackground(Color.WHITE);
subPanel.setVisible(true);
JCheckBox jCheckBox = new JCheckBox();
// jCheckBox.setBackground(Color.WHITE);
subPanel.add(jCheckBox);
JTextField ip = new JTextField(12);
subPanel.add(ip);
JTextField nodesInIp = new JTextField(6);
nodesInIp.setVisible(false);
subPanel.add(nodesInIp);
jPanel1.add(subPanel);
jPanel1.repaint();
jPanel1.revalidate();
}
}
public class RemoveIPEvent implements ActionListener {
public void removeIP(Container container) {
for (Component c : container.getComponents()) {
if (c instanceof JCheckBox) {
if (((JCheckBox) c).isSelected()) {
jPanel1.remove(container);
jPanel.revalidate();
jPanel1.repaint();
}
} else if (c instanceof Container) {
removeIP((Container) c);
}
}
}
public void actionPerformed(ActionEvent e) {
removeIP(jPanel1);
}
}
}
After Clicking on the Add button and then clicking on the JComboBox will make portion of JTextField dissapear. Could someone pls point out the mistake?
Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself.
//jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width, Integer.MAX_VALUE));
Don't set the preferred size of components. The layout manager will determine the preferred size as components are added/removed. Then scrollbars will appear as required.
jPanel1.repaint();
jPanel1.revalidate();
The order should be:
jPanel1.revalidate();
jPanel1.repaint();
The revalidate() first invokes the layout manager before it is repainted.
//form.setSize(width, height);
form.pack();
Again, don't try to set the size. Let the layout managers do their jobs. The pack() will size the frame based on the sizes of the components added to the frame.
I'm stuck using Button and JButton
expected result.. ( all information working )
http://i.stack.imgur.com/3qX7v.png
and what I have
http://i.stack.imgur.com/a4gao.png
I want to replace this:
Button butRock = new Button("Rock");
butRock.addActionListener(this);
ButtPan.add(butRock);
To This:
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
I'm stuck because when I replace Button to JButton the program doesn't work properly...when I use this JButton
Question: How to replace the button with picture and that program still work properly...
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class gui extends JFrame implements ActionListener
{
public JLabel JWoL,JWoLPlayer,JWoLPC,JNumWin,JNumLose,JNumTie, logo;
public JLabel JWinT,JLoseT,JTieT, rpsP, rpsC, result;
JPanel LabelsPan;
static final int WINS = 0, LOSSES = 1, DRAWS = 2;
int[] counts = new int[3];
String[] strings = {"| You Win", "| You Lose", "| Draw"};
JLabel[] labels = {JNumWin, JNumLose, JNumTie};
#SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
gui theWindow = new gui();
theWindow.show();
}
private void record(int type)
{
JWoL.setText(strings[type]);
counts[type]++;
labels[type].setText(""+counts[type]);
}
public gui() throws IOException
{
JPanel logo = new JPanel();
logo.setLayout(new GridLayout(1,1));
BufferedImage myPicture = ImageIO.read(new File("logo.jpg"));
JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
add(picLabel);
JPanel ButtPan=new JPanel();
ButtPan.setLayout(new GridLayout(1,3));
BufferedImage buttonIcon = ImageIO.read(new File("rock.jpg"));
JButton butRock = new JButton(new ImageIcon(buttonIcon));
butRock.addActionListener(this);
ButtPan.add(butRock);
Button butPaper = new Button("Paper");
butPaper.addActionListener(this);
ButtPan.add(butPaper);
Button butScissors = new Button("Scissors");
butScissors.addActionListener(this);
ButtPan.add(butScissors);
JWoLPlayer = new JLabel();
JWoLPC = new JLabel();
JWoL= new JLabel();
JLabel rpsPlayer= new JLabel("| Your Choice: ");
JLabel rpsComputer= new JLabel("| Computers Choice: ");
setTitle("| RoPaS GAME |");
LabelsPan=new JPanel();
LabelsPan.setLayout(new GridLayout(3,2));
rpsP = new JLabel();
LabelsPan.add(rpsPlayer);
LabelsPan.add(JWoLPlayer);
rpsC = new JLabel();
LabelsPan.add(rpsComputer);
LabelsPan.add(JWoLPC);
result =new JLabel();
LabelsPan.add(JWoL,"Center");
JPanel WLPan = new JPanel();
WLPan.setLayout(new GridLayout(3, 2));
JWinT = new JLabel("Wins: ");
JLoseT = new JLabel("Losses: ");
JTieT = new JLabel("Ties: ");
WLPan.add(JWinT);
JNumWin = new JLabel();
WLPan.add(JNumWin);
WLPan.add(JLoseT);
JNumLose = new JLabel();
WLPan.add(JNumLose);
WLPan.add(JTieT);
JNumTie = new JLabel();
WLPan.add(JNumTie);
JLabel[] labels1 = {JNumWin, JNumLose, JNumTie};
labels = labels1;
JPanel TwoPanesN1=new JPanel();
TwoPanesN1.setLayout(new BorderLayout());
TwoPanesN1.add(logo,"North");
TwoPanesN1.add(LabelsPan,"West");
TwoPanesN1.add(WLPan,"East");
getContentPane().setLayout(new GridLayout(3,2));
getContentPane().add(ButtPan);
getContentPane().add(TwoPanesN1);
Font fontDisplay = new Font("Arial", Font.BOLD, 16);
JWoL.setFont(fontDisplay);
LabelsPan.setFont(fontDisplay);
setSize(400,250);
setVisible(true);
setResizable(false);
addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent ev){System.exit(0);}});
}
public void Play(String PlayerChoice)
{
String PCchoice=PCansw();
JWoLPC.setText(PCchoice);
if(PlayerChoice.equals(PCchoice))
record(DRAWS);
else if(PlayerChoice.equals("Rock"))
if(PCchoice.equals("Paper"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Paper"))
if(PCchoice.equals("Scissors"))
record(LOSSES);
else
record(WINS);
else if(PlayerChoice.equals("Scissors"))
if(PCchoice.equals("Rock"))
record(LOSSES);
else
record(WINS);
}
public String PCansw()
{
String rpsPC2="";
int rpsPC=(int)(Math.random( )*3)+1;
if(rpsPC==1)
rpsPC2= "Rock";
else if(rpsPC==2)
rpsPC2= "Paper";
else if(rpsPC==3)
rpsPC2= "Scissors";
return rpsPC2;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Exit"))
System.exit(0);
else
{
JWoLPlayer.setText(e.getActionCommand());
Play(e.getActionCommand());
}
}
}
The problem is that you are using getActionCommand to determine which JButton was clicked but this property is not set by default in Swing. You would have to call
butRock.setActionCommand("Rock");
java.awt.Button automatically uses the label property as the ActionCommand if it not explicitly set. From the docs
If the command name is null (default) then this method returns the label of the button.
Some asides:
Better to avoid mixing heavy & lightweight components and use lightweight components throughout the application.
As your Rock, Paper, Scissors buttons have identical functionality, consider using an Action.
A direct instance JFrame is typically used rather than extending the class
Use Initial Threads
Window#show is deprecated. Use Window#setVisible.
Don't use System.exit - See more here
I tried using:
frame1.getContentPane().setBackground(Color.yellow);
But it is not working. Can anyone help me?
import java.awt.*;
import java.awt.Color;
public class PlayGame {
public static void main(String[] args) {
GameFrame frame1 = new GameFrame();
frame1.getContentPane().setBackground(Color.yellow);
// Set Icon
Image icon = Toolkit.getDefaultToolkit().getImage("image/poker_icon.gif");
frame1.setIconImage(icon);
frame1.setVisible(true);
frame1.setSize(600, 700);
frame1.setTitle("Card Game");
// Set to exit on close
frame1.setDefaultCloseOperation(GameFrame.EXIT_ON_CLOSE);
}
}
GameFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GameFrame extends JFrame implements ActionListener {
private JPanel topPnl, btmPnl, pcPnl, mainPnl;
private JPanel titlePnl, playerPnl, computerPnl;
private JLabel titleLbl, playerLbl, computerLbl;
private JLabel testTextBox1, testTextBox2;
private ImageIcon playerIcon, computerIcon;
//
private JPanel pickCardPnl, pickCardTitlePnl, cardPnl, resultPnl, optionPnl;
private JLabel pickCardTitleLbl;
private JLabel card1Lbl, card2Lbl, card3Lbl, card4Lbl, card5Lbl;
private JLabel resultLbl;
private JButton restartBtn, showCardBtn, exitBtn;
private JButton card1Btn, card2Btn, card3Btn, card4Btn, card5Btn;
private ImageIcon card1Pic, card2Pic, card3Pic, card4Pic, card5Pic;
private JButton playerBtn, computerBtn;
private ImageIcon playerPic;
private String[] card = new String[53];
private String name;
// ArrayInt al;
public GameFrame() {
// a1 = new Array();
//a1.generateRandom();
setCard();
setName();
// Top Panel /////////////////////////////////////
mainPnl = new JPanel(new BorderLayout());
topPnl = new JPanel(new BorderLayout(50, 0));
titlePnl = new JPanel();
pcPnl = new JPanel(new GridLayout(1, 2, 10, 10));
playerPnl = new JPanel(new BorderLayout(10, 10));
computerPnl = new JPanel(new BorderLayout(10, 10));
// Title Panel
titleLbl = new JLabel("Card Game");
titlePnl.add(titleLbl);
// Player Panel
playerIcon = new ImageIcon("image/player.png");
playerLbl = new JLabel(name, playerIcon, JLabel.CENTER);
playerPnl.add(playerLbl, BorderLayout.NORTH);
playerPic = new ImageIcon("image/unknwon.png");
playerBtn = new JButton(playerPic);
playerPnl.add(playerBtn, BorderLayout.CENTER);
playerBtn.setContentAreaFilled(false);
playerBtn.setBorder(BorderFactory.createEmptyBorder());
// Computer Panel
computerIcon = new ImageIcon("image/computer.png");
computerLbl = new JLabel("Computer:", computerIcon, JLabel.CENTER);
computerPnl.add(computerLbl, BorderLayout.NORTH);
playerPic = new ImageIcon("image/back.png");
computerBtn = new JButton(playerPic);
computerPnl.add(computerBtn, BorderLayout.CENTER);
computerBtn.setContentAreaFilled(false);
computerBtn.setBorder(BorderFactory.createEmptyBorder());
pcPnl.add(playerPnl);
pcPnl.add(computerPnl);
// Add panel into Top Panel
topPnl.add(titlePnl, BorderLayout.NORTH);
topPnl.add(pcPnl, BorderLayout.CENTER);
// Bottom Panel /////////////////////////////////////
btmPnl = new JPanel(new BorderLayout());
pickCardPnl = new JPanel(new BorderLayout());
pickCardTitlePnl = new JPanel();
cardPnl = new JPanel(new GridLayout(1, 5, 5, 5));
resultPnl = new JPanel();
optionPnl = new JPanel(new GridLayout(1, 3, 5, 5));
// Pick Card Panel
pickCardTitleLbl = new JLabel("Pick Your Card:");
pickCardPnl.add(pickCardTitleLbl, BorderLayout.NORTH);
card1Pic = new ImageIcon(card[1]);
card1Btn = new JButton(card1Pic);
cardPnl.add(card1Btn);
card1Btn.addActionListener(this);
card2Pic = new ImageIcon(card[2]);
card2Btn = new JButton(card2Pic);
cardPnl.add(card2Btn);
card2Btn.addActionListener(this);
card3Pic = new ImageIcon(card[3]);
card3Btn = new JButton(card3Pic);
cardPnl.add(card3Btn);
card3Btn.addActionListener(this);
card4Pic = new ImageIcon(card[4]);
card4Btn = new JButton(card4Pic);
cardPnl.add(card4Btn);
card4Btn.addActionListener(this);
card5Pic = new ImageIcon(card[5]);
card5Btn = new JButton(card5Pic);
cardPnl.add(card5Btn);
card5Btn.addActionListener(this);
// new ImageIcon(a1.getRandomNumber);
pickCardPnl.add(cardPnl, BorderLayout.CENTER);
card1Btn.setContentAreaFilled(false);
card1Btn.setBorder(BorderFactory.createEmptyBorder());
card2Btn.setContentAreaFilled(false);
card2Btn.setBorder(BorderFactory.createEmptyBorder());
card3Btn.setContentAreaFilled(false);
card3Btn.setBorder(BorderFactory.createEmptyBorder());
card4Btn.setContentAreaFilled(false);
card4Btn.setBorder(BorderFactory.createEmptyBorder());
card5Btn.setContentAreaFilled(false);
card5Btn.setBorder(BorderFactory.createEmptyBorder());
// Result Panel
setCard();
resultLbl = new JLabel("adasdadadasdasdasdasd");
resultPnl.add(resultLbl);
// Option Panel
restartBtn = new JButton("Restart");
optionPnl.add(restartBtn);
restartBtn.addActionListener(this);
showCardBtn = new JButton("Show Cards");
optionPnl.add(showCardBtn);
showCardBtn.addActionListener(this);
exitBtn = new JButton("Exit");
optionPnl.add(exitBtn);
exitBtn.addActionListener(this);
// Add panel into Bottom Panel
btmPnl.add(pickCardPnl, BorderLayout.NORTH);
btmPnl.add(resultPnl, BorderLayout.CENTER);
btmPnl.add(optionPnl, BorderLayout.SOUTH);
//
mainPnl.add(topPnl, BorderLayout.NORTH);
// add(midPNL, BorderLayout.CENTER);
mainPnl.add(btmPnl, BorderLayout.CENTER);
add(mainPnl);
// Menu bar
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Game");
menuBar.add(menu);
JMenuItem item3 = new JMenuItem("Change Name");
item3.addActionListener(this);
menu.add(item3);
JMenuItem item = new JMenuItem("Change Card Deck");
item.addActionListener(this);
menu.add(item);
JMenu subMenu = new JMenu("Change BackGround");
subMenu.addActionListener(this);
menu.add(subMenu);
JMenuItem subItem = new JMenuItem("Blue");
subItem.addActionListener(this);
subMenu.add(subItem);
JMenuItem subItem2 = new JMenuItem("Green");
subItem2.addActionListener(this);
subMenu.add(subItem2);
//
menu.addSeparator();
//
JMenuItem item4 = new JMenuItem("Quit");
item4.addActionListener(this);
menu.add(item4);
setJMenuBar(menuBar);
} //End of GameFrame
public void setCard() {
GenRandom g1 = new GenRandom();
g1.GenRandomCard();
int[] allCard = new int[11];
allCard = g1.getAllCard();
for (int i = 1; i <= 10; i++) {
card[i] = "image/card/" + allCard[i] + ".png";
}
}
public void setName() {
// name = JOptionPane.showInputDialog(null, "Please Enter Your Name", "Welcome", JOptionPane.QUESTION_MESSAGE) + ":";
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == card1Btn) {
playerBtn.setIcon(card1Pic);
card1Btn.setEnabled(false);
}
if (e.getSource() == card2Btn) {
playerBtn.setIcon(card2Pic);
card2Btn.setEnabled(false);
}
if (e.getSource() == card3Btn) {
playerBtn.setIcon(card3Pic);
card3Btn.setEnabled(false);
}
if (e.getSource() == card4Btn) {
playerBtn.setIcon(card4Pic);
card4Btn.setEnabled(false);
}
if (e.getSource() == card5Btn) {
playerBtn.setIcon(card5Pic);
card5Btn.setEnabled(false);
}
if (e.getSource() == restartBtn) {
new AePlayWave("sound/jet.wav").start();
JOptionPane.showMessageDialog(null, "Restart Button ");
}
if (e.getSource() == exitBtn) {
/* long start = System.currentTimeMillis();
long end = start + 4 * 1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end) {
// run
new AePlayWave("sound/jet.wav").start();
}*/
System.exit(0);
}
}
}
Since you did not post an SSCCE, I will do it for you. This shows how to change the background color of a JFrame. Starting from this, you can start adding components to the JFrame and see where you go wrong, instead of letting us look at a few hundred lines of code.
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.EventQueue;
public class ColoredFrame {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame( "TestFrame" );
frame.getContentPane().setBackground( Color.PINK );
//frame contains nothing, so set size
frame.setSize( 200, 200 );
frame.setVisible( true );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} );
}
}
Just put your setVisible(true); at the end of your constructor.
Moreover you had added mainPnl on your JFrame, so changing colour of the JFrame will be useless,
so instead of writing
add(mainPnl);
in your GameFrame class, you better be using
setContentPane(mainPnl);
for frame1.getContentPane().setBackground(Color.YELLOW); to work.
Hope this might help
Regards
You should give background color to JPanel and then use this JPanel in your JFrame rather than giving direct background to your JFrame.
I know this is a very old question, but for others that are looking for the right answer this could also be written as following:
frame1.getContentPane().setBackground(new Color (255,255,102)); //or whatever color you want in the RGB range
This is driving me insane. I'm trying to change the panels when you click on 3 different buttons and it works, but for one panel - only once.
If you click addPerson - the Person panel shows,
If you then click addCD - the CD panel shows; (same for view store)
If you then click on addPerson - it doesn't work. It throws a nullpointer exception.
Even if you click on addCD/viewstore and THEN add Person it shows but it just won't show a second time.
In a test file, I created a GUI with an add and remove: if I clicked add it threw the null pointer exception but if I just added it already and compiled, it was fine...
/* PERSON PANEL */
public JPanel create_PersonPnl()
{
personPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
personPnl.setBackground(Color.WHITE);
personPnl.setPreferredSize(minPnl);
/* VERTICAL BOX for Person boxes */
Box personBox = Box.createVerticalBox();
personBox.setBorder(new TitledBorder(new LineBorder(Color.DARK_GRAY), "Person"));
/* Horizontal Box for Name Lbl & TF */
Box nameBox = Box.createHorizontalBox();
nameBox.add(Box.createHorizontalStrut(10));
nameLbl = new JLabel("Name: ");
nameBox.add(nameLbl);
nameBox.add(Box.createHorizontalStrut(5));
nameTF = new JTextField();
nameBox.add(nameTF);
nameBox.add(Box.createHorizontalStrut(10));
personBox.add(nameBox);
personBox.add(Box.createVerticalStrut(10));
Box limitBox = Box.createHorizontalBox();
limitBox.add(Box.createHorizontalStrut(10));
limitLbl = new JLabel("CD Limit: ");
limitBox.add(limitLbl);
limitTF = new JFormattedTextField();
limitBox.add(limitTF);
limitBox.add(Box.createHorizontalStrut(10));
personBox.add(limitBox);
personBox.add(Box.createVerticalStrut(10));
personBox.add(addPersonBtn = new JButton("Add Person"));
personBox.add(Box.createVerticalStrut(10));
personList = new JList(temp);
personList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollp = new JScrollPane(personList);
scrollp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollp.setSize(100, 45);
personBox.add(scrollp);
personBox.add(Box.createVerticalStrut(10));
Box optionsBox = Box.createHorizontalBox();
editPrsnBtn = new JButton("Edit");
editPrsnBtn.addActionListener(this);
optionsBox.add(editPrsnBtn);
removePrsnBtn = new JButton("Remove");
removePrsnBtn.addActionListener(this);
optionsBox.add(removePrsnBtn);
personBox.add(optionsBox);
personPnl.add(personBox);
return personPnl;
}
This is what is in my ActionPerformed method.
if(e.getSource() == addPersonBtn)
{
changePnl.removeAll();
changePnl.add(create_PersonPnl());
changePnl.revalidate();
System.out.println("PersonPnl added");
}
if(e.getSource() == addCDBtn)
{
changePnl.removeAll();
changePnl.add(create_CDPnl());
changePnl.revalidate();
}
if(e.getSource() == viewStoreBtn)
{
changePnl.removeAll();
changePnl.add(create_StorePnl());
changePnl.revalidate();
}
Only code for ChangePnl.
changePnl = new JPanel();
changePnl.setBackground(Color.WHITE);
defaultPnl = new JPanel();
defaultPnl.setBackground(Color.WHITE);
defaultPnl.add(new JLabel("Welcome to the CD Store"));
defaultPnl.add(new JLabel("Click an option from the left"));
changePnl.add(defaultPnl);
The S.O.P was to debug to see what was being run.. and that only prints once and that's it unless I take out .add(create_PersonPnl()); so I've narrowed it but I don't have a clue since it works the first time.
Thank in advance!
Separate test file to prove it's create_PersonPnl()
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class Test implements ActionListener
{
JButton add, remove;
JButton addPersonBtn, editPrsnBtn, removePrsnBtn;
JFrame frame;
JFormattedTextField limitTF;
JLabel nameLbl, limitLbl;
JList personList;
JPanel TotalGUI, welcomePnl, mainPnl, imagePnl, changePnl, defaultPnl, cdPnl, storePnl;
JPanel personPnl;
JScrollPane scrollp;
JTextField nameTF;
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
Dimension minPnl = new Dimension(300, 400);
/* Test for JList */
String[] temp = {"1", "2", "3", "4", "1", "2", "3", "4","1", "2", "3", "4","1", "2", "3", "4" };
public Test()
{
frame = new JFrame("CD Store");
frame.setExtendedState(JFrame.NORMAL);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack(); //sets size based on components size in TotalGUI
//frame.setJMenuBar(create_MenuBar());
//frame.setMinimumSize(minDim);
frame.setSize(725, 550);
//set frame location (central to screen)
int fw = frame.getSize().width;
int fh = frame.getSize().height;
int fx = (dim.width-fw)/2;
int fy = (dim.height-fh)/2;
frame.getContentPane().add(create_Content_Pane());
frame.setVisible(true);
//moves the frame to the centre
frame.setLocation(fx, fy);
}
public JPanel create_Content_Pane()
{
JPanel TotalGUI = new JPanel();
TotalGUI.add(remove = new JButton("Remove"));
remove.addActionListener(this);
TotalGUI.add(add = new JButton("Add")); <- this crashes when selected
add.addActionListener(this);
//TotalGUI.add(create_PersonPnl()); <- works just fine
return TotalGUI;
}
public JPanel create_PersonPnl()
{
personPnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
personPnl.setBackground(Color.WHITE);
personPnl.setPreferredSize(minPnl);
/* VERTICAL BOX for Person boxes */
Box personBox = Box.createVerticalBox();
personBox.setBorder(new TitledBorder(new LineBorder(Color.DARK_GRAY), "Person"));
/* Horizontal Box for Name Lbl & TF */
Box nameBox = Box.createHorizontalBox();
nameBox.add(Box.createHorizontalStrut(10));
nameLbl = new JLabel("Name: ");
nameBox.add(nameLbl);
nameBox.add(Box.createHorizontalStrut(5));
nameTF = new JTextField();
nameBox.add(nameTF);
nameBox.add(Box.createHorizontalStrut(10));
personBox.add(nameBox);
personBox.add(Box.createVerticalStrut(10));
Box limitBox = Box.createHorizontalBox();
limitBox.add(Box.createHorizontalStrut(10));
limitLbl = new JLabel("CD Limit: ");
limitBox.add(limitLbl);
limitTF = new JFormattedTextField();
limitBox.add(limitTF);
limitBox.add(Box.createHorizontalStrut(10));
personBox.add(limitBox);
personBox.add(Box.createVerticalStrut(10));
personBox.add(addPersonBtn = new JButton("Add Person"));
personBox.add(Box.createVerticalStrut(10));
personList = new JList(temp);
personList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollp = new JScrollPane(personList);
scrollp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollp.setSize(100, 45);
personBox.add(scrollp);
personBox.add(Box.createVerticalStrut(10));
Box optionsBox = Box.createHorizontalBox();
editPrsnBtn = new JButton("Edit");
editPrsnBtn.addActionListener(this);
optionsBox.add(editPrsnBtn);
removePrsnBtn = new JButton("Remove");
removePrsnBtn.addActionListener(this);
optionsBox.add(removePrsnBtn);
personBox.add(optionsBox);
personPnl.add(personBox);
return personPnl;
}
public static void main(String[] args)
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == remove)
{
TotalGUI.removeAll();
TotalGUI.revalidate();
}
if(e.getSource() == add)
{
TotalGUI.add(create_PersonPnl());
TotalGUI.revalidate();
}
}
}
In your method
public JPanel create_Content_Pane()
{
JPanel TotalGUI = new JPanel();
TotalGUI.add(remove = new JButton("Remove"));
remove.addActionListener(this);
TotalGUI.add(add = new JButton("Add")); <- this crashes when selected
add.addActionListener(this);
//TotalGUI.add(create_PersonPnl()); <- works just fine
return TotalGUI;
}
The NullPointerException occurs because your private field TotalGUI is null... Remove the JPanel declaration in front of TotalGUI = new JPanel(); That will solve the null pointer problem. This probably solves only your problem in the test scenario... To solve the problem in your original scenario it would be nice to have the complete source code of the class..