创建一个JFrame,在一个输入框中输入数字,然后乘以2显示在另一个文本框中,点击相应按钮实现相应功能。
package com.demo;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
class TemperatureFrame extends JFrame{
private JButton jFahrenheit = new JButton("Fahrenheit");
private JButton jCelsius = new JButton("Celsius");
private JButton jclr = new JButton("Clear");
private JTextArea jTextFahrenheit = new JTextArea(1, 5);
private JTextArea jTextCelsius = new JTextArea(1, 5);
private JPanel jPanelText = new JPanel();
private JPanel jPanelButton = new JPanel();
private WindowListener actionListener = new WindowListener();
public TemperatureFrame(){
creatWindow();
}
private void creatWindow(){
this.setLocation(200, 200);
this.setSize(300, 300);
this.setLayout(new BorderLayout());
this.add(jPanelText, BorderLayout.CENTER);
this.add(jPanelButton, BorderLayout.SOUTH);
jPanelText.setLayout(new FlowLayout());
jPanelText.add(jTextFahrenheit);
jPanelText.add(jTextCelsius);
jPanelText.add(jclr);
jPanelButton.add(jFahrenheit);
jPanelButton.add(jCelsius);
jFahrenheit.addActionListener(actionListener);
jCelsius.addActionListener(actionListener);
jclr.addActionListener(actionListener);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.pack();
this.setVisible(true);
}
class WindowListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == jFahrenheit){
try{
String fahrenheitValue = jTextFahrenheit.getText();
System.out.println(fahrenheitValue);
double faValue = Double.parseDouble(fahrenheitValue);
double ceValue = faValue * 2 - 1.0;
String celsiusValue = String.valueOf(ceValue);
jTextCelsius.setText(celsiusValue);
}
catch(Exception ex){
JOptionPane.showMessageDialog( null, "Please input values");
}
}
else if(e.getSource() == jCelsius){
try{
String ceValue = jTextCelsius.getText();
double ce = Double.parseDouble(ceValue);
double feValue = ce / 2;
String fe = String.valueOf(feValue);
jTextFahrenheit.setText(fe);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, "Please input values");
}
}
else if(e.getSource() == jclr){
jTextFahrenheit.setText(null);
jTextCelsius.setText(null);
}
}
}
}
public class Demo {
public static void main(String[] args) {
new TemperatureFrame();
}
}
Swing提供了3种文本输入输出组件,分别是JTextField,JPasswordField, JTextArea。其中JTextField只能实现单行文本的输入输出, JPasswordField把输出的文字信息
设置为其他显示字符(密码输入框采用这种形式),JTextArea实现多行文本的输入输出。这3个子类都是JTextComponent的子类。