我試圖讓'enlargeListener implements ActionListener'類從shapeName JTextField接受輸入並將其應用到for循環中。規範是,如果shapeName.getText()從shapeName JTextfield中獲取的內容與循環中指定的內容匹配(aka ==「rectangle」或==「circle」),它將實現放大或縮小方法。從JText字段輸入輸入
問題是我知道它返回JTextField中的內容......但即使它滿足循環的限定條件。循環仍然失敗,我無法弄清楚爲什麼。
例如..如果我在第一個文本框中輸入'rectangle'...它將返回到'enlargeListener implements'類下的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();
}
}
}
}
太棒了:D這麼簡單..yet殺死了整個代碼:) – user1780149