From my textbook: "Write an application that extends JFrame and that displays a phrase upside down when the user click a button. The phrase is displayed normally when the user clicks the button again."
Currently I have a String that is drawn using the paint() method and a Graphic object. The String is visible in the JUpsideDown frame and it's upside down and positioned in about the middle of the panel. I've added my button and a actionListener but I think the code in my actionPerformed method is wrong because I'm trying to make the negative font size a positive by multiplying by -1 but it doesn't seem to take effect when I repaint. The String positioned is moved to x = 100 ad y = 100 but the String is still upside down.
Any kind of guidance is appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class JUpsideDown extends JFrame implements ActionListener
{
int x = 350;
int y = 100;
int fontSize = -26;
Font font = new Font("Serif", Font.PLAIN, fontSize);
JButton press = new JButton("Flip Text");
String label = "Look at this text, it will flip!";
public JUpsideDown()
{
setTitle("JUpsideDown");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(press);
press.addActionListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
g.setFont(font);
g.drawString(label, x, y);
}
public void actionPerformed(ActionEvent e)
{
fontSize = fontSize * -1;
x = 100;
y = 100;
repaint();
}
public static void main(String[] args)
{
JUpsideDown frame = new JUpsideDown();
frame.setSize(450, 200);
frame.setVisible(true);
}
}
Your logic is right, although you need to instantiate again a new Font
object which will encapsulate the new fontsize
. This should be performed after the button is clicked inside actionPerformed()
method. In this way the behavior of the application will be the expected.
Below you may find a possible solution:
public void actionPerformed(ActionEvent e)
{
fontSize = fontSize * -1;
x = 100;
y = 100;
font = new Font("Serif", Font.PLAIN, fontSize); //added line
repaint();
}