Advertisement
makispaiktis

19. FlowLayout - Set Alignment through buttons and a container

May 31st, 2022 (edited)
925
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.89 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4.  
  5. public class Gui extends JFrame{
  6.  
  7.     // Variables
  8.     private JButton lb;
  9.     private JButton cb;
  10.     private JButton rb;
  11.     private FlowLayout layout;
  12.     private Container container;
  13.  
  14.     // Constructor
  15.     public Gui(){
  16.  
  17.         // Basics
  18.         super("JFrame's title");
  19.         layout = new FlowLayout();
  20.         setLayout(layout);
  21.         container = getContentPane();
  22.  
  23.         // Buttons
  24.         lb = new JButton("Left");
  25.         add(lb);
  26.         lb.addActionListener(
  27.                 new ActionListener() {
  28.                     @Override
  29.                     public void actionPerformed(ActionEvent event) {
  30.                         layout.setAlignment(FlowLayout.LEFT);
  31.                         layout.layoutContainer(container);
  32.                     }
  33.                 }
  34.         );
  35.         cb = new JButton("Center");
  36.         add(cb);
  37.         cb.addActionListener(
  38.                 new ActionListener() {
  39.                     @Override
  40.                     public void actionPerformed(ActionEvent event) {
  41.                         layout.setAlignment(FlowLayout.CENTER);
  42.                         layout.layoutContainer(container);
  43.                     }
  44.                 }
  45.         );
  46.         rb = new JButton("Right");
  47.         add(rb);
  48.         rb.addActionListener(
  49.                 new ActionListener() {
  50.                     @Override
  51.                     public void actionPerformed(ActionEvent event) {
  52.                         layout.setAlignment(FlowLayout.RIGHT);
  53.                         layout.layoutContainer(container);
  54.                     }
  55.                 }
  56.         );
  57.  
  58.     }
  59.  
  60.     // Main Function
  61.     public static void main(String[] agrs){
  62.         Gui gui = new Gui();
  63.         gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
  64.         gui.setSize(400, 400);
  65.         gui.setVisible(true);
  66.     }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement