不在GridLayout中的JPanel中显示

时间:2015-01-15 01:21:15

标签: java swing

我有一个带GridLayout的JFrame作为layoutmanager。当我按下新的...' (JMenuItem)新的ColorPanel对象与背景:蓝色被添加,但文本"测试"没有显示在JPanel内部。添加了ColorPanel对象并显示为蓝色,但是应该在里面的白色文本没有显示出来。我尝试在drawString(...,x,y)中添加getX()+ 20,getY()+ 20;它表现得很奇怪,没有出现在正确的地方,或根本没有露面。如何使文本显示在JPanel中,这些文本已通过GridLayout添加到框架中。

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();
        }
    });
}

}

2 个答案:

答案 0 :(得分:1)

  

我尝试在drawString(...,x,y)中添加getX()+ 20,getY()+ 20;它表现得很奇怪,而且没有出现在正确的地方

x / y值表示文本的底部/左侧位置,而不是顶部/左侧。

因此,如果您想进行自定义绘画,您必须确定正确的x / y值,以便文本显示在正确的位置",无论这对您意味着什么。

如果您想对文本进行任何精确定位,则需要使用FontMetrics类。您可以从Graphics对象获取FontMetrics。

答案 1 :(得分:1)

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);
}
相关问题