Hi,

I'm trying to print a string on the center of a window using GridBagLayout.
All I see printed is a part of the string I expect (the current month) instead of the whole string.
I don't seem to be able to spot where the error is and I'd appreciate if you could tell me.

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.util.*;

class DrawTextPanel extends JPanel {
	String text;
	String font;
	int size;
	Font fontFamily;


	DrawTextPanel(String text, String font, int size) {
		this.text = text;
		this.font = font;
		this.size = size;
		fontFamily = new Font(font, Font.BOLD, size);
	}

	public void paintComponent(Graphics comp) {
		Graphics2D g2d = (Graphics2D) comp;
		g2d.setFont(fontFamily);
		g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		FontMetrics fm = comp.getFontMetrics(fontFamily);
		int stringHeight = fm.getHeight();
		int stringWidth = fm.stringWidth(text);
		int yCoordinate = (getSize().height + stringHeight)/2;
		int xCoordinate = (getSize().width - stringWidth)/2;
		g2d.drawString(text, xCoordinate, yCoordinate);
		repaint();
	}
}


class Gui extends JFrame {
	String month;
	JPanel mainPane = new JPanel();
	GridBagLayout gbLayout = new GridBagLayout();
	GregorianCalendar gc;

	Gui() {
		super("test");
		setSize(200, 300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		gc = new GregorianCalendar();
		month = String.valueOf(gc.get(Calendar.MONTH));

		mainPane.setLayout(gbLayout);
		addText(month, mainPane, "Verdana", 20, 0, 0, 10, 2, 100, 2, GridBagConstraints.CENTER, GridBagConstraints.NONE);

		add(mainPane);

		setVisible(true);
	}

	private void addText(String text, Container cont, String font, int size, int gx, int gy, int gwidth, int gheight, int wx, int wy, int anch, int fi) {
		GridBagConstraints gbc = new GridBagConstraints();
		gbc.gridx = gx;
		gbc.gridy = gy;
		gbc.gridwidth = gwidth;
		gbc.gridheight = gheight;
		gbc.weightx = wx;
		gbc.weighty = wy;
		gbc.anchor = anch;
		gbc.fill = fi;
		DrawTextPanel dtComponent = new DrawTextPanel(text, font, size);
		gbLayout.setConstraints(dtComponent, gbc);
		cont.add(dtComponent);
	}



}
public class Test {
	public static void main(String[] args) {
		Gui gui = new Gui();
	}
}

Thanks for the help.

Hi

GridBagConstraints.NONE means that the item (text) can not grow.
Change .NONE to .BOTH and see what happens :D

Good luck :)

commented: good comment +2

Thanks, sneaker.
That did it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.