Java 如果组件是 jlabel,则获取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21412116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get text if component is jlabel
提问by geo
I have a LayeredPane2 with mant components such as jlabels, jbutton etc. I want to loop in the components and if the component is a Jlabel, get it's text. How can I do this? Here is my code so far:
我有一个带有 jlabels、jbutton 等 mant 组件的 LayeredPane2。我想在组件中循环,如果组件是 Jlabel,则获取它的文本。我怎样才能做到这一点?到目前为止,这是我的代码:
//search the components
for (int j=0; j<jLayeredPane2.getComponents().length; j++){
//if it is a jlabel
if ("class javax.swing.JLabel".equals(jLayeredPane2.getComponent(j).getClass().toString())){
//HOW DO I GET THE LABEL TEXT??
}
}
采纳答案by Michael Berry
You want the instanceof
keyword, then a cast:
您需要instanceof
关键字,然后是演员表:
if(jLayeredPane2.getComponent(j) instanceof JLabel) {
JLabel label = (JLabel)jLayeredPane2.getComponent(j);
String text = label.getText();
//...Then do whatever you want to do with said text.
}
回答by Bruno Toffolo
According to the JLabel docs, you can use the getText()
method to retrieve the label text.
根据JLabel docs,您可以使用该getText()
方法来检索标签文本。
String labelText = ((JLabel) jLayeredPane2.getComponent(j)).getText();
To check if the component is a JLabel you can use the comparison
要检查组件是否是 JLabel,您可以使用比较
if (jLayeredPane2.getComponent(j) instanceof JLabel) { }
as was already suggested in this question.
正如在这个问题中已经提出的那样。
Your final code would be something like this:
您的最终代码将是这样的:
if (jLayeredPane2.getComponent(j) instanceof JLabel) {
Label label = (JLabel) jLayeredPane2.getComponent(j);
String labelText = label.getText();
}