Home > Software engineering >  Set size of JTextField with BoyLayout Manager. Java
Set size of JTextField with BoyLayout Manager. Java

Time:10-05

I have seen this question been answered. but not for BoxLayout. I have created a schedule app in Java and because I want to display every hour under each other, I have chosen BoxLayout. When every hour is displayed, everything looks perfect. However, before my method is called by clicking a button, the JTextField just takes up the whole screen (with the button). How do I make that different?

Main class:

public class Main {
    
    public static void main(String[] args) {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setResizable(true);
                
    GamePanel gamepanel = new GamePanel();
    
    window.add(gamepanel);
    
    window.pack();
            
    window.setLocationRelativeTo(null);
    window.setVisible(true)
    
    }
}

GamePanel Class:

public class GamePanel extends JPanel implements ActionListener {
    
    //Screen Settings
    final int originalTileSize = 16;
    final int scale = 3;
    final int tileSize = originalTileSize * scale;
    final int maxScreenCol = 16;
    final int maxScreenRow = 12;
    final int screenWidth = tileSize * maxScreenCol;
    final int screenHeight = tileSize * maxScreenRow;
    
    //Initialize the things that are displayed
    JButton knopf;
    JTextField field;
    Tage days; 
    String textInhalt;
    static JLabel displayIsSchool;
    static JLabel stunden;
    static JLabel stunden1;
    static JLabel stunden2;
    static JLabel stunden3;
    static JLabel stunden4;
    static JLabel stunden5;
    static JLabel stunden6;
    static JLabel stunden7;
    static JLabel stunden8;
    
        //Panel constructor
        public GamePanel(){
            
            super();
            this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
            
            //JFrame stats
            this.setPreferredSize(new Dimension(screenWidth, screenHeight));
            this.setBackground(Color.darkGray);
            this.setDoubleBuffered(true);
            this.setFocusable(true);
            
            //Initialize Text field 
            field = new JTextField();
            field.setFont(new Font("Serif",Font.BOLD,30));
            field.setPreferredSize(new Dimension (100, 50));
            
            //Initialize Button 
            knopf = new JButton("klick");
            knopf.addActionListener(this);
            knopf.setPreferredSize(new Dimension (100, 35));
            
            //Initialize isSchool
            displayIsSchool = new JLabel("");
            displayIsSchool.setForeground(Color.white);
            displayIsSchool.setFont(new Font("Serif",Font.BOLD,30));
        
            //Initialize stunden
            stunden = new JLabel("");
            stunden.setForeground(Color.white);
            stunden.setFont(new Font("Serif",Font.BOLD,30));
            
            stunden1 = new JLabel("");
            stunden1.setForeground(Color.white);
            stunden1.setFont(new Font("Serif",Font.BOLD,30));
        
            stunden2 = new JLabel("");
            stunden2.setForeground(Color.white);
            stunden2.setFont(new Font("Serif",Font.BOLD,30));
        
            stunden3 = new JLabel("");
            stunden3.setForeground(Color.white);
            stunden3.setFont(new Font("Serif",Font.BOLD,30));
        
            stunden4 = new JLabel("");
            stunden4.setForeground(Color.white);
            stunden4.setFont(new Font("Serif",Font.BOLD,30));
        
            stunden5 = new JLabel("");
            stunden5.setForeground(Color.white);
            stunden5.setFont(new Font("Serif",Font.BOLD,30));
        
            stunden6 = new JLabel("");
            stunden6.setForeground(Color.white);
            stunden6.setFont(new Font("Serif",Font.BOLD,30));
        
            stunden7 = new JLabel("");
            stunden7.setForeground(Color.white);
            stunden7.setFont(new Font("Serif",Font.BOLD,30));
        
            stunden8 = new JLabel("");
            stunden8.setForeground(Color.white);
            stunden8.setFont(new Font("Serif",Font.BOLD,30));
        
            //Add everything to JFrame
            this.add(field);
            this.add(knopf);
            this.add(displayIsSchool);
            this.add(stunden);
            this.add(stunden1);
            this.add(stunden2);
            this.add(stunden3);
            this.add(stunden4);
            this.add(stunden5);
            this.add(stunden6);
            this.add(stunden7);
            this.add(stunden8);
        }
        
    //Call Method for set Day
    public void sayIf() {

        //Switch statement for user Input 
        switch(textInhalt) 
        {
                
            case "Montag":
                Montag.sagName();
                break;
            case "Dienstag":
                Dienstag.sagName();
                break;
            case "Mittwoch":
                Mittwoch.sagName();
                break;
            case "Donnerstag":
                Donnerstag.sagName();
                break;  
            case "Freitag":
                Freitag.sagName();      
                break;
            case "Samstag":
                Samstag.sagName();
                break;
            case "Sonntag":
                Sonntag.sagName();
                break;  
        }
    }   
    
        //schedule
        static String[] monHours = {"Bio", "Bio", "Mathe", "Mathe", "Chemie", "Chemie", "Frei", "Musik", "Musik"};
        static String[] dinHours = {"Deutsch", "Mathe", "Physik", "Physik", "Englisch", "Frei", "Französisch", "Frei", "Frei"};
        static String[] mitHours = {"Französisch", "Französisch", "Englisch", "Tutor", "Geschichte", "Geschichte", "Frei", "Sport", "Sport"};
        static String[] donHours = {"Englisch", "Englisch", "Deutsch", "Deutsch", "Informatik", "Informatik", "Frei", "Frei", "Frei"};
        static String[] freHours = {"PoWi", "PoWi", "Ethik", "Ethik", "Deutsch", "Frei", "Mathe", "Frei", "Frei"};
        static String[] samHours = {"", "", "", "", "", "", "", "", ""};
        static String[] sonHours = {"", "", "", "", "", "", "", "", ""};
        
