Sorry in advance for a not very specific title - the problem was hard to describe. I essentialy have a very simple program, a window with an X, a number that tells what size is the font in said X, and two buttons - increase and decrease which clicked should change the font size and number by one. They're in a class which implement ActionListener
Not this is the actionPerformed. The if else is Ctrl+C, Ctrl+V, the only thing changed is ++ and --. The problem is that program once running has a correctly working decrease button (decreases by 1) but increase causes value and font to increase by two.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == increase) {
size.setText(++value+"");
setFont(value);
}
else if (e.getSource() == decrease) {
size.setText(--value+"");
setFont(value);
}
}
After staring at my code and trying diffrent ways of writing it - changing value in separate lines and so on, I still can't understand why this happens. Below is the whole program (quite short, as I said it's supposed to be a simple exercise on JFrame and its components):
class FontDisplay extends JFrame implements ActionListener{
JLabel size, letter;
JButton increase, decrease;
int value; //to get rid of converting from strings to ints when changing size
public FontDisplay() {
value = 18;
setLayout(new GridLayout(2,2));
size = new JLabel("18");
letter = new JLabel("X", JLabel.RIGHT);
setFont(18);
increase = new JButton("Increase");
increase.addActionListener(this);
decrease = new JButton("Decrease");
decrease.addActionListener(this);
add(letter);
add(size);
add(increase);
add(decrease);
increase.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == increase) {
size.setText(++value+"");
setFont(value);
}
else if (e.getSource() == decrease) {
value--;
size.setText(value+"");
setFont(value);
}
}
private void setFont(int i) {
Font font = new Font(letter.getFont().getFontName(), Font.PLAIN,i);
letter.setFont(font);
}
public static void main(String[] args){
FontDisplay t = new FontDisplay();
t.setSize(200, 200);
t.setTitle("Check Font Size");
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}