Click here to Skip to main content
15,743,609 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi everyone, I've got a small (I hope) yet interesting problem. I have got an assignment today at my university which causes me a headache by now. The job is to design a swing app which uses reflection to create an instance of a class called "Pravokutnik" (never mind the class name) which is a subclass of JPanel. You write the parameters into a JTextField by this order: "className,Color,width,height"
If I want a red "square" (pravokutnik=square) which is 100x100, the input should be "Pravokutnik,red,100,100"
A click of the button bellow should gather info about the class, color and dimensions and create an instance of Pravokutnik and add it into the jPanelMain using FlowLayout. Every new one functions the same way etc.

My problem does not occure until the reflection-raped (:D) square is to be added to the jPanelMain. What happens is that i do not see a new Pravokutnik added to the GUI. EDIT: Tried to play with invalidate() functions called on the jPanelMain, and on the whole JFrame itself. No progress what so ever...
My code:
import java.awt.Color;
import java.lang.reflect.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;

public class Zad1_JavaII extends javax.swing.JFrame {

    private Color c;
    public Zad1_JavaII() {

    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPanelMain = new javax.swing.JPanel();


        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("Unesite parametre oblika:");

        jTextField1.setToolTipText("Oblik unosa parametara: Pravokutnik,boja,xVel,yVel");

        jButton1.setText("Stvori oblik");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
//Beneath this point NetBeans generates some layout code and makes my life miserable using immediate constants like 18,234, 113 etc..instead of declaring those numbers as constants, oh well its not anything I can't live without :)
        java.awt.FlowLayout flowLayout1 = new java.awt.FlowLayout();

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                    .addComponent(jPanelMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE))
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(29, 29, 29)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(jPanelMain, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)


//The event that occurs once the button is clicked and the parameters are straight entered
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        //Made simple now, maybe some more reflection required.
        String parametriString = jTextField1.getText();
        String[] parametri = parametriString.split(",");
        Class boja = Color.class;
        Field f;
        try {
            f = boja.getDeclaredField(parametri[1].toUpperCase());
            c = (Color)f.get(null); 
            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | 
                SecurityException ex) {
            Class pravokutnik = null;
            try {//Full class name specified
                pravokutnik = Class.forName("packageName." + parametri[0]);
            } catch (ClassNotFoundException ex) {
            Constructor ctr;
            try {
                try {
                    //constructor acquired 
                    ctr = pravokutnik.getDeclaredConstructor(Class.forName("java.awt.Color"));
                    Pravokutnik p = null;
                try {
                    p = (Pravokutnik) ctr.newInstance(c);

                    //pretty much hard-coded, will get to it
                    p.setSize(getWidthRefl(parametri[2]), getHeightRefl(parametri[3]));
                } catch (InstantiationException | IllegalAccessException | 
                        IllegalArgumentException | InvocationTargetException ex) {
                    //Shoot me, what am I doing wrong?
                    System.out.println("Panel should be added");
                } catch (ClassNotFoundException ex) {
            } catch (NoSuchMethodException | SecurityException ex) {
    private int getWidthRefl(String s) {
        int width;
        width = Integer.parseInt(s);
        return width;
    private int getHeightRefl(String s) {
        int height;
        height = Integer.parseInt(s);
        return height;
    public static void main(String args[]) {
//Auto generated code through NetBeans
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Zad1_JavaII.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Zad1_JavaII.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Zad1_JavaII.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Zad1_JavaII.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

         * Create and display the form
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Zad1_JavaII().setVisible(true);
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanelMain;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   

Sorry for the long post, I added pretty much all of the code so you can try it out yourself.
Updated 27-Oct-12 2:07am
Sergey Alexandrovich Kryukov 25-Oct-12 16:23pm    
Probably, "pravo" means "right", "kut" - "corner", "hideout", "place", "n-" and "-ik" are suffixes used to form a noun based on characteristic features, so the whole thing should mean "rectangular shape", and, in this context "kut" means "angle". It took me some time to figure it out. Am I close? Then I don't know why you call it "square", not "rectangular"... :-)
dsagner 25-Oct-12 17:45pm

Some 5 second research made me laugh :D.
Sergey Alexandrovich Kryukov 25-Oct-12 21:42pm    
This is about a square being a rectangle, but I'm talking about rectangle being a square -- it is not.
dsagner 25-Oct-12 17:06pm    
Yes Sergey, you are absolutely right :). Remarkable job, never thought that not changing the whole naming system to English based words would set a problem for the programmer society :D. A name is a name, what is behind it matters. Yet I am impressed! The thing with "square" is that I have a huge English vocabulary, just sometimes it's more simple to think of a rectangular shape as a square, so I use that one before the long word :D. But...can you help me :D?
Sergey Alexandrovich Kryukov 25-Oct-12 21:57pm    
Thank you very much. This is fun to do such exercises based solely on linguistic intuition which is in turn is based on my very limited knowledge of languages. I think I never saw Croatian texts before.

About your problem -- sorry, I never used Swing. I happened to help to fix Java problems even though I did not use Java for some decade. I would advise to move the pravokutnic into some obvious position and on top of Z-order to make sure it is properly inserted, and then take care about layout -- to isolate problems and make one step at a time. One problem of your code is that you use a number of immediate constants like 18, 345, 113. This thing is very bad for support and makes development messed up. Better declare them as explicit constant in some place, to start with, so you could play with them. Also, make sure your constants is easy to understand semantically, and they are logically fully independent. If one constant can be calculated based on 3 others, but you still define it as a constant, you will get problems. If something can be calculated, calculate it, never declare as constant. And of course, use the debugger in case of slightest concern of your run time behavior.

Just basic ideas.

Good luck,

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900