Icemanind
Icemanind

Reputation: 48736

Java Panel overlapping Menu

I am new to Java, so this question might be obvious.

I have this Initialization code:

frame = new JFrame();
frame.setTitle("Test");
frame.setBounds(100, 100, 512, 468);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

JPanel panel = new MyJPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setAlignmentY(Component.TOP_ALIGNMENT);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.setPreferredSize(new Dimension(0, 0));
panel.setMinimumSize(new Dimension(0, 0));
frame.getContentPane().add(panel, BorderLayout.CENTER);

JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);

JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);

mntmOpenBBinary.setPreferredSize(new Dimension(149, 22));
mnFile.add(mntmOpenBBinary);

JSeparator separator = new JSeparator();
mnFile.add(separator);

JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        System.exit(0);
    }
});
mnFile.add(mntmExit);

MyJPanel is a custom class that extends the JPanel class. Just as a test, it just writes "test" to the screen in the paintComponent method:

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    g.setColor(Color.BLACK);
    g.setFont(RenderFont);
    g.drawString("TEST", 1, 1);
    }

You can see from the image below that, for some reason, the drawString method is drawing behind the menu. The coordinates I give in drawString, I'd think, would be the coordinates relative to the JPanel window. Also, the JPanel is "filling" the entire space of the JFrame. I'd prefer that my MyJFrame be only 100x100, but it seems to always want to auto fill the JFrame. How can I solve these 2 issues?

enter image description here

Upvotes: 0

Views: 1148

Answers (1)

xav
xav

Reputation: 5628

The text is hidden by the menu bar because last parameter of drawString() is the text baseline, and not the upper bound: http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html#drawString(java.lang.String,%20int,%20int)

So you need to use something like:

 g.drawString("TEST", 1, 50);

Or better, use Font.getStringBounds() to compute your text height:

 Rectangle2D textBounds = g.getFont().getStringBounds("TEST", (((Graphics2D) g).getFontRenderContext());

And to avoid having your panel taking all Frame space, replace:

frame.getContentPane().add(panel, BorderLayout.CENTER);

with:

JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(panel, BorderLayout.NORTH);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);

Although, you should not need this:

panel.setAlignmentY(Component.TOP_ALIGNMENT);
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.setPreferredSize(new Dimension(0, 0));
panel.setMinimumSize(new Dimension(0, 0));

Upvotes: 4

Related Questions