简体   繁体   中英

Java Swing - Buttons on a new line

enter code here I have a UI with a toolbar to apply different filters on an image and the image is displayed on the right side (the toolbar is on the left side) I am adding new buttons but the toolbar is now really long and i want to give a limit so once it is reaching 1/5 of the total frame, I want to display the buttons on a new line.

public class Toolbar extends JPanel {
  private JButton filterOne;
  private JButton filterTwo;
  private JButton filterThree;
  private JButton loadImage;
  private JLabel picture;


  Toolbar(){
    filterOne = new JButton("filterOne");
    filterTwo = new JButton("filterTwo");
    filterThree = new JButton("filterThree");
    loadImage = new JButton("loadImage");
    picture = new JLabel();

    setLayout(new FlowLayout());

    add(loadImage);

    loadImage.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) { 
         ImageIcon pic = new ImageIcon("ImageOne.png");
         picture.setIcon(pic);

      }
    });
    add(filterOne);
    add(filterTwo);
    add(filterThree);
    add(picture);
  }
}



public class MainFrame extends JFrame {

  private JTextArea textArea;
  private Toolbar toolbar;
  private ImagePannel imagePannel;

  MainFrame() {
    // Generating a new
    setLayout(new BorderLayout());

    // Generating a new toolbar that contains all the buttons to generate new images.
    toolbar = new Toolbar();

    imagePannel = new ImagePannel();

    add(imagePannel,BorderLayout.CENTER);

    // Position of the toolbar within the upper side of the pannel.
    add(toolbar, BorderLayout.WEST);

    //This is the name of the window
    JFrame frame = new JFrame("My view");

    //Initialize the size of the window
    setSize(1200, 800);

    //Makes the window close when we are crossing the window
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Makes the window visible
    setVisible(true);
  }
}

...so once it is reaching 1/5 of the total frame, I want to display the buttons on a new line.

Don't use setLayout(new FlowLayout()); since this is not a "smart" layout, one you can control easily. Instead use a different layout, perhaps GridLayout(0, 5) -- one with a variable number of rows and with 5 columns.

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