下面列出了怎么用javax.swing.JTextArea的API类实例代码及写法,或者点击链接到github查看源代码。
public ChooseDirectory() {
setLayout(new PercentLayout(PercentLayout.VERTICAL, 3));
if (System.getProperty("javawebstart.version") != null) {
JTextArea area = new JTextArea(RESOURCE.getString("message.webstart"));
LookAndFeelTweaks.makeMultilineLabel(area);
add(area);
}
final JButton button = new JButton(RESOURCE.getString("selectDirectory"));
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectDirectory(button, null);
}
});
}
private JPanel createSqlRequestExplainPlanPanel(String sqlRequestExplainPlan) {
final JTextArea textArea = new JTextArea();
textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, textArea.getFont().getSize() - 1));
textArea.setEditable(false);
textArea.setCaretPosition(0);
// background nécessaire avec la plupart des look and feels dont Nimbus,
// sinon il reste blanc malgré editable false
textArea.setBackground(Color.decode("#E6E6E6"));
textArea.setText(sqlRequestExplainPlan);
final JPanel panel = new JPanel(new BorderLayout());
panel.setOpaque(false);
final JLabel label = new JLabel(getString("Plan_d_execution"));
label.setFont(label.getFont().deriveFont(Font.BOLD));
panel.add(label, BorderLayout.NORTH);
final JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
/**
* A�ade el textarea para el texto que se va a analizar
* @param contenedor contendor en el que añadirlo.
*/
private void anhadeTextAreaParaTextoAnalizado(Container contenedor) {
areaDeTextoAAnalizar = new JTextArea();
areaDeTextoAAnalizar.setLineWrap(true);
areaDeTextoAAnalizar.setWrapStyleWord(true);
areaDeTextoAAnalizar.setColumns(40);
areaDeTextoAAnalizar.invalidate();
JScrollPane scroll = new JScrollPane(areaDeTextoAAnalizar);
scroll.setBorder(new TitledBorder("Escribe o copia aquí un texto"));
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 4;
constraints.gridheight = 1;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.BOTH;
contenedor.add(scroll, constraints);
}
/**
* Initializes the widgets.
*/
@Override
protected void initGUI() {
super.initGUI();
setLayout(new BorderLayout());
m_TabbedPane = new JTabbedPane();
add(m_TabbedPane, BorderLayout.CENTER);
m_TextCode = new JTextArea();
m_TextCode.setFont(GUIHelper.getMonospacedFont());
m_TabbedPane.addTab("Write", new BaseScrollPane(m_TextCode));
m_PanePreview = new JEditorPane();
m_PanePreview.setEditable(false);
m_PanePreview.setContentType("text/html");
m_TabbedPane.addTab("Preview", new BaseScrollPane(m_PanePreview));
m_TabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
update();
}
});
}
private static void initAndShowUI() {
frame = new JFrame("Test frame");
frame.setSize(SIZE, SIZE);
frame.setLocationRelativeTo(null);
final JTextArea jta = new JTextArea();
jta.setBackground(Color.RED);
frame.add(jta);
jta.setText("1234567890");
jta.setFont(jta.getFont().deriveFont(150f));
jta.setDragEnabled(true);
jta.selectAll();
jta.setDropTarget(new DropTarget(jta, DnDConstants.ACTION_COPY,
new TestdropTargetListener()));
jta.addMouseListener(new TestMouseAdapter());
frame.setVisible(true);
}
/**
* Show the error list from the e-mail API if there are errors
*
* @param parent
* @param sfe
*/
private void showFailedException(SendFailedException sfe) {
String error = sfe.getMessage() + "\n";
Address[] ia = sfe.getInvalidAddresses();
if (ia != null) {
for (int x = 0; x < ia.length; x++) {
error += "Invalid Address: " + ia[x].toString() + "\n";
}
}
JTextArea ea = new JTextArea(error,6,50);
JScrollPane errorScrollPane = new JScrollPane(ea);
errorScrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
errorScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
JOptionPane.showMessageDialog(null,
errorScrollPane,
LangTool.getString("em.titleConfirmation"),
JOptionPane.ERROR_MESSAGE);
}
private void showEditableOptionPane(final String pText,
final String pTitle,
final int pMessageType)
{
final JTextArea ta = new JTextArea(48, 100);
ta.setText(pText);
ta.setWrapStyleWord(true);
ta.setLineWrap(false);
ta.setCaretPosition(0);
ta.setEditable(false);
JOptionPane.showMessageDialog( null,
new JScrollPane(ta),
pTitle,
pMessageType);
}
public void addChanPanel(String chanName) {
JTextArea messagePanel = new JTextArea();
messagePanel.setLineWrap(true);
messagePanel.setBackground(new Color(71, 71, 71));
messagePanel.setForeground(Color.white);
messagePanel.setFont(ircFont);
messagePanel.setEditable(false);
DefaultCaret dc = (DefaultCaret) messagePanel.getCaret();
dc.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
JTextArea userPanel = new JTextArea();
userPanel.setBackground(new Color(71, 71, 71));
messagePanels.put(chanName, messagePanel);
userPanels.put(chanName, userPanel);
}
@Override
public void insert(final String text, final int pos) {
final ScrollableJTextArea pane = getDelegate();
synchronized (getDelegateLock()) {
final JTextArea area = pane.getView();
final boolean doScroll = pos >= area.getDocument().getLength()
&& area.getDocument().getLength() != 0;
area.insert(text, pos);
revalidate();
if (doScroll) {
final JScrollBar vbar = pane.getVerticalScrollBar();
if (vbar != null) {
vbar.setValue(vbar.getMaximum() - vbar.getVisibleAmount());
}
}
}
repaintPeer();
}
private JPanel getAboutPanel() {
JPanel theAboutPanel = new JPanel( new GridBagLayout() );
GridBagConstraints theCons = getGridBagConstraints( 2 );
JLabel lab = new JLabel( new ImageIcon( getClass().getResource("images/Godctoon.gif" ) ) );
lab.setOpaque( false );
theAboutPanel.add( lab, theCons );
theCons.gridy++;
JTextArea a = new JTextArea( 250, 260 );
a.setText( "\n Geronimoo's Dominion Simulator \n\n"
+ " Version:\n 2.2.0\n" + " Written by:\n Jeroen Aga\n"
+ " Released:\n january 2019\n\n"
+ " Website:\n http://dominionsimulator.wordpress.com\n"
+ " Report bugs/Sing Praise:\n [email protected]\n" );
theAboutPanel.add( a, theCons );
theAboutPanel.setPreferredSize(new Dimension(250,260));
return theAboutPanel;
}
private static void logAndScrollToBottom(final JTextArea textArea, final String mesg) {
if(! SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
logAndScrollToBottom(textArea, mesg);
}
});
return;
}
textArea.append(textArea.getText().length() == 0 ? mesg : "\n" + mesg);
String text = textArea.getText();
if(text.length() > 2) {
int lastLinePos = text.lastIndexOf("\n", text.length() - 2);
if(lastLinePos > 0) {
textArea.setCaretPosition(lastLinePos + 1);
}
}
}
/**
* Constructor.
*
* @param xml XML data to be displayed
*/
public JXMLViewer(final InputStream xml) {
this.tabbedPane = new JTabbedPane();
if (xml instanceof PosDataInputStream) {
byte[] buf = ((PosDataInputStream) xml).getBuf();
StringBuilder sb = new StringBuilder(buf.length + 1);
for (byte b : buf) {
sb.append((char) b);
}
JTextArea textPlainText = new JTextArea(sb.toString());
textPlainText.setLineWrap(true);
textPlainText.setEditable(false);
tabbedPane.addTab("XML Plain Text", new JScrollPane(textPlainText));
}
this.setLayout(new BorderLayout());
this.add(this.tabbedPane, BorderLayout.CENTER);
}
/**
* Create the frame.
*/
public License() {
setTitle("License");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 300);
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(5, 5, 434, 265);
contentPane.add(scrollPane);
JTextArea txtrTheMitLicense = new JTextArea();
scrollPane.setViewportView(txtrTheMitLicense);
txtrTheMitLicense.setLineWrap(true);
txtrTheMitLicense.setEditable(false);
txtrTheMitLicense.setWrapStyleWord(true);
txtrTheMitLicense.setText("The MIT License (MIT)\n\nCopyright (c) 2015 Tinotenda Chemvura\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.");
}
@Test
public void testNestedQuotesRetainedAfterRoundTripSerialization() {
RunConfigurationFlagsState state = new RunConfigurationFlagsState("tag", "field");
RunConfigurationStateEditor editor = state.getEditor(null);
JTextArea textArea = getTextField(editor);
String originalText = "--where_clause=\"op = 'addshardreplica' AND purpose = 'rebalancing'\"";
textArea.setText(originalText);
editor.applyEditorTo(state);
assertThat(state.getRawFlags()).containsExactly(originalText);
editor.resetEditorFrom(state);
assertThat(textArea.getText()).isEqualTo(originalText);
// test flags generated for commands
assertThat(state.getFlagsForExternalProcesses())
.containsExactly("--where_clause=op = 'addshardreplica' AND purpose = 'rebalancing'");
}
void testTextComponent() {
System.out.println("testTextComponent:");
JTextArea area1 = new JTextArea();
injectComponent(p1, area1, false);
area1.setText(shaped);
JTextArea area2 = new JTextArea();
injectComponent(p2, area2, true);
area2.setText(text);
window.repaint();
printq = new JComponent[] { area1, area2 };
SwingUtilities.invokeLater(printComponents);
SwingUtilities.invokeLater(compareRasters);
}
/**
*
* @param id - component id.
* @param attrID - attribute id.
* @param lines - number of lines.
* @param columns - number of columns.
* @param attr - MarivnAttributes Object.
*/
public void addTextArea(String id, String attrID, int lines, int columns, MarvinAttributes attr)
{
JComponent comp = new JTextArea(lines, columns);
JScrollPane scrollPanel = new JScrollPane(comp);
((JTextArea)(comp)).setText(attr.get(attrID).toString());
// plug manually
panelCurrent.add(scrollPanel);
//box.add(l_scrollPane);
hashComponents.put(id, new MarvinPluginWindowComponent(id, attrID, attr, comp, ComponentType.COMPONENT_TEXTAREA));
//plugComponent(id, l_scrollPane, attrID, a_attributes, ComponentType.COMPONENT_TEXTAREA);
}
/**
* Instantiates a new about dialog.
*
* @param aParentFrame the a parent frame
* @param aDialogTitle the a dialog title
*/
public AboutDialog(JFrame aParentFrame, String aDialogTitle) {
super(aParentFrame, aDialogTitle);
getContentPane().setLayout(new BorderLayout());
JButton closeButton = new JButton("OK");
JLabel imageLabel = new JLabel(Images.getImageIcon(Images.UIMA_LOGO_BIG));
JPanel imagePanel = new JPanel();
imagePanel.setBackground(Color.WHITE);
imagePanel.add(imageLabel);
getContentPane().add(imagePanel, BorderLayout.WEST);
String aboutText = ABOUT_TEXT.replaceAll("\\$\\{version\\}", UIMAFramework.getVersionString());
JTextArea textArea = new JTextArea(aboutText);
textArea.setEditable(false);
getContentPane().add(textArea, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.add(closeButton);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
this.pack();
this.setResizable(false);
this.setModal(true);
// event for the closeButton button
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
AboutDialog.this.setVisible(false);
}
});
}
public PropertySheetPage() {
setLayout(LookAndFeelTweaks.createVerticalPercentLayout());
JTextArea message = new JTextArea();
message.setText(PropertySheetMain.RESOURCE.getString("Main.sheet1.message"));
LookAndFeelTweaks.makeMultilineLabel(message);
add(message);
final Bean data = new Bean();
data.setName("John Smith");
data.setText("Any text here");
data.setColor(Color.green);
data.setPath(new File("."));
data.setVisible(true);
data.setTime(System.currentTimeMillis());
DefaultBeanInfoResolver resolver = new DefaultBeanInfoResolver();
BeanInfo beanInfo = resolver.getBeanInfo(data);
PropertySheetPanel sheet = new PropertySheetPanel();
sheet.setMode(PropertySheet.VIEW_AS_CATEGORIES);
sheet.setProperties(beanInfo.getPropertyDescriptors());
sheet.readFromObject(data);
sheet.setDescriptionVisible(true);
sheet.setSortingCategories(true);
sheet.setSortingProperties(true);
add(sheet, "*");
// everytime a property change, update the button with it
PropertyChangeListener listener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
Property prop = (Property)evt.getSource();
prop.writeToObject(data);
System.out.println("Updated object to " + data);
}
};
sheet.addPropertySheetChangeListener(listener);
}
/**
* Maps {@code JTextArea.insert(String, int)} through queue
*/
public void insert(final String string, final int i) {
runMapping(new MapVoidAction("insert") {
@Override
public void map() {
((JTextArea) getSource()).insert(string, i);
}
});
}
private static JPanel createTestPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JTextArea textArea = new JTextArea(20, 20);
textArea.setText(getLongString());
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane);
return panel;
}
public ReloadLogAction(JTextArea textArea, LogPanel logPanel) {
this.logPanel = logPanel;
this.textArea = textArea;
putValue(Action.NAME, I18NSupport.getString("reload.log"));
putValue(Action.SMALL_ICON, ImageUtil.getImageIcon("reload_log"));
// putValue(Action.MNEMONIC_KEY, new Integer('R'));
// putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_R,
// KeyEvent.CTRL_DOWN_MASK));
putValue(Action.SHORT_DESCRIPTION, I18NSupport.getString("reload.log"));
putValue(Action.LONG_DESCRIPTION, I18NSupport.getString("reload.log"));
}
public MetalworksDocumentFrame() {
super("", true, true, true, true);
openFrameCount++;
setTitle("Untitled Message " + openFrameCount);
JPanel top = new JPanel();
top.setBorder(new EmptyBorder(10, 10, 10, 10));
top.setLayout(new BorderLayout());
top.add(buildAddressPanel(), BorderLayout.NORTH);
JTextArea content = new JTextArea(15, 30);
content.setBorder(new EmptyBorder(0, 5, 0, 5));
content.setLineWrap(true);
JScrollPane textScroller = new JScrollPane(content,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
top.add(textScroller, BorderLayout.CENTER);
setContentPane(top);
pack();
setLocation(offset * openFrameCount, offset * openFrameCount);
}
private JTextArea createTextArea() {
JTextArea textArea = new JTextArea();
textArea.setFont(RegexDialog.monoFont);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setEditable(false);
return textArea;
}
void testTextComponent() {
System.out.println("testTextComponent:");
JTextArea area1 = new JTextArea();
injectComponent(p1, area1, false);
area1.setText(shaped);
JTextArea area2 = new JTextArea();
injectComponent(p2, area2, true);
area2.setText(text);
window.repaint();
printq = new JComponent[] { area1, area2 };
SwingUtilities.invokeLater(printComponents);
SwingUtilities.invokeLater(compareRasters);
}
/**
* Method creates header panel with given title and description
*
* @param title header title
* @param text header description
*/
private void create(String title, String text) {
setLayout(new FlowLayout());
Icon icon = IconManager.SESSION_INVITATION_ICON;
textMain = new JTextArea();
textMain.setEditable(false);
textTitle = new JLabel();
String textConvertedToJLabelHTML = convertTextToJLabelHTML(title);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
titlePanel.setBackground(backColor);
textTitle.setText(textConvertedToJLabelHTML);
titlePanel.add(textTitle);
textMain.setText(text);
textMain.setSize(500, 100);
textMain.setWrapStyleWord(true);
textMain.setLineWrap(true);
JPanel textPanel = new JPanel();
textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
textPanel.add(titlePanel);
textPanel.add(textMain);
textPanel.setBackground(backColor);
add(textPanel);
JLabel lblIcon = new JLabel();
lblIcon.setIcon(icon);
add(lblIcon);
setBackground(backColor);
}
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JTextArea textArea = new JTextArea("Text area of the test.", 40, 40);
add(new JScrollPane(textArea));
}
});
}
/**
* O construtor recebe o JTextArea no qual será gerada a estrutura e a String
* que contém o nome da linguagem de programação.
*/
public GerarEstrutura(JTextArea area, String linguagem) {
this.area = area;
this.linguagem = linguagem;
gerar();
}
VectorContentViewer(String stringData, OnTextWatcher textWatcher) {
this.mTextWatcher = textWatcher;
setLayout(new GridLayout(1, 1));
mTextArea = new JTextArea();
mTextArea.setText(stringData);
mTextArea.getDocument().addDocumentListener(this);
mTextArea.setMinimumSize(new Dimension(200, 200));
add(mTextArea);
}
private JComponent getTitleComponent (String msg) {
JTextArea area = new JTextArea (msg);
area.setWrapStyleWord (true);
area.setLineWrap (true);
area.setEditable (false);
area.setOpaque (false);
area.setBorder(BorderFactory.createEmptyBorder());
area.setBackground(new Color(0, 0, 0, 0));
area.putClientProperty(JTextPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
return area;
}
void testTextComponent() {
System.out.println("testTextComponent:");
JTextArea area1 = new JTextArea();
injectComponent(p1, area1, false);
area1.setText(shaped);
JTextArea area2 = new JTextArea();
injectComponent(p2, area2, true);
area2.setText(text);
window.repaint();
printq = new JComponent[] { area1, area2 };
SwingUtilities.invokeLater(printComponents);
SwingUtilities.invokeLater(compareRasters);
}