        //create Day objects 
        static Tage Montag = new Tage(true, monHours, "Montag");
        static Tage Dienstag = new Tage(true, dinHours, "Dinestag")  ;
        static Tage Mittwoch = new Tage(true, mitHours, "Mittwoch")  ;
        static Tage Donnerstag = new Tage(true, donHours, "Donnerstag")  ;
        static Tage Freitag = new Tage(true, freHours, "Freitag")  ;
        static Tage Samstag = new Tage(false, samHours, "Samstag")  ;
        static Tage Sonntag = new Tage(false, sonHours, "Sonntag")  ;       
        
        
        //keyListener 
        public void actionPerformed(ActionEvent e) {
            if(e.getSource()==knopf) {
    
                textInhalt = field.getText();
                sayIf();
            }
        }
}

Tag (Day) Class:

package basicsPack;

public class Tage{
    
    //Variables for constructor 
    boolean isSchool;
    String[] stunden;
    String name;
    
    //Tage constructor 
    public Tage(boolean isSchool, String[] stunden, String name) {
        
        this.isSchool = isSchool;  
        this.stunden = stunden;
        this.name = name;
        
    }
    
    //sagName method
    public void sagName() {
        
        //Display hours an rather I have school
        if(this.isSchool == true) {
        
            GamePanel.displayIsSchool.setText("Du hast am "  name   " Schule ");
            GamePanel.stunden.setText(this.stunden[0]);
            GamePanel.stunden1.setText(this.stunden[1]);
            GamePanel.stunden2.setText(this.stunden[2]);
            GamePanel.stunden3.setText(this.stunden[3]);
            GamePanel.stunden4.setText(this.stunden[4]);
            GamePanel.stunden5.setText(this.stunden[5]);
            GamePanel.stunden6.setText(this.stunden[6]);
            GamePanel.stunden7.setText(this.stunden[7]);
            GamePanel.stunden8.setText(this.stunden[8]);
            
        }else {
            
            GamePanel.displayIsSchool.setText("Du hast am "   name   " keine Schule");
            GamePanel.stunden.setText("");
            GamePanel.stunden1.setText("");
            GamePanel.stunden2.setText("");
            GamePanel.stunden3.setText("");
            GamePanel.stunden4.setText("");
            GamePanel.stunden5.setText("");
            GamePanel.stunden6.setText("");
            GamePanel.stunden7.setText("");
            GamePanel.stunden8.setText("");
        }
    }
}

This is what it looks like at the moment

This Is what I want it to look like

CodePudding user response:

So yes, put the JTextField and JButton in their own JPanel in a BoxLayout using JPanel, that is fine, and place that JPanel in the BorderLayout.PAGE_START position of a JPanel that uses BorderLayout with the rest of the GUI below it. For example:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class Main2b {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GamePanel2 mainPanel = new GamePanel2();

            JFrame frame = new JFrame("GUI");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

}

@SuppressWarnings("serial")
class GamePanel2 extends JPanel {
    private JTextField field = new JTextField(10);
    private JButton knopf = new JButton("klick");
    
    public GamePanel2() {
        knopf.setMnemonic(KeyEvent.VK_K);
        
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.LINE_AXIS));
        topPanel.add(field);
        topPanel.add(knopf);
        
        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.PAGE_START);
        add(Box.createRigidArea(new Dimension(650, 400)));
        
    }
}

displays as

enter image description here


Other unrelated issues:

  • Avoid static variables unless there is a distinct need to use them (that isn't the case here) such as constants of a class or fields that must be part of the class, not the instance.
  • Use arrays or ArrayLists to reduce code repetition. This will make your code much easier to debug and enhance.
  • Also, you can give your JTextField an ActionListener, the same as the button, and it will be triggered when enter is pressed and the text field has focus.
  • If the user should only type in the days of the week and nothing else, then don't use a JTextField for this where the user can type in anything. Instead, use a JComboBox where they can only choose the Strings that you offer to them.

For example:

@SuppressWarnings("serial")
class GamePanel2 extends JPanel {
    public static final String[] TAG_DER_WOCH = { "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag",
            "Sonntag" };
    private JComboBox<String> tagDerWochCombo = new JComboBox<>(TAG_DER_WOCH);
    // private JTextField field = new JTextField(10);
    // private JButton knopf = new JButton("klick");

    public GamePanel2() {
        tagDerWochCombo.setSelectedIndex(-1);
        // knopf.setMnemonic(KeyEvent.VK_K);
        
        tagDerWochCombo.addActionListener(e -> {
            System.out.println(tagDerWochCombo.getSelectedItem());
        });

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.LINE_AXIS));
        topPanel.add(tagDerWochCombo);
        // topPanel.add(knopf);

        setLayout(new BorderLayout());
        add(topPanel, BorderLayout.PAGE_START);
        add(Box.createRigidArea(new Dimension(650, 400)));

    }
}
  • Related