JTextField,JTextArea,JTextPane,这三个什么区别?想用带滚动条自动换行的文本框该调用哪个控件,代码?

JTextField,JTextArea,JTextPane,这三个什么区别?想用带滚动条自动换行的文本框该调用哪个控件,代码?,第1张

貌似都行,出滚动条的要点是你要用个JScrollPane把文本区包起来
import javaawt;
import javaawtevent;
import javaxswing;
public class JTextAreaTest {
public static void main(String[] args) {
JFrame f = new JFrame();
Container contentPane = fgetContentPane();
contentPanesetLayout(new BorderLayout());
JPanel p1 = new JPanel();
p1setLayout(new GridLayout(1, 1));
JTextArea t1 = new JTextArea(5, 25);
t1setTabSize(10);
t1setLineWrap(true);
t1setWrapStyleWord(true);
p1add(new JScrollPane(t1));
contentPaneadd(p1);
fpack();

fsetSize(200,200);
fsetVisible(true);
fsetDefaultCloseOperation(JFrameDISPOSE_ON_CLOSE);
}
}

JScrollPane
文本域,Jtable,Jtree都可以放进去,超过显示就会出滚动条 
-----------------------------------------------------
import javaawtBorderLayout;
import javaxswingJFrame;
import javaxswingJScrollPane;
import javaxswingJTextPane;
public class MainFrame extends JFrame {
private String content = "row\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\nrow\r\n";
public MainFrame() {
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JScrollPane scrollPane_2 = new JScrollPane();
getContentPane()add(scrollPane_2, BorderLayoutCENTER);
JTextPane textPane = new JTextPane();
textPanesetText(content);
scrollPane_2setViewportView(textPane);
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}

package hao;
import javaawtBorderLayout;
import javaawtColor;
import javaawtDimension;
import javaawtGridLayout;
import javaioFile;
import javaxswingBorderFactory;
import javaxswingBox;
import javaxswingImageIcon;
import javaxswingJButton;
import javaxswingJComboBox;
import javaxswingJLabel;
import javaxswingJPanel;
import javaxswingJScrollPane;
import javaxswingJTextArea;
import javaxswingJTextPane;
import javaxswingtextBadLocationException;
import javaxswingtextSimpleAttributeSet;
import javaxswingtextStyleConstants;
import javaxswingtextStyledDocument;
public class ChatPanel extends JPanel {

private static final long serialVersionUID = 1L;
JButton send,record,saveRecord,image;
JTextArea inputArea;
JTextPane text;//注意用法
JComboBox fontName = null, fontSize = null, fontStyle = null, fontColor = null,fontBackColor = null;
public StyledDocument doc = null; JScrollPane scrollPane;JPanel textChat;

JButton music;
public ChatPanel() {
setLayout(new BorderLayout());

text = new JTextPane();
textsetEditable(false);

doc = textgetStyledDocument();//跟踪文本和写到该区域的位置
scrollPane = new JScrollPane(text);
//注意下面对JComboBox的巧用
String[] str_name = { "宋体", "黑体", "Dialog", "Gulim" };
String[] str_Size = { "12", "14", "18", "22", "30", "40" };
String[] str_Style = { "常规", "斜体", "粗体", "粗斜体" };
String[] str_Color = { "黑色", "红色", "蓝色", "", "绿色" };
String[] str_BackColor = { "无色", "灰色", "淡红", "淡蓝", "淡黄", "淡绿" };
fontName = new JComboBox(str_name);
fontSize = new JComboBox(str_Size);
fontStyle = new JComboBox(str_Style);
fontColor = new JComboBox(str_Color);
fontBackColor = new JComboBox(str_BackColor);

fontNamesetBackground(new Color(255,153,255));
fontSizesetBackground(new Color(255,153,255));
fontStylesetBackground(new Color(255,153,255));
fontColorsetBackground(new Color(255,153,255));
fontBackColorsetBackground(new Color(255,153,255));
Box box = BoxcreateVerticalBox();//创建一个可以容纳多个Box组件的Box
Box box_1 = BoxcreateHorizontalBox();
Box box_2 = BoxcreateHorizontalBox();
Box box_4 = BoxcreateHorizontalBox();
boxadd(box_1);
boxadd(box_2);
boxadd(box_4);
JLabel b1= new JLabel("字体~~"), b2 = new JLabel("样式~~"),b3 = new JLabel("字号~~"),b4 = new JLabel("颜色~~"),b5 = new JLabel("背景~~");
b1setBackground(new Color(255,153,255));
b2setBackground(new Color(255,153,255));
b3setBackground(new Color(255,153,255));
b4setBackground(new Color(255,153,255));
b5setBackground(new Color(255,153,255));
box_1add(b1);
box_1add(fontName);
box_1add(BoxcreateHorizontalStrut(8));
box_1add(b2);
box_1add(fontStyle);
box_1add(BoxcreateHorizontalStrut(8));
box_1add(b3);
box_1add(fontSize);
box_2add(BoxcreateHorizontalStrut(8));
box_2add(b4);
box_2add(fontColor);
box_2add(BoxcreateHorizontalStrut(8));
box_4add(b5);
box_4add(fontBackColor);
textChat = new JPanel();
textChatsetLayout(new BorderLayout());
textChatsetBackground(new Color(255,153,255));

inputArea = new JTextArea(3, 20);
inputAreasetLineWrap(true); //设置文本区的换行策略。88888
send = new JButton("发送");
record=new JButton("显示记录");
saveRecord=new JButton("储存记录");
image=new JButton("表情");
sendsetBackground(new Color(255,153,255));
recordsetBackground(new Color(255,153,255));
saveRecordsetBackground(new Color(255,153,255));
imagesetBackground(new Color(255,153,255));
Box box_3 = BoxcreateHorizontalBox();
box_3add(send); box_3add(BoxcreateHorizontalStrut(8));//设置按钮间距888
box_3add(record); box_3add(BoxcreateHorizontalStrut(8)); //设置按钮间距888
box_3add(saveRecord); box_3add(BoxcreateHorizontalStrut(8));//设置按钮间距888
box_3add(image);
boxsetBorder(BorderFactorycreateLineBorder(new Color(102,102,0),5));//设置Box的边框线
box_3setBorder(BorderFactorycreateLineBorder(new Color(102,102,0),5));
textChatadd(box,BorderLayoutNORTH);
textChatadd(inputArea,BorderLayoutCENTER);
textChatadd(box_3, BorderLayoutSOUTH);

inputArearequestFocus(true);
inputAreasetBorder(BorderFactorycreateLineBorder(new Color(102,102,0),5));//设置输入窗口边框线
textsetBorder(BorderFactorycreateLineBorder(new Color(102,102,0),8));//设置输入窗口边框线

JPanel audioPanel = new JPanel();//最上面的边框
audioPanelsetBackground(new Color(255,153,255));
audioPanelsetLayout(new GridLayout(1,1));

music = new JButton("想听就听");
musicsetPreferredSize(new Dimension(320,50));
musicsetBorder(BorderFactorycreateLineBorder(ColorBLACK,10));//设置输入窗口边框线
audioPaneladd(music);
add(audioPanel, BorderLayoutNORTH);
add(scrollPane,BorderLayoutCENTER);
add(textChat, BorderLayoutSOUTH);
}
void insertIcon(ImageIcon image) {
textsetCaretPosition(docgetLength());
textinsertIcon(image);
insert(new MessageStyle());///
}
public void insert(MessageStyle attrib) {
try {

docinsertString(docgetLength(), attribgetText() + "\n", attribgetAttrSet());//写完后接着换行

} catch (BadLocationException e) {
eprintStackTrace();
}
}
public MessageStyle getMessageStyle(String line) {

MessageStyle att = new MessageStyle();

attsetText(line);
attsetName((String) fontNamegetSelectedItem());
attsetSize(IntegerparseInt((String) fontSizegetSelectedItem()));
String temp_style = (String) fontStylegetSelectedItem();
if (temp_styleequals("常规")) {
attsetStyle(MessageStyleGENERAL);
}
else if (temp_styleequals("粗体")) {
attsetStyle(MessageStyleBOLD);
}
else if (temp_styleequals("斜体")) {
attsetStyle(MessageStyleITALIC);
}
else if (temp_styleequals("粗斜体")) {
attsetStyle(MessageStyleBOLD_ITALIC);
}
String temp_color = (String) fontColorgetSelectedItem();
if (temp_colorequals("黑色")) {
attsetColor(new Color(0, 0, 0));
}
else if (temp_colorequals("红色")) {
attsetColor(new Color(255, 0, 0));
}
else if (temp_colorequals("蓝色")) {
attsetColor(new Color(0, 0, 255));
}
else if (temp_colorequals("")) {
attsetColor(new Color(255, 255, 0));
}
else if (temp_colorequals("绿色")) {
attsetColor(new Color(0, 255, 0));
}
String temp_backColor = (String) fontBackColorgetSelectedItem();
if (!temp_backColorequals("无色")) {
if (temp_backColorequals("灰色")) {
attsetBackColor(new Color(200, 200, 200));
}
else if (temp_backColorequals("淡红")) {
attsetBackColor(new Color(255, 200, 200));
}
else if (temp_backColorequals("淡蓝")) {
attsetBackColor(new Color(200, 200, 255));
}
else if (temp_backColorequals("淡黄")) {
attsetBackColor(new Color(255, 255, 200));
}
else if (temp_backColorequals("淡绿")) {
attsetBackColor(new Color(200, 255, 200));
}
}
return att;
}
}

我这有个联系swing的界面大全,里面包含了常用的主件,可以直接用
package demosynth;
import javaxswing;
import javaawt;
import javaawtevent;
import javalangreflectInvocationTargetException;
import javaxswingtree;
import javaxswingevent;
import javaxswingborder;
import javaxswingplafmetalMetalLookAndFeel;
import javaxswingplafsynthSynthLookAndFeel;
import javaxswingtable;
public class SwingTest extends JFrame {
/
主模块,初始化所有子模块,并设置主框架的相关属性
/
public SwingTest() {
// 初始化所有模块
MenuTest menuTest = new MenuTest();
LeftPanel leftPanel = new LeftPanel();
RightPanel rightPanel = new RightPanel();
BottomPanel bottomPanel = new BottomPanel();
CenterPanel centerPanel = new CenterPanel();
// 设置主框架的布局
Container c = thisgetContentPane();
// csetLayout(new BorderLayout());
thissetJMenuBar(menuTest);
cadd(leftPanel, BorderLayoutWEST);
cadd(rightPanel, BorderLayoutEAST);
cadd(centerPanel, BorderLayoutCENTER);
cadd(bottomPanel, BorderLayoutSOUTH);
// 利用无名内隐类,增加窗口事件
thisaddWindowListener(new WindowAdapter() {
public void WindowClosing(WindowEvent e) {
// 释放资源,退出程序
dispose();
Systemexit(0);
}
});
setSize(800, 600);
setTitle(" All Groupware Of Swing ");
// 隐藏frame的标题栏,此功暂时关闭,以方便使用window事件
// setUndecorated(true);
setLocation(200, 150);
thissetVisible(true);
}
// //////////////////////////////////////////////////////////////////////////
/
菜单栏处理模块 JMenuBar --+ --JMenu--+ --JMenuItem --ActionListener

/
class MenuTest extends JMenuBar {
private JDialog aboutDialog;
/
菜单初始化 *** 作
/
public MenuTest() {
JMenu fileMenu = new JMenu("File");
JMenuItem exitMenuItem = new JMenuItem("Exit", KeyEventVK_E);
JMenuItem aboutMenuItem = new JMenuItem("About", KeyEventVK_A);
fileMenuadd(exitMenuItem);
fileMenuadd(aboutMenuItem);
thisadd(fileMenu);
aboutDialog = new JDialog();
initAboutDialog();
// 菜单事件
exitMenuItemaddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
Systemexit(0);
}
});
aboutMenuItemaddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// "关于"对话框的处理
aboutDialogsetVisible(true);
}
});
}
/
返回关于对话框
/
public JDialog getAboutDialog() {
return aboutDialog;
}
/
设置"关于"对话框的外观及响应事件, *** 作和JFrame一样都是在内容 框架上进行的
/
public void initAboutDialog() {
aboutDialogsetTitle("About");
Container con = aboutDialoggetContentPane();
// Swing 中使用html语句
Icon icon = new ImageIcon("smilegif");
JLabel aboutLabel = new JLabel("<html><b><font size=5>"
+ "<center>All Groupware Of Swing !" + "<br>KasamHuang",
icon, JLabelCENTER);
// JLabel aboutLabel = new JLabel("Swing
// 组件大全简体版!",icon,JLabelCENTER);
conadd(aboutLabel, BorderLayoutCENTER);
aboutDialogsetSize(450, 225);
aboutDialogsetLocation(300, 300);
aboutDialogaddWindowListener(new WindowAdapter() {
public void WindowClosing(WindowEvent e) {
dispose();
}
});
}
}
// //////////////////////////////////////////////////////////////////////////
/
最左边模块,继承JPanel,初始化内容为JTree JPanel--+ --JTree
/
class LeftPanel extends JPanel {
private int i = 0;
public LeftPanel() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child = new DefaultMutableTreeNode("Child");
DefaultMutableTreeNode select = new DefaultMutableTreeNode("select");
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("" + i);
rootadd(child);
rootadd(select);
childadd(child1);
JTree tree = new JTree(root);
treegetSelectionModel()setSelectionMode(
TreeSelectionModelDISCONTIGUOUS_TREE_SELECTION);
// 每个节点的行高
treesetRowHeight(20);
treeaddTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
// 内隐类不能直接引用外部类tree,1外部变量可申明为final 2新建外部类的对象
JTree tree = (JTree) egetSource();
DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree
getLastSelectedPathComponent();
i++;
selectNodeadd(new DefaultMutableTreeNode("" + i));
// Object s = treegetLastSelectedPathComponent();//
// getSelectedValue();
// JOptionPaneshowMessageDialog(null, s + " is selected",
// "Message !", JOptionPaneYES_OPTION);
}
});
treesetPreferredSize(new Dimension(100, 300));
// treesetEnabled(true);
JScrollPane scrollPane = new JScrollPane(tree);
// scrollPanesetSize(100,350);
thisadd(scrollPane);
}
}
// //////////////////////////////////////////////////////////////////////////
/
最下面层模块,继承JPanel,初始化内容为进度条,并由定时器控制 JPanel--+ --JProcessBar --Timer
/
class BottomPanel extends JPanel {
private JProgressBar pb;
public BottomPanel() {
pb = new JProgressBar();
pbsetPreferredSize(new Dimension(550, 20));
// 设置定时器,用来控制进度条的处理
Timer time = new Timer(1, new ActionListener() {
int counter = 0;
public void actionPerformed(ActionEvent e) {
counter++;
pbsetValue(counter);
Timer t = (Timer) egetSource();
// 如果进度条达到最大值重新开发计数
if (counter == pbgetMaximum()) {
tstop();
counter = 0;
tstart();
}
}
});
timestart();
pbsetStringPainted(true);
pbsetMinimum(0);
pbsetMaximum(1000);
pbsetBackground(Colorwhite);
pbsetForeground(Colorred);
thisadd(pb);
}
/
设置进度条的数据模型
/
public void setProcessBar(BoundedRangeModel rangeModel) {
pbsetModel(rangeModel);
}
}
// //////////////////////////////////////////////////////////////////////////
/
最右边模块,继承JPanel,初始化各种按钮 JPanel--+ --JButton --JToggleButton -- JList --
JCombox --JCheckBox
/
class RightPanel extends JPanel {
public RightPanel() {
thissetLayout(new GridLayout(8, 1));
// 初始化各种按钮
JCheckBox checkBox = new JCheckBox("CheckButton");
JButton button = new JButton("OpenFile");
buttonaddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser file = new JFileChooser();
int result = fileshowOpenDialog(new JPanel());
if (result == fileAPPROVE_OPTION) {
String fileName = filegetSelectedFile()getName();
String dir = filegetCurrentDirectory()toString();
JOptionPaneshowConfirmDialog(null,
dir + "" + fileName, "SelectFile",
JOptionPaneYES_OPTION);
}
}
});
JToggleButton toggleButton = new JToggleButton("RadioButton");
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton radioButton1 = new JRadioButton("RadioButton 1", false);
JRadioButton radioButton2 = new JRadioButton("RadioButton 2", false);
// 组合框的处理
JComboBox comboBox = new JComboBox();
comboBoxsetToolTipText("ComboBox");
comboBoxaddItem("程序员");
comboBoxaddItem("分析员");
comboBoxaddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox comboBox1 = (JComboBox) egetSource();
comboBox1addItem("程序员");
comboBox1addItem("分析员");
}
});
// 列表框的处理
DefaultListModel litem = new DefaultListModel();
litemaddElement("SAT");
litemaddElement("SUN");
JList list = new JList(litem);
listaddListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
JList l = (JList) egetSource();
Object s = lgetSelectedValue();
JOptionPaneshowMessageDialog(null, s, "Message !",
JOptionPaneYES_OPTION);
}
});
// 增加按钮组
buttonGroupadd(radioButton1);
buttonGroupadd(radioButton2);
// 增加各种按钮到JPanel中显示
add(button);
add(toggleButton);
add(checkBox);
add(radioButton1);
add(radioButton2);
add(comboBox);
add(list);
thissetBorder(new EtchedBorder(EtchedBorderLOWERED,
ColorLIGHT_GRAY, Colorblue));
}
}
// //////////////////////////////////////////////////////////////////////////
/
中间层模块,继承JPanel,初始化页签,并在页签中设置文本区,表格, 文本区上下用分隔条分隔 JPanel--+ -JTabbedPane--+
--Draw --JTable -JTextAreas -JText --JPopupMenu
/
class CenterPanel extends JPanel {
public CenterPanel() {
JTabbedPane tab = new JTabbedPane(JTabbedPaneTOP);
JTextField textField = new JTextField(
"Text Area,Click <Text Button> Will select file !");
textFieldsetActionCommand("textField");
JTextPane textPane = new JTextPane();
textPanesetCursor(new Cursor(CursorTEXT_CURSOR));
textPanesetText("Editor,Click the TextArea ");
// textPanesetForeground(new ImageIcon(""));
textPaneaddMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JTextPane textPane = (JTextPane) egetSource();
textPanesetText("Editor click command success!");
// textFieldsetText(""+textPanegetText());
}
});
/
UpperCaseDocument doc = new Document();
textFieldsetDocumentsetDocument(doc);
docaddDocumentListener(new DocumentListener() { public void
changedUpdate(DocumentEvent e){} public void
removeUpdate(DocumentEvent e){} public void
insertUpdate(DocumentEvent e) { Document text =
(Document)egetDocument(); textsetText("Copy Success !"); } });
/
JSplitPane splitPane = new JSplitPane(JSplitPaneVERTICAL_SPLIT,
textField, textPane);
JTable table = new JTable(10, 10);
// UIManagerget("TablefocusCellForeground");
// tableshowHorizontalLines(true);
// tableshowVerticalLines(true);
// tablesetGridColor(Colorblue);
JPanel pane = new JPanel();
paneadd(tablegetTableHeader(), BorderLayoutNORTH);
paneadd(table);
tabaddTab("Text Action", splitPane);
// tabaddTab(tablegetTableHeader());
tabaddTab("Table Action", pane);
tabsetPreferredSize(new Dimension(500, 600));
thisadd(tab);
thissetEnabled(true);
}
}
public static void main(String args[]){
new SwingTest();
}
}

