【发布时间】:2015-07-30 07:26:25
【问题描述】:
当我创建一堆JTextFields 时,我看到第一个被选中。我想取消选择它,因为我有焦点侦听器并且它会自动运行。
有什么线索吗?
SSCCE:
JTextField tf = new JTextField("hello");
tf.setForeground(Color.decode("0x8C8C8C")); // for nice comment inside the text field
textFieldKwotaWplacona.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e)
{
if(tf.getForeground() != Color.BLACK)
{
tf.setText("");
tf.setForeground(Color.BLACK);
}
} @Override
public void focusLost(FocusEvent arg0) {}});
//for deleting "nice comment" after click
tf.setBounds(//some bounds);
add(tf);
对另一个文本字段重复该过程
编辑2: 实际代码(我相信它的 sscce :P)
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Main extends JFrame implements ActionListener
{
JTextField textFieldKwotaWplacona, textFieldOprocentowanie, textFieldDlugoscLokaty, textFieldKwotaOtrzymana;
Main()
{ setSize(500,300);
setLayout(null);
setTitle("Program do liczenia procentu składanego");
setDefaultCloseOperation(EXIT_ON_CLOSE);
textFieldKwotaWplacona = new JTextField("Ilość pieniędzy wpłaconych");
textFieldKwotaWplacona.setForeground(Color.decode("0x8C8C8C"));
textFieldKwotaWplacona.addActionListener(this);
textFieldKwotaWplacona.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e)
{
if(textFieldKwotaWplacona.getForeground() != Color.BLACK)
{
textFieldKwotaWplacona.setText("");
textFieldKwotaWplacona.setForeground(Color.BLACK);
}
} @Override
public void focusLost(FocusEvent arg0) {}});
textFieldKwotaWplacona.setBounds(10, 10, 100, 20);
add(textFieldKwotaWplacona);
textFieldOprocentowanie = new JTextField("Oprocentowanie");
textFieldOprocentowanie.setForeground(Color.decode("0x8C8C8C"));
textFieldOprocentowanie.addActionListener(this);
textFieldOprocentowanie.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e)
{
if(textFieldOprocentowanie.getForeground() != Color.BLACK)
{
textFieldOprocentowanie.setText("");
textFieldOprocentowanie.setForeground(Color.BLACK);
}
}
@Override
public void focusLost(FocusEvent arg0) {}});
textFieldOprocentowanie.setBounds(10, 40, 100, 20);
add(textFieldOprocentowanie);
}
@Override
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
}
public static void main(String[] args)
{
Main a=new Main();
a.setVisible(true);
}
}
我想将焦点设置到窗口或其他地方,以防止文本消失。
【问题讨论】:
-
want to deselect it, because I have focus listener and it's running automatically.- 我不知道那是什么意思。发布您的SSCCE 来证明问题。 -
某些东西必须具有焦点,只需将其分配给其他组件即可。由于您没有发布 SSCCE 或 MCVE,因此我无法为您提供更多“线索”。
-
那不是 SSCCE。我们如何编译和执行那段代码???
-
不,抱歉,我将粘贴我的实际代码
-
这是一个 MCVE / SSCCE(尽管
ActionListener部分不是必需的,并且您有一些未使用的字段),很好。我假设您将有一个按钮或其他一些组件,除了文本字段之外,它们可以成为焦点。对吗?
标签: java focus jtextfield