The string is surrounded by a box with a 5 pixels padding. The box is automatically centered in the app window.
The above output is produced by the following Java code:
import javax.swing.*;
import java.awt.*;
public class Frame
{
public static void main(String[] args)
{
SwingApp app = new SwingApp(300, 200); // set app window size
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class SwingApp extends JFrame
{
private final DrawPanel panel; // class variable
public SwingApp(int width, int height) // class constructor
{
super(); // call to super class constructor
Container pane = super.getContentPane(); // create layout, set colors
panel = new DrawPanel(); // add GUI components
panel.setBackground(Color.yellow);
pane.add(panel);
Toolkit toolkit = Toolkit.getDefaultToolkit(); // optionally position JFrame
Dimension screenSize = toolkit.getScreenSize(); // in the middle of the screen
super.setLocation((screenSize.width - width)/2, (screenSize.height - height)/2);
super.setTitle("Swing app"); // set desired window title
super.setSize(width, height); // set desired window size
super.setVisible(true);
// add here more code for GUI components
}
}
class DrawPanel extends JPanel // main window panel
{
private final String s; // string to draw
private final int border; // border width around the string
public DrawPanel() // class constructor
{
s = "Welcome to CSCI201";
border = 5;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g); // must be the 1st line
// add here more code for drawing on panel
g.setFont(new Font("Serif", Font.BOLD, 20));
int leading = g.getFontMetrics().getLeading();
int ascent = g.getFontMetrics().getAscent();
int fontHeight = g.getFontMetrics().getHeight();
int stringWidth = g.getFontMetrics().stringWidth(s);
// (x,y) is the position of the blue box top left corner
int x = (getWidth() - stringWidth - 2*border) / 2;
int y = (getHeight() - fontHeight - 2*border) / 2;
g.setColor(Color.blue);
g.fillRect(x, y, stringWidth + 2*border, fontHeight + 2*border);
// drawing the string in white atop the box
g.setColor(Color.white);
g.drawString(s, x + border, y + ascent + leading + border);
}
}
|