有没有办法将文本框放入用户可以输入文本的JFrame中?有点像TextEdit或Notepad应用程序。
答案 0 :(得分:2)
与记事本最接近的是JTextArea
。将其包裹在JScrollPane
的滚动条中。可见。
提示:使其成为原生的PLAF,使其更加逼近。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Editpad {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(2,3,2,3));
// adjust numbers for a bigger default area
JTextArea editArea = new JTextArea(5,40);
// adjust the font to a monospaced font.
Font font = new Font(
Font.MONOSPACED,
Font.PLAIN,
editArea.getFont().getSize());
editArea.setFont(font);
gui.add(new JScrollPane(editArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
JFrame f = new JFrame("Editpad");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See http://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
答案 1 :(得分:1)
使用JTextField
,这是一个单行“文本区域”,或JTextArea
,可以处理多行。两者的作用相似。以下是JTextField
的简单示例:
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextField;
public class Foo extends JFrame {
public Foo() {
setLayout(new FlowLayout());
JTextField field = new JTextField(20);
add(field);
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
Foo foo = new Foo();
}
}
要对此类组件执行任何有用的操作,您还需要向组件添加事件/操作侦听器(比如JButton
)以对其中的文本执行某些操作(您可以通过调用{ getText()
或JTextField
)