gpt4 book ai didi

java - 如何获取 JTextField 的真实 x 和 y 坐标

转载 作者:行者123 更新时间:2023-12-01 17:23:39 24 4
gpt4 key购买 nike

我在编写一段代码时遇到了问题,在该代码中我将 JPanel 添加到其他代码中以形成布局。问题是,在显示窗口后,我需要获取其中一个文本字段的 x 和 y 坐标,但每当我尝试使用 getX() 和 getY() 时> 他们不断返回 0 的方法。我已经验证了 getX()getY() 方法在窗口初始化和显示后被调用。我该如何解决这个问题并获取文本字段的实际坐标。

这是窗口代码:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;


public class GraphicsPanel extends JFrame implements ActionListener, CaretListener{

JPanel buttonPanel = new JPanel();
JPanel mainPanel = new JPanel();
JPanel animationPanel = new JPanel();
JPanel bottomPanel = new JPanel();
JPanel text = new JPanel();

PokemonLearnsets info = new PokemonLearnsets();

HealthBar healthBar1 = new HealthBar();
HealthBar healthBar2 = new HealthBar();

JTextArea textArea = new JTextArea();
JTextField response = new JTextField();

int health1 = 100;
int total1 = 100;
int health2 = 100;
int total2 = 100;
int startOfRect = 1;
int p1MonNum = -1;
int waitTime = 20;
int p2MonNum = -1;

TextInterface theText;

Icon allIcons[][];
JLabel p1Gif;
JLabel p2Gif;

JPanel mainBuilderPanel = new JPanel();
JPanel builderPanel = new JPanel();
JPanel builderMessagePanel = new JPanel();

JPanel monPanels [] = new JPanel[6];
JPanel imagePanels[] = new JPanel[6];
JPanel namePanels[] = new JPanel[6];
JPanel movePanels[] = new JPanel[6];

JPanel allMoves[][] = new JPanel[6][4];

JTextField names[] = new JTextField[6];

JTextField moves[][] = new JTextField[6][4];

JButton validate = new JButton("Validate");

JLabel tempImages[] = new JLabel[6];
JLabel emptyLabels[] = new JLabel[6];

AutoSuggestor [] nameSuggestions = new AutoSuggestor[6];

AutoSuggestor [][] moveSuggestions = new AutoSuggestor[6][4];


public GraphicsPanel(String name){

super(name);

setupTeamBuilderPanel();

// setupBattlePanel();
}

private void setupTeamBuilderPanel() {

Container c = getContentPane();

mainBuilderPanel.setLayout(new BorderLayout());
mainBuilderPanel.setBorder(new LineBorder(Color.BLACK, 2));
builderPanel.setLayout(new GridLayout(1, 0));
builderPanel.setBorder(new LineBorder(Color.BLACK, 1));
builderMessagePanel.setBorder(new LineBorder(Color.BLACK, 2));

for (int i = 0; i < monPanels.length; i ++) {

monPanels[i] = new JPanel();
imagePanels[i] = new JPanel();
namePanels[i] = new JPanel();
movePanels[i] = new JPanel();

names[i] = new JTextField();

names[i].addCaretListener(this);

emptyLabels[i] = new JLabel();
tempImages[i] = emptyLabels[i];

monPanels[i].setBorder(new LineBorder(Color.BLACK, 3));
imagePanels[i].setBorder(new LineBorder(Color.BLACK, 3));
movePanels[i].setBorder(new LineBorder(Color.BLACK, 3));

monPanels[i].setLayout(new GridLayout(0 ,1));
namePanels[i].setLayout(new GridLayout(1, 0));
movePanels[i].setLayout(new GridLayout(0, 1));
imagePanels[i].setLayout(new BorderLayout());

namePanels[i].add(new JLabel(" Name:"));
namePanels[i].add(names[i]);
imagePanels[i].add(tempImages[i]);
imagePanels[i].add(namePanels[i], BorderLayout.SOUTH);
monPanels[i].add(imagePanels[i]);

for (int k = 0; k < moves[i].length; k ++) {

moves[i][k] = new JTextField();

allMoves[i][k] = new JPanel();

allMoves[i][k].setLayout(new GridLayout(0, 1));

allMoves[i][k].add(new JLabel(" Move " + Integer.toString(k + 1) + ":"));
allMoves[i][k].add(moves[i][k]);
allMoves[i][k].add(new JLabel());
allMoves[i][k].add(new JLabel());

movePanels[i].add(allMoves[i][k]);

}

monPanels[i].add(movePanels[i]);

builderPanel.add(monPanels[i]);

}

String welcomeMessage = "";

for (int i = 0; i < 5; i ++) {

welcomeMessage += " ";

}

welcomeMessage += "Welcome to the Teambuilder!";

setupSuggestions();

validate.addActionListener(this);

builderMessagePanel.add(new JLabel(welcomeMessage));
mainBuilderPanel.add(builderMessagePanel, BorderLayout.NORTH);
mainBuilderPanel.add(validate, BorderLayout.SOUTH);
mainBuilderPanel.add(builderPanel);

c.add(mainBuilderPanel);
}

private void setupBattlePanel() {

Container c = getContentPane();

mainPanel.setLayout(new GridLayout());
bottomPanel.setLayout(new GridLayout());

animationPanel.setBorder(new LineBorder(Color.BLACK, 3));
animationPanel.setLayout(new GridLayout(0, 2));

mainPanel.add(animationPanel);

buttonPanel.setBorder(new LineBorder(Color.BLACK, 3));
buttonPanel.setLayout(new FlowLayout(5));
buttonPanel.setBackground(Color.GREEN);
// buttonPanel.add(new JLabel(" "));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));
// buttonPanel.add(new JButton("Testing"));

bottomPanel.add(buttonPanel);

text.setLayout(new GridLayout());
text.setBorder(new LineBorder(Color.BLACK, 3));
text.add(response);

bottomPanel.add(text);


textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);

textArea.setEditable(false);
textArea.setBackground(Color.LIGHT_GRAY);
JScrollPane textAreaPane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

textAreaPane.setBorder(new LineBorder(Color.BLACK, 3));

mainPanel.add(textAreaPane);

c.add(mainPanel, BorderLayout.CENTER);

c.add(bottomPanel, BorderLayout.SOUTH);

}

