简体   繁体   中英

How to add a new line to text in Java?

I am creating a game of checkers in Java for my A2 Computing coursework, I have recently working on the GUI of the Checkerboard, of which I wish to add in a menu bar, I have been able to achieve this as can be seen in my code, however for one of the menu items, known as Rules, I wish to add a couple of the basic rules within the text, this occurs on the line:
JMenuItem RulesText = new JMenuItem("")

Within this I wish to input the text for the rules, I have inputted some of these already has can be seen.

My problem is that, they are all on one line, so when I run the application, it appears as "Moves are always only diagonal. Single pieces are always limited to forward moves (toward the opponent). Kings are limited to moving diagonally, but may move both forward and backward". The problem is that this is not the format that I want it to be present in, I want it be present in a format similar to this

  • Moves are always only diagonal
  • Single pieces are always limited to forward moves (toward the opponent) ect......

So how can I possibly achieve this, I have attempted to research this I couldn't find anything in my format, as I would prefer to not have to change the majority of the code. Any answers would be extremely appreciated. Thank you. My Code can be seen Below:

    JMenuBar bar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    JMenu HelpMenu = new JMenu("Help");
    JMenuItem Exit = new JMenuItem("Exit");
    JMenuItem MainMenu = new JMenuItem("Main Menu");
    JMenu Rules = new JMenu("Rules of Checkers");
    JMenuItem RulesText = new JMenuItem("- Moves are always only diagonal \n Single pieces are always limited to forward moves (toward the opponent) \n Kings are limited to moving diagonally, but may move both forward and backward");
    Rules.add(RulesText);
    HelpMenu.add(Rules);
    bar.add(HelpMenu);
    fileMenu.add(MainMenu);
    fileMenu.addSeparator();
    fileMenu.add(Exit);
    HelpMenu.add(Rules);
    bar.add(fileMenu);
    bar.add(HelpMenu);
    window.setJMenuBar(bar);

Try wrapping the text in html tags and placing a <BR> tag where you want the line break.

However, I do agree with @rageandqq you should think about placing the rules in a JDialog or something similar

It doesn't look like this is possible, and is one of the limitations of using Swing to develop your application. None of the constructors or behaviours on the JMenuItem seem to allow for String formatting.

Besides, it's not very wise nor user friendly to set an entire JMenuItem to display such a large block of text.
You should consider using a JDialog box or something similar to bring up a screen where you can display your formatted rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM