【发布时间】:2020-10-20 02:14:30
【问题描述】:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RecallStudy extends JFrame
implements KeyListener,
ActionListener
{
//CREATION OF ELEMENTS
JLabel recallLabel;
JTextField enterText;
String enterTex;
JTextField recieveText;
JPanel displayInfo;
GridBagConstraints constraints = new GridBagConstraints();
public static void main (String [] args) {
//MAKING THE WINDOW
JFrame frame = new JFrame("RecallStudy");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(500, 500);
frame.setLocation(200, 200);
frame.setContentPane(new RecallStudy());
frame.pack();
frame.setVisible(true);
}
//GRIDLAYOUT CONSTRUCTION
public RecallStudy() {
setLayout(new GridBagLayout());
constraints.weightx = 3.0;
constraints.weighty = 3.0;
constraints.fill = GridBagConstraints.BOTH;
int x, y; // for clarity
constraints.gridheight = 2; // span two rows
addGB(recieveText, x =2, y = 1);
constraints.gridheight = 2; // set it back
addGB(enterText, x = 0, y = 1);
constraints.gridwidth = 1; // span two columns
addGB(new JLabel("Recall"), x = 1, y = 0);
constraints.gridwidth = 2; // set it back
addGB(new JLabel(""), x = 0, y = 0);
constraints.gridwidth = 1;
addGB(new JLabel(""), x = 2, y =0);
constraints.gridwidth = 1;
addGB(new JLabel(""), x = 2, y = 2);
constraints.gridwidth = 1;
addGB (new JLabel(""), x = 0, y =2);
constraints.gridwidth = 1;
//Set the proper restrictions on the listeners
enterText.addKeyListener(this);
recieveText.setEditable(false);
}
void addGB(Component component, int x, int y) {
constraints.gridx = x;
constraints.gridy = y;
add(component, constraints);
}
public RecallStudy(String name) {
super (name);
}
public void keyTyped(KeyEvent e) {
displayInfo(e, "KEY TYPED: ");
}
/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
displayInfo(e, "KEY PRESSED: ");
}
/** Handle the key released event from the text field. */
public void keyReleased(KeyEvent e) {
displayInfo(e, "KEY RELEASED: ");
}
/** Handle the button click. */
public void actionPerformed(ActionEvent e) {
//Clear the text components.
enterText.setText("");
recieveText.setText(enterTex);
//Return the focus to the typing area.
enterText.requestFocusInWindow();
}
private void displayInfo (KeyEvent e, String keyStatus) {
}
}
由于某种原因,这段代码没有运行...我不明白为什么...有人可以解释一下吗?当我把它关闭时,我的代码没有任何错误,但是当我尝试运行它的第二次它不起作用。我很困惑我缺少哪些组件来让它运行。我知道我还没有完成 displayInfo 部分,但这似乎不是它无法运行的原因。我真的很困惑,我觉得我开始这段代码的方式与其他所有代码一样,但这个无法运行。
【问题讨论】:
-
这在我看来是您previous question 的延续。看起来您已经对该问题中的代码进行了一些改进,而不是 edit 该问题,您决定发布另一个问题。你的代码给我的印象是你需要彻底学习 Swing 而这不是你可以通过关于 SO 的问题来做的事情。请注意
weightx的值必须介于0.0和1.0之间,而不是3.0。
标签: java swing nullpointerexception jtextfield gridbaglayout