我有一个自定义的 swing 组件,它有一些子元素,包括 JTextField。我想为容器提供与 JTextField 相同的基线,因此我重写了容器中的 getBaseline 方法。但是,当为容器调用 getBaseline 时,并不总是设置 JTextField 的位置。我试图在容器的 getBaseline 方法中添加对 doLayout 的调用,但这没有帮助。我想要的是以下内容:
public int getBaseline(int w, int h) {
Dimension size = textField.getPreferredSize();
int textBaseline = textField.getBaseline(size.width, size.height);
int textY = textField.getY();
return textY + textBaseline;
}
在上面的代码中 textY 等于 0。
我写了一些代码来说明这个问题。第一次单击“添加”时,基线是错误的。第二次是正确的。
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class CustomComponent extends JPanel {
public CustomComponent() {
setLayout(new GridBagLayout());
textField.setColumns(8);
layoutElements();
}
public void addComponent() {
JPanel comp = new JPanel();
comp.setPreferredSize(new Dimension(50, 200));
comp.setBackground(Color.red);
otherComponents.add(comp);
layoutElements();
}
public int getBaseline(int w, int h) {
Dimension size = textField.getPreferredSize();
return textField.getY() + textField.getBaseline(size.width, size.height);
}
public Component.BaselineResizeBehavior getBaselineResizeBehavior() {
return Component.BaselineResizeBehavior.CONSTANT_DESCENT;
}
private void layoutElements() {
removeAll();
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.SOUTH;
add(textField, constraints);
for (JPanel comp : otherComponents)
add(comp, new GridBagConstraints());
if (getParent() != null)
getParent().validate();
}
private JTextField textField = new JTextField();
private ArrayList<JPanel> otherComponents = new ArrayList<JPanel>();
}
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
frame.getContentPane().add(panel);
JButton addComponent = new JButton("Add");
GridBagConstraints constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.BASELINE;
panel.add(addComponent, constraints);
final CustomComponent customComp = new CustomComponent();
panel.add(customComp, constraints);
addComponent.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
customComp.addComponent();
}
});
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}