Reputation: 63
I'm trying to test out the Set and Get method, but it didn't seem to work.
I added ActionListener
to a button, then perform it when it is clicked. But it didn't work though. In a bigger project, I used this method as well but since it didn't work, I had to simplify it to a smaller program to make it easier to understand. However, I still couldn't understand it. Can you guys help me to point out the problem?
Here is the code:
public class SetAndGet extends JPanel {
private int index = 3500;
private JButton btPrev;
private JLabel lbIndex;
public SetAndGet() {
init();
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
private void init() {
setLayout(null);
setBackground(Color.WHITE);
lbIndex = new JLabel(index + "");
lbIndex.setBounds(10, 10, 50, 30);
add(lbIndex);
btPrev = new JButton("Previous");
btPrev.setBounds(100, 10, 80, 30);
btPrev.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// index--; THIS ONE WORKED, OF COURSE
// lbIndex.setText(index + "");
// BUT THIS ONE DIDNT, PLEASE EXPLAIN FOR ME
int i = getIndex();
setIndex(i--);
lbIndex.setText(index + "");
}
});
add(btPrev);
}
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.setSize(200, 200);
f.setLocationRelativeTo(null);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.add(new SetAndGet());
f.setVisible(true);
}
}
Upvotes: 0
Views: 57
Reputation:
Your getter and setter are working, you are just not changing the value.
i--
will subtract one from i
after it has been assigned to the setter.
If you want to subtract one before setting the value, use --i
:
public void actionPerformed(ActionEvent e) {
// index--; THIS ONE WORKED, OF COURSE
// lbIndex.setText(index + "");
// BUT THIS ONE DIDNT, PLEASE EXPLAIN FOR ME
int i = getIndex();
setIndex(--i);
lbIndex.setText(index + "");
}
Upvotes: 2