我需要更改 Jcomponents 内的文本,这些文本排列在 JPanel 上的坐标 x 和 y 处。 但是,如果我更改除 TextFields 或 PasswordFields 之外的所有位置的文本,元素的位置和尺寸就会滑动。
监听器,改变元素的参数
private TextListener textListener = new TextListener() {
@Override
public void textValueChanged(TextEvent e) {
if (comp.getClass() == JButton.class) {
((JButton)comp).setText(ttext.getText());
}else{
if(comp.getClass() == JTextField.class){
((JTextField)comp).setText(ttext.getText());
}else{
if(comp.getClass() == JPasswordField.class){
((JPasswordField)comp).setText(ttext.getText());
}else{
if(comp.getClass() == JTextArea.class){
((JTextArea)comp).setText(ttext.getText());
}else{
if(comp.getClass() == JCheckBox.class){
((JCheckBox)comp).setText(ttext.getText());
}else{
((JRadioButton)comp).setText(ttext.getText());
}
}
}
}
}
try{
comp.setBounds(tx,ty,Integer.valueOf(twidth.getText()),Integer.valueOf(theight.getText()));
}catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null,"Error","Error",JOptionPane.ERROR_MESSAGE);
}
comp.repaint();
}
};
我能做什么?谢谢!
最佳答案
- 为了获得更好的帮助,请尽快发布 SSCCE ,短,可运行,可编译
<小时/>which are arranged at the coordinates x and y on JPanel
Component[] Components = myPanel.getComponents();
然后在
components
数组内循环if (components[i] instanceof JLabel) { JLabel myLabel = (JLabel) components[i]; myLabel.whatever } else if (components[i] instanceof JButton) { JButton myButton = (JButton) components[i]; myButton.whatever } and so on....,
这种形式的这个/这些临时变量仅在循环内部有效,但提供真正的
JComponent
,并且它们确实发生了变化您可能会迷失在
JFrame
中,并且某些Compound JComponent
不会返回真正的JComponents
(JPanel
、JButton
、JTextField
),返回在BasicXxxUI
中实现的Objects
,但可以用替换>JComponents
,或者可以使用为JComponents
实现的方法,例如可编辑的JComboBox
可以返回JTextField
或JFormattedTextField
作为编辑器组件
- 将
JComponents
放置在JPanel
中并不是一个好主意,您需要在所有情况下都知道什么、如何、在哪里、有多少......
关于java - 更改 JComponent 上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16721147/