我是 Java 新手,现在正在学习初学者课程。非常好,我正在尝试各种东西,但现在我被卡住了。这段代码不起作用。它应该以相反的顺序(按字)输出输入。
翻转它的代码在我编写的一段没有 GUI 的代码中工作,现在我正试图让它在带有固定按钮、标签等的 GUI 中工作。为此,我从互联网上复制了一个示例并尝试以这样的方式改变它会起作用。但它似乎没有找到我在 actionPerformed 中使用的变量并且在 AddComponentsToPane 中设置。它必须与静态和非静态有关,我似乎不太清楚
任何帮助将不胜感激。
这是代码。
package flipit;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.*; //ArrayList;
import javax.swing.*;
public class FlipIt extends JFrame implements ActionListener {
public static void addComponentsToPane(Container pane) {
pane.setLayout(null);
JLabel greetingLabel = new JLabel("Enter your array ");
JTextField inField = new JTextField();
JTextField commentaryField = new JTextField();
JTextField strLen = new JTextField();
JButton button = new JButton("FlipIt");
pane.add(greetingLabel);
pane.add(inField);
pane.add(commentaryField);
pane.add(button);
Insets insets = pane.getInsets();
Dimension size = button.getPreferredSize();
greetingLabel.setBounds ( 5 + insets.left, 35 + insets.top,size.width + 40, size.height);
inField.setBounds (120 + insets.left, 33 + insets.top,size.width + 200, size.height);
//size = commentaryField.getPreferredSize();
commentaryField.setBounds(120 + insets.left, 80 + insets.top,size.width + 200, size.height);
size = button.getPreferredSize();
button.setBounds ( 5 + insets.left, 80 + insets.top,size.width + 40, size.height);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Reverse the input string.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Size and display the window.
Insets insets = frame.getInsets();
frame.setSize(500 + insets.left + insets.right,
425 + insets.top + insets.bottom);
frame.setVisible(true);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void actionPerformed(ActionEvent event) {
String InputStr = inField.getText();
int length = InputStr.length();
if (InputStr.compareTo("") == 0 || InputStr == null) {
commentaryField.setText("Please enter some data, this array is empty");
}
else {
// Convert string variable to an ArrayList.
List<String> list = new ArrayList<String>(Arrays.asList(InputStr.split(" ")));
// Converting ArrayList to a String Array
String [] InputList = list.toArray(new String[list.size()]);
int i = 0 ;
String ReverseOrder = "" ;
// starting for loop to print the array in reversed order.
for (i=InputList.length-1;i>=0; i--)
{ReverseOrder = ReverseOrder + " " + InputList[i] ;
}
// print result.
commentaryField.setText(ReverseOrder);
strLen.setText("Lengte string : "+ length);
}
}
}
谢谢,罗伯。