我在创建这个框架时使用了eclipse
这只是一个示例代码,但我只是想知道它是如何运作的
对于更多的视角,请在这里问。
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextField;
public class ExampleApp {
private JFrame frmHi;
private JTextField textField;
private JButton btnAnother;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleApp window = new ExampleApp();
window.frmHi.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ExampleApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHi = new JFrame();
frmHi.setTitle("Hi");
frmHi.setBounds(100, 100, 450, 300);
frmHi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHi.getContentPane().setLayout(null);
JButton btnEnter = new JButton("Enter");
btnEnter.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
textField.setText("You pressed enter");
}
}
});
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("Hi there from button");
}
});
btnEnter.setBounds(119, 63, 89, 23);
frmHi.getContentPane().add(btnEnter);
textField = new JTextField();
textField.setEnabled(false);
textField.setEditable(false);
textField.setBounds(108, 30, 173, 20);
frmHi.getContentPane().add(textField);
textField.setColumns(10);
btnAnother = new JButton("Backspace");
btnAnother.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == KeyEvent.VK_BACK_SPACE){
textField.setText("you pressed backspace");
}
}
});
btnAnother.setBounds(119, 119, 89, 23);
frmHi.getContentPane().add(btnAnother);
}
}