resize a window bases on the text content
I want to be able to Enter Text that will appear on the window and then if I were to re-size th开发者_运维知识库e window then the text could change with its size. The problem is that I'm not entirely sure how to implement this. Since I will to writing to the Jpanel I'm thinking I would have to use a Jlabel to add the text onto the window, but then resizing the window might not affect the Jlabel? Am I suppose to directly write on the Jpanel somehow, or get the size of the window(length and width) and use that to increase or decrease the size of the text? Any help would be appreciated.
If I understand your question correctly that you are trying to re-size some label type text you could try something along these lines:
public class ResizeTextTest extends JFrame{
public ResizeTextTest() {
add(new MyPanel());
}
public static void main(String[] args) {
ResizeTextTest t = new ResizeTextTest();
t.setSize(400,300);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setVisible(true);
}
class MyPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//Using a multiplier like this on the width and height of the
//Panel will give you a text size that correlates with the size
//of the window.
Font f = new Font("Arial", Font.PLAIN,
(int) (.0005 * this.getWidth() * this.getHeight()));
g.setFont(f);
g.drawString("Hello World", 50, 100);
}
}
The paintComponent method is automatically called when the window is resized. You can also call it explicitly using the component's repaint() method.
Use a text area, not a label. Make sure the 'line wrap' property is selected/true.
精彩评论