[英]insert line break in java
我在换行符时遇到问题,我编写了这样的代码
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Welcome extends JFrame {
JMenu menuAdd, menuShow, menuEdit, menuHelp;
JMenuItem addCar, addRent, addUser, editCar, editCostumer, editUser, showCar, showRent, helpAbout;
JLabel lblWelcome;
JMenuBar mb;
public Welcome() {
setTitle("Car Tooner");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,400);
setLocationRelativeTo(null);
setResizable(false);
menuAdd = new JMenu("Add");
menuShow = new JMenu("Show");
menuEdit = new JMenu("Edit");
menuHelp = new JMenu("Help");
addCar = new JMenuItem("Car");
addRent = new JMenuItem("Rent");
addUser = new JMenuItem("User");
editCar = new JMenuItem("Car");
editCostumer = new JMenuItem("Costumer");
editUser = new JMenuItem("User");
showCar = new JMenuItem("Car");
showRent = new JMenuItem("Rent");
helpAbout = new JMenuItem("About");
mb = new JMenuBar();
lblWelcome = new JLabel("Welcome, Admin \nto Car Tooner", SwingConstants.CENTER);
setJMenuBar(mb);
mb.add(menuAdd);
mb.add(menuEdit);
mb.add(menuShow);
mb.add(menuHelp);
menuAdd.add(addCar);
menuAdd.add(addRent);
menuAdd.add(addUser);
menuEdit.add(editCar);
menuEdit.add(editCostumer);
menuEdit.add(editUser);
menuShow.add(showCar);
menuShow.add(showRent);
menuHelp.add(helpAbout);
add(lblWelcome);
}
public static void main(String[] args) {
Welcome wlc = new Welcome();
wlc.setVisible(true);
}
}
但是当我运行程序时,无法执行换行符,
lblWelcome = new JLabel("Welcome, Admin \nto Car Tooner", SwingConstants.CENTER);
我想输入“欢迎您,向Tooner管理员(\\ n新行)”这样的文字,有人可以帮助我吗?
您可以嵌入HTML来做到这一点。 我会用
lblWelcome = new JLabel("<html>Welcome, Admin <br/>to Car Tooner", SwingConstants.CENTER);
我想输入“欢迎您,向Tooner管理员(\\ n新行)”这样的文字,有人可以帮助我吗?
用<html></html>
包围字符串,并用<br>
换行。
JLabel l = new JLabel("<html>Welcome admin <br>to car Toner</html>", SwingConstants.CENTER);
也可以在这里进行扩展讨论
public static final String NL = System.getProperty("line.separator");
您需要获取行分隔符,以便它可以跨平台工作,因为\\ n并不总是有效。 例如,\\ r \\ n是在Windows中执行此操作的正确方法。 只需将line.separator写入变量,然后在需要时将其添加。 这就是为什么static之所以有用的原因,因为它将在该类的所有实例之间保持不变。
要构建它:
lblWelcome = new JLabel("Welcome, Admin" + NL + "to Car Tooner", SwingConstants.CENTER);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.