private void setupSuggestions() {

ArrayList<String> allPossibleMoves = new ArrayList<String>();

Collections.addAll(allPossibleMoves, info.getAllMoves());

for (int i = 0; i < 6; i ++) {

for (int k = 0; k < 4; k ++) {

moveSuggestions[i][k] = new AutoSuggestor(moves[i][k], allPossibleMoves, Color.WHITE.brighter(), Color.BLACK, Color.BLACK, 0.75f);
moveSuggestions[i][k].setTextField(moves[i][k]);

}

}

}

public void writeToScreen(String writing) {
String current = textArea.getText();
textArea.setText(current + writing);
}

public void updateAll() {

mainPanel.updateUI();
bottomPanel.updateUI();
mainBuilderPanel.updateUI();

}

public void setTextInterface(TextInterface text) {
theText = text;
response.addActionListener(theText.action);
}

public void drawMons(String name1, String name2) {

animationPanel.removeAll();

ImageIcon secImage = new ImageIcon(this.getClass().getResource("SpritesFront/" + name2 + ".gif"));
secImage = new ImageIcon(secImage.getImage().getScaledInstance((int)(secImage.getIconWidth() * 1.5), (int)(secImage.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon = secImage;
p2Gif = new JLabel(icon);

ImageIcon firstImage = new ImageIcon(this.getClass().getResource("SpritesBack/" + name1 + "-back.gif"));
firstImage = new ImageIcon(firstImage.getImage().getScaledInstance((int)(firstImage.getIconWidth() * 1.5), (int)(firstImage.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon2 = firstImage;
p1Gif = new JLabel(icon2);

animationPanel.add(healthBar2);
animationPanel.add(p2Gif);
animationPanel.add(p1Gif);
animationPanel.add(healthBar1);

updateAll();
}

public void fillPortions(int x) {
JLabel [] labels = new JLabel[x];
for (int i = 0; i < x; i ++) {
labels[i] = new JLabel();
animationPanel.add(labels[i]);
}
}

public void refreshHealthBar(int health, int total, int pNum, int mon) {

if (pNum == 1) {
if (p1MonNum != mon && p1MonNum != -1) {
p1MonNum = mon;

health1 = health;
total1 = total;

healthBar1.setHealth(health);
healthBar1.setTotal(total);

redoHealthPanel();
}
else {
p1MonNum = mon;
healthBar1.setTotal(total);;
while (health < health1) {

healthBar1.setHealth(health1);

redoHealthPanel();

health1--;
}

while (health > health1) {

healthBar1.setHealth(health1);

redoHealthPanel();

health1++;
}
}
}
else {
if (p2MonNum != mon && p2MonNum != -1) {
p2MonNum = mon;

health2 = health;
total2 = total;

healthBar2.setHealth(health);
healthBar2.setTotal(total);

redoHealthPanel();

updateAll();
}
else {
p2MonNum = mon;
healthBar2.setTotal(total);
while (health < health2) {

healthBar2.setHealth(health2);

redoHealthPanel();

health2--;
}

while (health > health2) {

healthBar2.setHealth(health2);

redoHealthPanel();

health2++;
}
}
}

}

private void redoHealthPanel () {
animationPanel.removeAll();

animationPanel.add(healthBar2);
animationPanel.add(p2Gif);
animationPanel.add(p1Gif);
animationPanel.add(healthBar1);

updateAll();

try {
TimeUnit.MILLISECONDS.sleep(waitTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private String validatePokemon() {

String answer = "";

String tempMonNames [] = new String[6];

boolean invalidMove = false;

for (int i = 0; i < monPanels.length; i ++) {

String currentName = names[i].getText();

if (currentName.isEmpty()) {

answer = "You must have 6 Pokemon on your team but you can have less than 4 moves";
return answer;

}

for (String element : tempMonNames) {

if (element == null) {

continue;

} else if (currentName.equals(element)) {

answer = "You have duplicate Pokemon on your team";

return answer;

}
}

if (!info.validPokemon(currentName)) {

answer += "Pokemon #" + (i + 1) + " is invalid\n";

} else {

tempMonNames[i] = currentName;

}

int count = 0;

for (int k = 0; k < moves[i].length; k++) {

if (moves[i][k].getText().isEmpty()) {

count++;

}

if (!info.validMove(moves[i][k].getText().replace(" ", "").toLowerCase(), currentName)) {

answer += "Pokemon #" + (i + 1) + ", move #" + (k + 1) + " is invalid\n";
invalidMove = true;

}

if (count >= 4) {

answer += "Pokemon #" + (i + 1) + " has no moves\n";
break;

}

}

}

if (invalidMove) {

answer += "***Please keep in mind only damaging moves without recoil are allowed, if there aren't enough for 4 moves, leave fields blank***";

}

return answer;

}

@Override
public void actionPerformed(ActionEvent e) {

if (validatePokemon().isEmpty()) {

JOptionPane.showMessageDialog(null, "Confirmed" , "", JOptionPane.INFORMATION_MESSAGE);

} else {

JOptionPane.showMessageDialog(null, validatePokemon() , "", JOptionPane.ERROR_MESSAGE);

}
}


@Override
public void caretUpdate(CaretEvent e) {

for (int i = 0; i < names.length; i ++) {

if (info.validPokemon(names[i].getText()) && tempImages[i].getParent() == null) {

ImageIcon temp = new ImageIcon(this.getClass().getResource("SpritesFront/" + names[i].getText().replace(" ", "").replace(":", "").replace("'", "").replace(".", "").replace("-", "").toLowerCase() + ".gif"));
temp = new ImageIcon(temp.getImage().getScaledInstance((int)(temp.getIconWidth() * 1.5), (int)(temp.getIconHeight() * 1.5), Image.SCALE_DEFAULT));
Icon icon = temp;

imagePanels[i].remove(tempImages[i]);

tempImages[i] = new JLabel(icon);

imagePanels[i].add(tempImages[i]);

updateAll();

} else if (!info.validPokemon(names[i].getText())){

imagePanels[i].remove(tempImages[i]);

updateAll();

}

}
}

}

这是为窗口设置的:

        GraphicsPanel window = new GraphicsPanel("Pokemon");
window.setBounds(0, 0, 1440, 830);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);

这是调用 getX()getY() 的地方:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

public class AutoSuggestor {

private final JTextComponent textComp;
private JPanel suggestionsPanel;
private JWindow autoSuggestionPopUpWindow;
private String typedWord;
private final ArrayList<String> dictionary = new ArrayList<>();
private JTextField textField;
private int currentIndexOfSpace, tW, tH;
private DocumentListener documentListener = new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}

@Override
public void removeUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}

@Override
public void changedUpdate(DocumentEvent de) {
checkForAndShowSuggestions();
}
};
private final Color suggestionsTextColor;
private final Color suggestionFocusedColor;

public AutoSuggestor(JTextComponent textComp, ArrayList<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {
this.textComp = textComp;
this.suggestionsTextColor = textColor;
this.suggestionFocusedColor = suggestionFocusedColor;
this.textComp.getDocument().addDocumentListener(documentListener);

setDictionary(words);

typedWord = "";
currentIndexOfSpace = 0;
tW = 0;
tH = 0;

autoSuggestionPopUpWindow = new JWindow();
autoSuggestionPopUpWindow.setOpacity(opacity);

suggestionsPanel = new JPanel();
suggestionsPanel.setLayout(new GridLayout(0, 1));
suggestionsPanel.setBackground(popUpBackground);

addKeyBindingToRequestFocusInPopUpWindow();
}

private void addKeyBindingToRequestFocusInPopUpWindow() {
textComp.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
textComp.getActionMap().put("Down released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
break;
}
}
}
});
suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
suggestionsPanel.getActionMap().put("Down released", new AbstractAction() {
int lastFocusableIndex = 0;

@Override
public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))

ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
int max = sls.size();

if (max > 1) {//more than 1 suggestion
for (int i = 0; i < max; i++) {
SuggestionLabel sl = sls.get(i);
if (sl.isFocused()) {
if (lastFocusableIndex == max - 1) {
lastFocusableIndex = 0;
sl.setFocused(false);
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it

} else {
sl.setFocused(false);
lastFocusableIndex = i;
}
} else if (lastFocusableIndex <= i) {
if (i < max) {
sl.setFocused(true);
autoSuggestionPopUpWindow.toFront();
autoSuggestionPopUpWindow.requestFocusInWindow();
suggestionsPanel.requestFocusInWindow();
suggestionsPanel.getComponent(i).requestFocusInWindow();
lastFocusableIndex = i;
break;
}
}
}
} else {//only a single suggestion was given
autoSuggestionPopUpWindow.setVisible(false);
setFocusToTextField();
checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
}
}
});
}

