我有一个 JFrame,其布局管理器为 GridLayout。当我按“New...”(JMenuItem)时,添加了背景为蓝色的新 ColorPanel 对象,但文本“test”未显示在 JPanel 内。正在添加 ColorPanel 对象并显示为蓝色,但是应该在里面的白色文字没有显示出来。我尝试在 drawString(... ,x,y); 中添加 getX()+20,getY()+20;它的行为很奇怪,没有出现在正确的位置,或者根本没有出现。如何使文本出现在已通过 GridLayout 添加到框架的 JPanel 内。
public class MainFrame{
protected JFrame frame;
private JPanel containerPanel;
private GridLayout gl = new GridLayout(3,1);
public MainFrame(){
frame = new JFrame("Test");
containerPanel = new JPanel();
gl.setHgap(3);gl.setVgap(3);
frame.setLayout(gl);
frame.setSize(500, 500);
frame.setJMenuBar(getMenuBar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public JMenuBar getMenuBar(){
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem newItem = new JMenuItem("New...");
newItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.add(new ColorPanel());
frame.getContentPane().revalidate();
}
});
file.add(newItem);
menu.add(file);
return menu;
}
private class ColorPanel extends JPanel{
ColorPanel(){
setBackground(Color.BLUE);
setPreferredSize(new Dimension(150,150));
setVisible(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
System.out.println("X:"+getX()+"Y:"+getY());
g.drawString("Test", getX(), getY());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
new MainFrame();
}
});
}
}
最佳答案
getX()
和 getY()
返回组件在其父级上下文中的 x/y 位置。
组件内的所有引用都是相对于该组件的,这意味着该组件的左上角/顶部位置实际上是0x0
。
这可能意味着文本被绘制在组件的可见区域之外。
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
FontMetrics fm = g.getFontMetrics();
int y = fm.getFontHeight() + fm.getAscent();
System.out.println("X:"+getX()+"Y:"+getY());
g.drawString("Test", 0, y);
}
关于java - 不显示在 GridLayout 的 JPanel 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955383/