Java graphics2d:文本字段 [英] Java graphics2d: text field
本文介绍了Java graphics2d:文本字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我搜索了很多主题,但没有找到具体答案.我需要在 Graphics2D
上输入字段数据(例如 JTextField
或 TextField
).
I searched for many topics but did not find any with a concrete answer. I need a field data input on the Graphics2D
(like the JTextField
or TextField
).
有人知道我如何创建此组件吗?还是将文本字段( Component
)放在 Graphics2D
中?
Does anyone know how I can create this component? Or put a text field (Component
) in Graphics2D
?
谢谢!
推荐答案
不是很确定您要的内容,但是这里有一些代码,当您双击时会在面板上添加文本字段.然后,您可以在文本字段中添加文本.
Not really sure what you are asking for, but here is some code that will add a text field to a panel when you double click. You can then add text to the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class InvisibleTextField extends JTextField
implements ActionListener, FocusListener, MouseListener, DocumentListener
{
public InvisibleTextField()
{
setOpaque( false );
setColumns( 1 );
setBorder( null );
setSize( getPreferredSize() );
setColumns( 0 );
addActionListener( this );
addFocusListener( this );
addMouseListener( this );
getDocument().addDocumentListener( this );
}
// Implement ActionListener
public void actionPerformed(ActionEvent e)
{
setEditable( false );
}
// Implement FocusListener
public void focusLost(FocusEvent e)
{
setEditable( false );
}
public void focusGained(FocusEvent e) {}
// Implement MouseListener
public void mouseClicked( MouseEvent e )
{
if (e.getClickCount() == 2)
setEditable( true );
}
public void mouseEntered( MouseEvent e ) {}
public void mouseExited( MouseEvent e ) {}
public void mousePressed( MouseEvent e ) {}
public void mouseReleased( MouseEvent e ) {}
// Implement DocumentListener
public void insertUpdate(DocumentEvent e)
{
updateSize();
}
public void removeUpdate(DocumentEvent e)
{
updateSize();
}
public void changedUpdate(DocumentEvent e) {}
private void updateSize()
{
setSize( getPreferredSize() );
}
public static void main(String[] args)
{
JPanel panel = new JPanel();
panel.setFocusable( true );
panel.setLayout( null );
panel.addMouseListener( new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
JPanel panel = (JPanel)e.getSource();
if (e.getClickCount() == 1)
{
panel.requestFocusInWindow();
}
if (e.getClickCount() == 2)
{
InvisibleTextField tf = new InvisibleTextField();
tf.setText("Enter Text");
tf.setLocation(e.getPoint());
panel.add( tf );
tf.requestFocusInWindow();
tf.selectAll();
}
}
});
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.add(new JLabel("Double Click to Add Text"), BorderLayout.NORTH);
frame.add(panel);
frame.setSize(650, 300);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
这篇关于Java graphics2d:文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文