[英]not displaying in JPanel in GridLayout
我有一个带有GridLayout的JFrame作为其layoutmanager。 当我按下'New ...'(JMenuItem)时,添加了具有background:blue的新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();
}
});
}
}
我试图在drawString(...,x,y);中添加getX()+ 20,getY()+ 20; 表现奇怪,没有出现在正确的位置
x / y值表示文本的底部/左侧位置,而不是顶部/左侧。
因此,如果要进行自定义绘画,则必须确定适当的x / y值,以使文本“显示在正确的位置”,这对您而言意味着什么。
如果要对文本进行任何精美的定位,则需要使用FontMetrics
类。 您可以从Graphics
对象获取FontMetrics。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.