尝试使用 actionListener 将字符串颠倒过来

Trying to use actionListener to turn a String upside down

来自我的教科书: "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."

目前我有一个使用 paint() 方法绘制的字符串和一个图形对象。字符串在 JUpsideDown 框架中可见,它倒置并位于面板的大约中间。我已经添加了我的按钮和一个 actionListener,但我认为我的 actionPerformed 方法中的代码是错误的,因为我试图通过乘以 -1 使负字体大小变为正字体,但它在我重绘时似乎没有生效.定位的字符串移动到 x = 100 ad y = 100 但字符串仍然颠倒。

欢迎任何形式的指导。

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);

    }

}

你的逻辑是正确的,虽然你需要再次实例化一个新的Font对象来封装新的fontsize。这应该在 actionPerformed() 方法中单击按钮后执行。这样,应用程序的行为将符合预期。

您可能会在下面找到可能的解决方案:

public void actionPerformed(ActionEvent e)
    {
        fontSize = fontSize * -1;
        x = 100;
        y = 100;
        font = new Font("Serif", Font.PLAIN, fontSize); //added line
        repaint();
    }