LineText //代表(最后)读取的一行文本

DiDiansetText(LineText);//把最后一把文本"设置"为文本组件的内容

问题就出现在:

在while循环里 ,每一次都会使用最后一行代码来替换 文本组件的内容;    所以文本组件只会显示最后一行的内容

解决办法[推荐的方法]:

 StringBuilder sb=new StringBuilder();
    while((LineText=BRreadLine())!=null){
        sbappend(LineText); //把每一行都保存到StringBuilder
        sbappend("\r\n");//如果每一行都需要换行,那么把每一行后面都加上一个换行符
    }
    //读取完了,才设置文本组件的文字
    DiDiansetText(sbtoString);

最后建议 : 

JTextArea文本组件说明

JTextArea jta=new JTextArea();//文本域组件, 可以调用append方法,追加文字
jtaappend(LineText+"\r\n"); //但是频繁的追加文本,是不推荐的 *** 作,导致性能降低
//建议还是使用StringBuilder或者StringBuffer来连接字符串

JTextField / JTextPane文本组件的说明

JTextPane jtp=new JTextPane();
jtpsetText(jtpgetText()+LineText+"\r\n");//可以在调用setText的时候 ,
//先getText获取之前文本,在添加上新的文本


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/10292931.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-07
下一篇 2023-05-07

发表评论

登录后才能评论

评论列表(0条)

保存