在我的化学课上,老师告诉我可以通过制作一些与化学相关的课程来获得额外的学分。我觉得这是个好主意,因为我毕竟是在学习计算机科学。到目前为止,这是我的代码,但我无法让它显示我想要的字符串,即使在我按下回车键之后。任何帮助都会很棒。谢谢
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class window extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
private JTextField textBox;
private String textInput;
public window() {
textInput = "";
textBox = new JTextField("Enter symbol here:", 30);
this.add(textBox);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.CYAN);
g.setFont(new Font("", Font.BOLD, 20));
g.drawString("Enter element symbol in text box above.", 110, 50);
g.drawString(textInput, 100, 100);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER) {
textInput = textBox.getText();
}
repaint();
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
import java.awt.Color;
import javax.swing.JFrame;
public class elementRunner {
public static void main(String[] args) {
window panel = new window();
JFrame frame = new JFrame("Element project ~ By: Harsh Patel");
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel.setBackground(Color.RED);
frame.setVisible(true);
frame.addKeyListener(panel);
frame.add(panel);
}
}
问题是将侦听器设置为JPanel
,如果将其设置为JTextField
,则可以正常工作。不过,我附上了下面的代码,也许JLabels会有所帮助。我的意思是,它更容易,更结构化等等。但你必须学习布局是如何工作的。不管怎样,在我看来就是这样:
ElementRunner.java (大写Element)
public class ElementRunner {
public static void main(String[] args) {
MyWindow panel = new MyWindow();
panel.setBackground(Color.RED);
JFrame frame = new JFrame("Element project ~ By: Harsh Patel");
frame.setBounds(100, 100, 600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
frame.setVisible(true);
}
}
MyWindow.java(Window太通用了,这样我们就知道它是你的,像Element一样大写)
public class MyWindow extends JPanel implements KeyListener {
private static final long serialVersionUID = 1L;
private JTextField textBox;
private String textInput;
public MyWindow() {
textInput = "";
textBox = new JTextField("Enter symbol here:", 30);
textBox.addKeyListener(this); // This line adds the listener to the TextField
this.add(textBox);
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.CYAN);
g.drawString("Enter element symbol in text box above.", 110, 50);
g.drawString(textInput, 100, 100);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_ENTER) {
textInput = textBox.getText();
}
repaint();
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
}