Java/Swing – 为文本字段设置标题

huangapple go评论48阅读模式
英文:

Java/Swing - Set title for TextField

问题

我找不到任何用于设置TextField标题的类。因此,我决定创建一个。我的问题非常简单。

我真的需要在我的类中包含JFrame吗?或者可能有一种不同的方法来解决这个问题。

这是我的GUI类。

public GUI() {	
    JFrame f = new JFrame("MyLibrary");
    JTextField tf = new JTextField();
    
    tf.setBounds(50, 50, 400, 30);
    tf.setFont(new Font("Arial", Font.BOLD, 16));
    FieldTitle ft = new FieldTitle(f, tf, "Book title");
    
    f.add(tf);
    f.setSize(1280, 720);
    f.setLocationRelativeTo(null);
    f.setLayout(null);
    f.setVisible(true);
}

这是我的FieldTitle类。

public FieldTitle(JFrame f, Component c, String title) {
    JLabel l = new JLabel(title);
    
    l.setBounds(c.getBounds().x, c.getBounds().y - 20, c.getWidth(), 20);
    
    f.add(l);
}

感谢您的时间和努力。祝您有一个美好的一天!

英文:

I could not find any class to set a title for TextField. Therefore, I decided to make one. My question is really simple.

Do I really need to include JFrame in my class or maybe there is a different way to accomplish this problem.

Here is my GUI class.

public GUI() {	
	JFrame f = new JFrame("MyLibrary");
	JTextField tf = new JTextField();
	
	tf.setBounds(50, 50, 400, 30);
	tf.setFont(new Font("Arial", Font.BOLD, 16));
	FieldTitle ft = new FieldTitle(f, tf, "Book title");
	
	f.add(tf);
	f.setSize(1280, 720);
	f.setLocationRelativeTo(null);
	f.setLayout(null);
	f.setVisible(true);
}

And here is my FieldTitle class.

public FieldTitle(JFrame f, Component c, String title) {
	JLabel l = new JLabel(title);
	
	l.setBounds(c.getBounds().x, c.getBounds().y - 20, c.getWidth(), 20);
	
	f.add(l);
}

Thank you for your time and effort. Have a great day!

答案1

得分: 2

不要使用空布局。不要使用setBounds()。

Swing被设计用于与布局管理器一起使用。您可以轻松地使用一个JPanel和一个BoxLayout

  1. 创建一个JPanel并将布局设置为垂直的BoxLayout
  2. 创建并将JLabel添加到面板
  3. 创建并将JTextField添加到面板
  4. 将面板添加到框架。

阅读Swing教程上的布局管理器以获取更多信息。您将找到一个可用的示例,演示如何创建一个使用BoxLayout的面板的框架。

英文:

Don't use a null layout. Don't use setBounds().

Swing was designed to be used with layout managers. You can easily use a JPanel with a BoxLayout:

  1. Create a JPanel and set the layout to a vertical BoxLayout
  2. Create and add the JLabel to the panel
  3. Create and and the JTextField to the panel
  4. Add the panel to the frame.

Read the Swing tutorial on Layout Managers for more information. You will find a working example that shows how to create a frame with a panel using a BoxLayout.

huangapple
  • 本文由 发表于 2020年7月22日 05:28:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63023374.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定