我想让我的JLabel有一个适合文本的边框。我尝试使用int来调整大小,但这不起作用。有人可以帮忙吗? 这是我的Java代码:
package first;
import java.awt.*;
import javax.swing.*;
public class TopLevelWindow {
static int hgap=5;
static int vgap=5;
private static void createWindow() {
//Create and set up the window.
JFrame frame = new JFrame("Window");
JLabel textLabel = new JLabel("Welcome Child",SwingConstants.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
textLabel.setForeground(Color.YELLOW);
textLabel.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 5));
//Display the window.
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
frame.getContentPane().setBackground(Color.BLACK);
}
public static void main(String[] args) { createWindow(); }
}
我希望它看起来像这样的文本框: http://www.bogleech.com/halloween/undertale-grillbys.png 这可能在java?
答案 0 :(得分:0)
如果要从屏幕获得效果,则应将垂直对齐设置为NORTH
,并使用由白色外边框和内部不可见边框组成的CompoundBorder,它看起来像边距。试试这段代码:
JLabel textLabel = new JLabel("Test test test test test test test...");
textLabel.setPreferredSize(new Dimension(500, 250));
textLabel.setForeground(Color.WHITE);
textLabel.setFont(new Font("Courier", Font.BOLD, 30));
// sets the text to the upper left corner
textLabel.setVerticalAlignment(SwingConstants.NORTH);
textLabel.setBorder(new CompoundBorder( // sets two borders
BorderFactory.createMatteBorder(10, 10, 10, 10, Color.WHITE), // outer border
BorderFactory.createEmptyBorder(10, 10, 10, 10))); // inner invisible border as the margin
答案 1 :(得分:0)
显然,如果将JLabel的大小设置为300×300,其边框将围绕该矩形。
相反,只留下JLabel的尺寸,并将其放置在具有居中布局的面板中,然后将边框放在该面板上:
JLabel textLabel = new JLabel("Welcome Child",SwingConstants.CENTER);
textLabel.setForeground(Color.YELLOW);
textLabel.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 5));
JPanel textPanel = new JPanel(new GridBagLayout());
textPanel.add(textLabel);
textPanel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textPanel, BorderLayout.CENTER);