fubarable

Swing example program

Jan 20th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. import java.awt.Color;
  2. import java.awt.Dimension;
  3. import java.awt.Graphics;
  4. import java.awt.GridBagLayout;
  5. import java.awt.GridLayout;
  6. import javax.swing.*;
  7.  
  8. @SuppressWarnings("serial")
  9. public class Gui002 extends JPanel {
  10.     private static final int TEXT_FIELD_COUNT = 3;
  11.     private static final Color BG = Color.BLACK;
  12.     private static final Dimension PREF_SIZE = new Dimension(500, 350);
  13.     private JTextField[] fields = new JTextField[TEXT_FIELD_COUNT];
  14.    
  15.     public Gui002() {
  16.         // make background black
  17.         setBackground(BG);
  18.        
  19.         // create JPanel to hold 3 JTextFields in a single column
  20.         JPanel innerPanel = new JPanel(new GridLayout(0, 1, 10, 0));
  21.         // allow background color to show through this JPanel
  22.         innerPanel.setOpaque(false);
  23.        
  24.         // create and add our 3 JTextFields
  25.         for (int i = 0; i < fields.length; i++) {
  26.             fields[i] = new JTextField(10);
  27.             innerPanel.add(fields[i]);
  28.         }
  29.        
  30.         setPreferredSize(PREF_SIZE); // not best way to do this
  31.         // set layout of enclosing JPanel so that inner panel is centered
  32.         setLayout(new GridBagLayout());
  33.         add(innerPanel);
  34.     }
  35.    
  36.     @Override
  37.     protected void paintComponent(Graphics g) {
  38.         super.paintComponent(g);
  39.        
  40.         // .... only painting code goes here
  41.     }
  42.  
  43.     private static void createAndShowGui() {
  44.         Gui002 mainPanel = new Gui002();
  45.  
  46.         JFrame frame = new JFrame("GUI");
  47.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  48.         frame.getContentPane().add(mainPanel);  // add components first
  49.         frame.pack();
  50.         frame.setLocationRelativeTo(null);
  51.         frame.setVisible(true);  // set visible **after** components added
  52.     }
  53.  
  54.     public static void main(String[] args) {
  55.         SwingUtilities.invokeLater(() -> createAndShowGui());
  56.     }
  57. }
Add Comment
Please, Sign In to add comment