java输入框
时间: 2023-09-08 07:11:34 浏览: 44
要创建一个 Java 输入框,可以使用 Java Swing 库中的 JTextField 类。以下是一个简单的示例:
```java
import javax.swing.*;
public class InputBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Input Box Example");
JTextField textField = new JTextField(20);
textField.setBounds(50, 50, 150, 30);
frame.add(textField);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
```
在这个示例中,我们创建了一个 JFrame 对象,并在其上添加了一个 JTextField 对象。`setBounds` 方法用于设置输入框的位置和大小。最后,我们设置了 JFrame 的大小、布局和可见性。运行这个程序,你将会看到一个简单的输入框。
相关问题
gui java 输入框
你可以使用 Java Swing 中的 JTextField 类来创建 GUI 中的输入框。以下是一个简单的示例代码:
```java
import javax.swing.JFrame;
import javax.swing.JTextField;
public class InputBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Input Box Example");
JTextField inputBox = new JTextField();
inputBox.setBounds(50, 50, 150, 30); // 设置输入框位置和大小
frame.add(inputBox);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
```
在上面的示例中,我们创建了一个 JFrame 对象和一个 JTextField 对象,并将 JTextField 对象添加到 JFrame 对象中。我们还设置了输入框的位置和大小,然后将 JFrame 对象设置为可见。
你可以根据需要调整输入框的大小和位置。如果你想在输入框中显示默认文本,你可以使用 JTextField 的 setText() 方法来设置默认文本。
Java 输入框加减法
很高兴为您解答。对于您的问题,可以使用Java Swing中的JTextField和JButton组件来实现。
首先创建两个JTextField组件用于输入数字,然后创建两个JButton组件用于加法和减法运算。当用户单击加法或减法按钮时,程序将读取文本字段中的输入值并执行相应的运算,并在第三个JTextField组件中显示结果。
下面是示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
private JTextField textField1, textField2, resultField;
private JButton addButton, minusButton;
public Calculator() {
super("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// create the text fields
textField1 = new JTextField(10);
textField2 = new JTextField(10);
resultField = new JTextField(10);
resultField.setEditable(false);
// create the buttons
addButton = new JButton("+");
addButton.addActionListener(this);
minusButton = new JButton("-");
minusButton.addActionListener(this);
// add the components to the frame
add(textField1);
add(textField2);
add(addButton);
add(minusButton);
add(resultField);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Calculator();
}
public void actionPerformed(ActionEvent e) {
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
int result = 0;
if (e.getSource() == addButton) {
result = num1 + num2;
} else if (e.getSource() == minusButton) {
result = num1 - num2;
}
resultField.setText(Integer.toString(result));
}
}
```
请注意,此代码仅用于教学和演示用途,可能存在漏洞和安全隐患。在实际应用中,请使用更安全和可靠的代码实现。
希望这可以帮助您解决问题!