private void setFocusToTextField() {
textComp.requestFocusInWindow();
}

public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {
ArrayList<SuggestionLabel> sls = new ArrayList<>();
for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);
sls.add(sl);
}
}
return sls;
}

private void checkForAndShowSuggestions() {
typedWord = getCurrentlyTypedWord();

suggestionsPanel.removeAll();//remove previos words/jlabels that were added

//used to calcualte size of JWindow as new Jlabels are added
tW = 0;
tH = 0;

boolean added = wordTyped(typedWord);

if (!added) {
if (autoSuggestionPopUpWindow.isVisible()) {
autoSuggestionPopUpWindow.setVisible(false);
}
} else {
showPopUpWindow();
setFocusToTextField();
}
}

protected void addWordToSuggestions(String word) {
SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);

calculatePopUpWindowSize(suggestionLabel);

suggestionsPanel.add(suggestionLabel);
}

public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
String text = textComp.getText();
String wordBeingTyped = "";
text = text.replaceAll("(\\r|\\n)", " ");
if (text.contains(" ")) {
int tmp = text.lastIndexOf(" ");
if (tmp >= currentIndexOfSpace) {
currentIndexOfSpace = tmp;
wordBeingTyped = text.substring(text.lastIndexOf(" "));
}
} else {
wordBeingTyped = text;
}
return wordBeingTyped.trim();
}

