我试图让“enlargeListener 实现 ActionListener”类从 shapeName JTextField 获取输入并将其应用到 for 循环中。规范是,如果从 shapeName JTextfield 获取的 shapeName.getText() 返回的内容与循环中指定的内容匹配(又名 == "rectangle" 或 == "circle"),它将实现放大或缩小方法。
问题是我知道它返回 JTextField 中的内容......但即使它符合循环的条件......循环仍然失败,我不知道为什么。
例如..如果我在第一个文本框中键入“矩形”...它将作为字符串“矩形”返回到“放大侦听器实现”类下的 for 循环。然而,当它针对 == "rectangle" 进行测试时,它仍然失败。我已经梳理了很多很多文件以试图弄清楚......但我仍然无法。任何帮助,将不胜感激 :)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestShape extends JFrame
{
Circle c;
Rectangle r;
JTextField shapeName;
JTextField areaText;
String input;
String area;
public TestShape()
{
JPanel jp = new JPanel();
c = new Circle(65);
r = new Rectangle(60,80);
add(r);
add(c);
r.setBounds(10, 0, 300,300);
c.setBounds(250, 0, 300, 300);
getContentPane().add(jp);
jp.setLayout(null);
shapeName = new JTextField(" ");
shapeName.setBounds(150, 200, 335, 22);
jp.add(shapeName);
add(jp);
areaText = new JTextField();
areaText.setBounds(150, 222, 335, 22);
jp.add(areaText);
add(jp);
JButton enlarge = new JButton("Enlarge");
enlarge.setBounds(150, 300, 80, 28);
jp.add(enlarge);
add(jp);
enlarge.addActionListener(new enlargeListener());
JButton shrink = new JButton("Shrink");
shrink.setBounds(235, 300, 80, 28);
jp.add(shrink);
add(jp);
shrink.addActionListener(new shrinkListener());
}
public static void main(String[] args)
{
TestShape test = new TestShape();
test.setVisible(true);
test.setSize(500,500);
test.setLocation(500,100);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class enlargeListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent arg0)
{
input = shapeName.getText().toString();
if(input == "rectangle")
{
r.enlarge();
//areaText.setText(r.getArea());
}
else if (input == "circle")
{
c.enlarge();
}
else
{
System.out.print("cannot do");
}
}
}
class shrinkListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if(shapeName.getText() == "rectangle")
{
r.shrink();
}
else
{
c.shrink();
}
}
}
}