2 回答

TA貢獻1806條經驗 獲得超8個贊
很簡單:使用一個 FocusListener,一個添加到每個 JTextField。例如,如果您有這樣的 JTextFields:
private JTextField[][] fields = new JTextField[ROW_COUNT][ROW_COUNT];
假設你有一個像這樣的 FocusListener:
private class MyFocus implements FocusListener {
@Override
public void focusLost(FocusEvent e) {
// get JTextField that lost focus
JTextField textField = (JTextField) e.getSource();
// set color back to white
textField.setBackground(INACTIVE_COLOR);
}
@Override
public void focusGained(FocusEvent e) {
// get JTextField that is gaining focus
JTextField textField = (JTextField) e.getSource();
// set color to the active background
textField.setBackground(ACTIVE_COLOR);
}
}
您可以創建和添加您的偵聽器
FocusListener focusListener = new MyFocus();
setLayout(new GridLayout(ROW_COUNT, ROW_COUNT, 1, 1));
for (int row = 0; row < fields.length; row++) {
for (int col = 0; col < fields[row].length; col++) {
JTextField field = new JTextField(COLS);
field.addFocusListener(focusListener);
add(field);
}
}
整個可測試的東西:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class FocusExample extends JPanel {
private static final int ROW_COUNT = 20;
private static final int COLS = 5;
protected static final Color ACTIVE_COLOR = Color.PINK;
protected static final Color INACTIVE_COLOR = Color.WHITE;
private JTextField[][] fields = new JTextField[ROW_COUNT][ROW_COUNT];
public FocusExample() {
FocusListener focusListener = new MyFocus();
setLayout(new GridLayout(ROW_COUNT, ROW_COUNT, 1, 1));
for (int row = 0; row < fields.length; row++) {
for (int col = 0; col < fields[row].length; col++) {
JTextField field = new JTextField(COLS);
field.addFocusListener(focusListener);
add(field);
}
}
}
private class MyFocus implements FocusListener {
@Override
public void focusLost(FocusEvent e) {
// get JTextField that lost focus
JTextField textField = (JTextField) e.getSource();
// set color back to white
textField.setBackground(INACTIVE_COLOR);
}
@Override
public void focusGained(FocusEvent e) {
// get JTextField that is gaining focus
JTextField textField = (JTextField) e.getSource();
// set color to the active background
textField.setBackground(ACTIVE_COLOR);
}
}
private static void createAndShowGui() {
FocusExample mainPanel = new FocusExample();
JFrame frame = new JFrame("FocusExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

TA貢獻1757條經驗 獲得超7個贊
你不需要面板。只需這樣做:
聲明這個鼠標適配器:
MouseAdapter ma = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JTextField tf = (JTextField) e.getSource();
tf.setBackground(Color.BLACK);
}
};
在創建文本字段的循環內執行此操作:
textField.addMouseListener(ma);
MouseEvent 知道單擊了哪個 JTextField,因此您可以訪問它并更改它的顏色。將此鼠標偵聽器添加到每個文本字段,這應該可以工作。
添加回答
舉報