private void calculatePopUpWindowSize(JLabel label) {
//so we can size the JWindow correctly
if (tW < label.getPreferredSize().width) {
tW = label.getPreferredSize().width;
}
tH += label.getPreferredSize().height;
}

public void setTextField(JTextField textField) {

this.textField = textField;

}

private void showPopUpWindow() {
autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.setSize(tW, tH);
autoSuggestionPopUpWindow.setVisible(true);

//show the pop up
autoSuggestionPopUpWindow.setLocation(textComp.getX(), textComp.getY() + textComp.getHeight());
autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textComp.getWidth(), 30));
autoSuggestionPopUpWindow.revalidate();
autoSuggestionPopUpWindow.repaint();

}

public void setDictionary(ArrayList<String> words) {
dictionary.clear();
if (words == null) {
return;//so we can call constructor with null value for dictionary without exception thrown
}
for (String word : words) {
dictionary.add(word);
}
}

public JWindow getAutoSuggestionPopUpWindow() {
return autoSuggestionPopUpWindow;
}

public JTextComponent getTextField() {
return textComp;
}

public void addToDictionary(String word) {
dictionary.add(word);
}

boolean wordTyped(String typedWord) {

if (typedWord.isEmpty()) {
return false;
}
//System.out.println("Typed word: " + typedWord);

boolean suggestionAdded = false;

for (String word : dictionary) {//get words in the dictionary which we added
boolean fullymatches = true;
for (int i = 0; i < typedWord.length(); i++) {//each string in the word
if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
fullymatches = false;
break;
}
}
if (fullymatches) {
addWordToSuggestions(word);
suggestionAdded = true;
}
}
return suggestionAdded;
}
}

