0

I need to use the GridBagLayout but I get below error. Can you please help?

java.lang.IllegalArgumentException: cannot add to layout: constraints must be a GridBagConstraint at java.awt.GridBagLayout.addLayoutComponent(Unknown Source) at java.awt.Container.addImpl(Unknown Source) at java.awt.Container.add(Unknown Source) at havuzAracıFormu.(havuzAracıFormu.java:221) at havuzAracıFormu$1.run(havuzAracıFormu.java:47) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$500(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import org.jdatepicker.impl.JDatePanelImpl;
import org.jdatepicker.impl.JDatePickerImpl;
import org.jdatepicker.impl.UtilDateModel;

import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFormattedTextField.AbstractFormatter;

import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import java.awt.event.ActionEvent;

public class havuzAracıFormu extends JFrame {

    private JPanel contentPane;
    private JTextField textFieldAdSoyad;
    private JTextField textFieldGorev;
    private JTextField textFieldDepartman;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    havuzAracıFormu frame = new havuzAracıFormu();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     * @throws ClassNotFoundException 
     * @throws SQLException 
     */
    public havuzAracıFormu() throws ClassNotFoundException, SQLException {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 728, 992);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.CENTER;

        setContentPane(contentPane);

        JLabel lblKullancBilgileri = new JLabel("Kullan\u0131c\u0131 Bilgileri");
        Font font = lblKullancBilgileri.getFont();
        lblKullancBilgileri.setFont(new Font(font.getFontName(), Font.BOLD, 14));
        contentPane.add(lblKullancBilgileri);       

        JLabel lblAdSoyad = new JLabel("Ad\u0131 Soyad\u0131");
        JLabel lblGorevi = new JLabel("Görevi");
        JLabel lblDepartmani = new JLabel("Departman\u0131");
        contentPane.add(lblAdSoyad,gbc);

        textFieldAdSoyad = new JTextField();
        contentPane.add(textFieldAdSoyad, gbc);
        textFieldAdSoyad.setColumns(10);

        contentPane.add(lblGorevi);

        textFieldGorev = new JTextField();
        contentPane.add(textFieldGorev, gbc);
        textFieldGorev.setColumns(5);

        contentPane.add(lblDepartmani, gbc);

        textFieldDepartman = new JTextField();
        contentPane.add(textFieldDepartman);
        textFieldDepartman.setColumns(10);


        JLabel lblAracBilgileri = new JLabel("Araç Bilgileri");
        Font font2 = lblAracBilgileri.getFont();
        lblAracBilgileri.setFont(new Font(font2.getFontName(), Font.BOLD, 14));
        contentPane.add(lblAracBilgileri, gbc);

        JLabel lblMarka = new JLabel("Marka");
        contentPane.add(lblMarka, gbc);
        JTextField textFieldMarka = new JTextField(5);
        contentPane.add(textFieldMarka,gbc);
        textFieldMarka.setColumns(5);

        JLabel lblModel = new JLabel("Model");
        contentPane.add(lblModel,gbc);
        JTextField textFieldModel = new JTextField();
        contentPane.add(textFieldModel,gbc);
        textFieldModel.setColumns(5);

        JLabel lblPlakaNo = new JLabel("PlakaNo");
        contentPane.add(lblPlakaNo,gbc);
        JTextField textFieldPlakaNo = new JTextField();
        contentPane.add(textFieldPlakaNo,gbc);
        textFieldPlakaNo.setColumns(5);

        JLabel lblCikisTarihiveSaati = new JLabel("Çıkış Tarihi ve Saati");
        contentPane.add(lblCikisTarihiveSaati,gbc);
        JTextField textFieldCikis = new JTextField();
//      contentPane.add(textFieldCikis);
        UtilDateModel model = new UtilDateModel();
        Properties p = new Properties();
        p.put("text.today", "Today");
        p.put("text.month", "Month");
        p.put("text.year", "Year");
        JDatePanelImpl datePanel = new JDatePanelImpl(model, p);
        JDatePickerImpl datePicker = new JDatePickerImpl(datePanel, new DateLabelFormatter());
        contentPane.add(datePicker,gbc);

        textFieldCikis.setColumns(5);

        JLabel lblCikisKm = new JLabel("Çıkış Km");
        contentPane.add(lblCikisKm,gbc);
        JTextField textFieldCikisKm = new JTextField();
        contentPane.add(textFieldCikisKm,gbc);
        textFieldCikisKm.setColumns(5);

        JLabel lblDonusTarihiveSaati = new JLabel("Dönüş Tarihi ve Saati");
        contentPane.add(lblDonusTarihiveSaati,gbc);
        JTextField textFieldDonus = new JTextField();
        UtilDateModel model2 = new UtilDateModel();
        Properties p2 = new Properties();
        p2.put("text.today", "Today");
        p2.put("text.month", "Month");
        p2.put("text.year", "Year");
        JDatePanelImpl datePanel2 = new JDatePanelImpl(model2, p);

        JDatePickerImpl datePicker2 = new JDatePickerImpl(datePanel2, new DateLabelFormatter());
        contentPane.add(datePicker2,gbc);
        textFieldDonus.setColumns(5);

        JLabel lblDonusKm = new JLabel("Dönüş Km");
        contentPane.add(lblDonusKm,gbc);
        JTextField textFieldDonusKm = new JTextField();
        contentPane.add(textFieldDonusKm,gbc);
        textFieldDonusKm.setColumns(5);

        JLabel lblNeden = new JLabel("Aracın Kullanılacağı Yer-Kullanım Neden Geçici Araç");
        contentPane.add(lblNeden,gbc);
        JTextField textFieldNeden = new JTextField();
        contentPane.add(textFieldNeden,gbc);
        textFieldNeden.setColumns(5);

        JLabel lblKullanimSuresi = new JLabel("Kullanım Süresi");
        contentPane.add(lblKullanimSuresi,gbc);
        JTextField textFieldSure = new JTextField();
        contentPane.add(textFieldSure,gbc);
        textFieldSure.setColumns(5);

        JLabel lblHasarveEksiklikler = new JLabel("Hasar ve Eksiklikler");
        contentPane.add(lblHasarveEksiklikler,gbc);

        JLabel lblAractaGorulenHasarlar = new JLabel("Araçta Görülen Hasarlar veya Eksiklikler (Zincir, İstetme, İlk Yardım Çantası vs.");
        contentPane.add(lblAractaGorulenHasarlar,gbc);

        JTextField textFieldHasar = new JTextField();
        contentPane.add(textFieldHasar,gbc);
        textFieldHasar.setColumns(5);

        JButton btnNewButton = new JButton("Gönder");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String url = "jdbc:sqlserver://WIN-J53H5BK2ANC;databaseName=test;integratedSecurity=true;";
                try {
                    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

                Connection conn = DriverManager.getConnection(url);
                Statement st = conn.createStatement();
                String queryString = "insert into havuzAracıFormu values ('" + textFieldAdSoyad.getText() + "'," + 
                                                                          "'" + textFieldGorev.getText() + "'," +
                                                                          "'" + textFieldDepartman.getText() + "'," +
                                                                          "'" + textFieldMarka.getText() + "'," +
                                                                          "'" + textFieldModel.getText() + "'," +
                                                                          "'" + textFieldPlakaNo.getText() + "'," +
                                                                          "'" + datePicker.getJFormattedTextField().getText() + "'," +
                                                                          "'" + textFieldCikisKm.getText() + "'," +
                                                                          "'" + datePicker2.getJFormattedTextField().getText()+ "'," +
                                                                          "'" + textFieldDonusKm.getText() + "'," +
                                                                          "'" + textFieldNeden.getText() + "'," +
                                                                          "'" + textFieldSure.getText() + "'," +
                                                                          "'" + textFieldHasar.getText() + "')";
                st.executeUpdate(queryString);
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        contentPane.add(btnNewButton, BorderLayout.SOUTH);
    }

}

class DateLabelFormatter extends AbstractFormatter{

    private String datePattern = "yyyy-MM-dd";
    private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);

    @Override
    public Object stringToValue(String text) throws ParseException {

        return dateFormatter.parseObject(text);
    }

    @Override
    public String valueToString(Object value) throws ParseException {
        if(value != null){
            Calendar cal = (Calendar) value;
            return dateFormatter.format(cal.getTime());
        }
        return "";
    }

}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Deniz Hekimci
  • 11
  • 1
  • 1
  • 6
    It makes it much quicker and easier for everyone to look through your code if you post a [mcve], or a [Short, Self Contained, Correct Example](http://sscce.org/) :) – Gulllie Nov 10 '16 at 12:34
  • 1
    Variable names very long like spagetti confused, please make your code more readable. Define everything at first (at the beginning of the class). – Coder ACJHP Nov 10 '16 at 13:12
  • 1
    Why would you ever write an entire class before doing basic testing??? You have all kind of unnecessary code in this class that is not realated to the layout of components. None of the ActionListener code is relevant to the layout. The SQL has noting to do with the layout. So start from the beginning. Create a create with some components and see if the components display the way you want. If not, then you have simple code to post in the forum. – camickr Nov 10 '16 at 15:54
  • We don't know where the problem is because we can't compile your code because you use 3rd party classes. We don't know what statement is causing the problem. Only you know the statement that is causing the problem because it tells you the line number where the problem is. – camickr Nov 10 '16 at 15:56
  • BTW - *"Can you please help?"* is a vague question. Questions on SO should be specific, like *"Why is this exception occurring?"* or *"How would we go about fixing this exception?"*. Drop the 'please' in future & be specific about what information you are requesting of people answering. – Andrew Thompson Nov 10 '16 at 18:12

1 Answers1

2

Once that code is formed into a simpler form that will compile without all the cruft, the first line of the stack trace that relates to the custom (i.e. your) code is:

contentPane.add(btnNewButton, BorderLayout.SOUTH);

BorderLayout.SOUTH is a constraint meant for a BorderLayout, but earlier in the code we see..

contentPane.setLayout(new GridBagLayout()); // I.E. **NOT** a BorderLayout

General advice

  • See What is a stack trace, and how can I use it to debug my application errors? As programmers we will see a lot of exceptions throughout our careers, we need to learn how to solve them, or at least the majority of them. It is only when you know how to solve most exceptions but are not sure why a particular exception is happening in a particular line of code, that you should ask on SO.
  • As mentioned by several people in comments, when in doubt, simplify code to the point where the error shows but all irrelevant code is removed.
  • The only reason I looked into this was because I was especially bored and could not sleep. I'd usually just vote to close and move on to the next problem where the person could manage to create an MCVE. So ..don't rely on someone taking pity on you in future.
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433