class SuggestionLabel extends JLabel {

private boolean focused = false;
private final JWindow autoSuggestionsPopUpWindow;
private final JTextComponent textComponent;
private final AutoSuggestor autoSuggestor;
private Color suggestionsTextColor, suggestionBorderColor;

public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {
super(string);

this.suggestionsTextColor = suggestionsTextColor;
this.autoSuggestor = autoSuggestor;
this.textComponent = autoSuggestor.getTextField();
this.suggestionBorderColor = borderColor;
this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();

initComponent();
}

private void initComponent() {
setFocusable(true);
setForeground(suggestionsTextColor);

addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);

replaceWithSuggestedText();

autoSuggestionsPopUpWindow.setVisible(false);
}
});

getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");
getActionMap().put("Enter released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
replaceWithSuggestedText();
autoSuggestionsPopUpWindow.setVisible(false);
}
});
}

public void setFocused(boolean focused) {
if (focused) {
setBorder(new LineBorder(suggestionBorderColor));
} else {
setBorder(null);
}
repaint();
this.focused = focused;
}

public boolean isFocused() {
return focused;
}

private void replaceWithSuggestedText() {
String suggestedWord = getText();
String text = textComponent.getText();
String typedWord = autoSuggestor.getCurrentlyTypedWord();
String t = text.substring(0, text.lastIndexOf(typedWord));
String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);
textComponent.setText(tmp);
}
}

showPopUpWindow 方法中的 textComp.getX()textComp.getY() 是给出零的部分。

最佳答案

经过一段时间的思考,我想出了这个解决方案,它对我有用。

int x = 0;
int y = 0;

Component currentComponent = textComp;

while (currentComponent != null) {

x += currentComponent.getX();
y += currentComponent.getY();

currentComponent = currentComponent.getParent();

}

关于java - 如何获取 JTextField 的真实 x 和 y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61244181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com