Swing Swing: Elemente werden doppel/verschoben gezeichnet, sind teils unsichtbar etc...

zap

Mitglied
Hallo,

ich habe ein paar Probleme mit dem hinzufügen von JPanels. Ich habe ein Frame, darin liegt ein JPanel (nennen wir es DiceBox). Der DiceBox sollen jetzt mehrere Dices hinzugefügt werden. Dice ist eine Klasse, die von JPanel erbt, und allerlei Elemente wie Textfelder, Buttons etc enthält.
Also MyFrame ---> DiceBox ---> mehrere Dices

Ich habe NetBeans gui-builder benutzt, d.h. der Code wurde größtenteils automatisch für mich erzeugt.

Schon bei nur einem Dice, der hinzugefügt wird, gibt es Probleme. Es wird links der Dice korrekt angezeigt, hat jedoch keinerlei Funktion. Gleichzeitig sieht man weiter rechts den Button erneut (es wurde aber nur einer hinzugefügt!), dieser funktioniert. Die übrigen (funktionistüchtigen) Elemente bei dem ominösen Würfel auf der rechten Seite tauchen erst durch Hovern auf.
1dice.PNG

Füge ich einen zweiten Dice hinzu, sieht es bereits im Editor komisch aus. Bei der Positionierung wird der zweite Würfel noch richtig angezeigt, sobald man loslässt sieht man nur noch diese gelben Linien im Editor:
editor2dices.PNG

Startet man dann das Programm, kommt soetwas bei raus, wobei der linke wieder keine Funktion hat und bei den beiden rechten die Elemente erst durch Hovern auftauchen.
2dices.PNG

Eigentlich sollen die beiden nebeneinander positioniert werden. Ich habe probiert, DiceBox verschiedene LayoutManager zu geben, aber es war immer dasselbe.

Der Code von MyFrame (komplett mit dem gui-builder gemacht):
Java:
package unnamed;

import dice.DiceUi;
import java.awt.EventQueue;

public class NewJFrame extends javax.swing.JFrame {

    public DiceUi dice1;
   
    public NewJFrame() {
        dice1 = new DiceUi();
        initComponents();
       // pnlDiceBox.add(dice1);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        pnlDiceBox = new javax.swing.JPanel();
        diceUi1 = new dice.DiceUi();
        diceUi2 = new dice.DiceUi();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        pnlDiceBox.add(diceUi1);
        pnlDiceBox.add(diceUi2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlDiceBox, javax.swing.GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(281, Short.MAX_VALUE)
                .addComponent(pnlDiceBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url]
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private dice.DiceUi diceUi1;
    private dice.DiceUi diceUi2;
    private javax.swing.JPanel pnlDiceBox;
    // End of variables declaration                   
}

Und hier der Code des Würfels. Dieser ist auch mit dem Builder entstanden, enthällt aber noch ein paar zusätzliche Variablen und EventListener. Das sollte für das Problem allerdings irrelevant sein.
Java:
package dice;

import java.util.ArrayList;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class DiceUi extends javax.swing.JPanel {

//CONSTRUCTORS----------------------CONSTRUCTORS----------------------CONSTRUCTORS----------------------CONSTRUCTORS
    /* Create the panel */
    public DiceUi() {
        count = 1;
        mode = 6;
        bonus = 0;
        name = "Dice " + id;
        initComponents();
        countBox.getDocument().addDocumentListener(
                new DocumentListener() {

                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        updateCount();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        updateCount();
                    }

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        updateCount();
                    }
                });
        modeBox.getDocument().addDocumentListener(
                new DocumentListener() {

                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        updateMode();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        updateMode();
                    }

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        updateMode();
                    }
                });
        bonusBox.getDocument().addDocumentListener(
                new DocumentListener() {
                    @Override
                    public void changedUpdate(DocumentEvent e) {
                        updateBonus();
                    }

                    @Override
                    public void removeUpdate(DocumentEvent e) {
                        updateBonus();
                    }

                    @Override
                    public void insertUpdate(DocumentEvent e) {
                        updateBonus();
                    }
                });
    }
//END CONSTRUCTORS

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        lblHeadline = new javax.swing.JLabel();
        lblCalculation = new javax.swing.JLabel();
        countBox = new javax.swing.JTextField();
        lblD = new javax.swing.JLabel();
        modeBox = new javax.swing.JTextField();
        lblPlus = new javax.swing.JLabel();
        bonusBox = new javax.swing.JTextField();
        lblEquals = new javax.swing.JLabel();
        lblResult = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtSingleResults = new javax.swing.JTextArea();
        btnRoll = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        lblHeadline.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblHeadline.setText("Dice 1");

        lblCalculation.setText("10D6 + 15 = 100");

        countBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                countBoxActionPerformed(evt);
            }
        });

        lblD.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblD.setText("D");

        modeBox.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblPlus.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblPlus.setText("+");

        bonusBox.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblEquals.setText("=");

        lblResult.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblResult.setForeground(new java.awt.Color(255, 0, 0));
        lblResult.setText("100");

        txtSingleResults.setColumns(20);
        txtSingleResults.setRows(5);
        jScrollPane1.setViewportView(txtSingleResults);

        btnRoll.setBackground(new java.awt.Color(255, 0, 51));
        btnRoll.setText("Roll dice(s)!");
        btnRoll.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        btnRoll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRollActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lblHeadline)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(countBox, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblD)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(modeBox, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblPlus)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bonusBox, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblEquals)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblResult)
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblCalculation)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnRoll))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblHeadline)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCalculation)
                    .addComponent(btnRoll))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(countBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblD)
                    .addComponent(modeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblPlus)
                    .addComponent(bonusBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblEquals)
                    .addComponent(lblResult)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>                       

    private void countBoxActionPerformed(java.awt.event.ActionEvent evt) {                                         
        System.out.println("hhrdgd");
    }                                       

    private void btnRollActionPerformed(java.awt.event.ActionEvent evt) {                                       
        if (!error) {
            DiceMath.rollDices(resultList, count, mode);
            result = DiceMath.calculateResult(resultList,
                    bonus);
            System.out.println("Result for ID: " + id + ": "
                    + result);
        }
        lblCalculation.setText(resultText(true));
        txtSingleResults.setText(singleResults(true));
    }                                       

    //METHODS--------------------METHODS--------------------METHODS--------------------METHODS--------------------METHODS
    /**
     * Updates count to the value typed into the countBox textfield.
     */
    private void updateCount() {
        String t = countBox.getText();
        try {
            error = false;
            count = Integer.parseInt(t);
            lblCalculation.setText(resultText(true));
        } catch (NumberFormatException e) {
            System.out.println("Only numbers permitted.");
            error = true;
        }
    }

    /**
     * Updates mode to the value typed into the modeBox textfield.
     */
    private void updateMode() {
        String t = modeBox.getText();
        try {
            error = false;
            mode = Integer.parseInt(t);
            lblCalculation.setText(resultText(true));
        } catch (NumberFormatException e) {
            System.out.println("Only numbers permitted.");
            error = true;
        }
    }

    /**
     * Updates bonus to the value typed into the bonusBox textfield.
     */
    private void updateBonus() {
        String t = bonusBox.getText();
        try {
            error = false;
            bonus = Integer.parseInt(t);
            lblCalculation.setText(resultText(true));
        } catch (NumberFormatException e) {
            System.out.println("Only numbers permitted.");
            error = true;
        }
    }

//END METHODS
//STRINGS----------------------STRINGS----------------------STRINGS----------------------STRINGS----------------------STRINGS
    /**
     * String which shows to calculation (count, mode, bonus and the result).
     *
     * @param showResult Decides whether the result should be shown or not
     * @return Returns the whole calculation or "ERROR", if the calculation can
     * not be done.
     */
    public String resultText(boolean showResult) {
        /* if there is no error in textfields */
        if (!error) {
            if (showResult) {
                return count + "D" + mode + " + " + bonus + " = "
                        + result;
            } else {
                return count + "D" + mode + " + " + bonus + " = ";
            }
        } /* if there is an error in one textfield */ else {
            return "ERROR";
        }
    }

    /**
     * String of all single results plus the bonus.
     *
     * @param organize Decides, if results should be ordered or not
     * @return Returns all single results in a String
     */
    public String singleResults(boolean organize) {
        if (!error) {
            /* organize results, if mode is activated */
            if (organize) {
                DiceMath.organizeResults(resultList, mode);
            }

            String singleResults = "Single results: (";
            for (int result = 0; result < resultList.size(); result++) {
                /* last result: */
                if (result == resultList.size() - 1) {
                    singleResults = singleResults
                            + resultList.get(result) + ") + "
                            + bonus;
                } /* results */ else {
                    singleResults = singleResults
                            + resultList.get(result) + ", ";
                }
            }

            return singleResults;
        } else {
            return "ERROR";
        }
    }
//END STRINGS 

//ATTRIBUTES------------------ATTRIBUTES------------------ATTRIBUTES------------------ATTRIBUTES------------------ATTRIBUTES
    /**
     * Stores the result of every dice-roll. Has as many entrys as count.
     */
    public ArrayList<Integer> resultList = new ArrayList<>();
    private int result;
    private int count; //    how many dices
    private int mode; //   which kind of dice
    private int bonus;
    private int id;
    private String name;
    private int x, y, w, h;
    private boolean error;

    static private int diceCount; //   counts the amount of dice-engines used

    // Variables declaration - do not modify                     
    private javax.swing.JTextField bonusBox;
    private javax.swing.JButton btnRoll;
    private javax.swing.JTextField countBox;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCalculation;
    private javax.swing.JLabel lblD;
    private javax.swing.JLabel lblEquals;
    private javax.swing.JLabel lblHeadline;
    private javax.swing.JLabel lblPlus;
    private javax.swing.JLabel lblResult;
    private javax.swing.JTextField modeBox;
    private javax.swing.JTextArea txtSingleResults;
    // End of variables declaration                   
//END ATTRIBUTES
}

Ich habe wirklich garkeine Ahnung, warum sich das so buggy verhält :noe: Würde mich freuen, wenn ihr mir weiterhelfen könnt.
 
Ich habs vom gui-builder generieren lassen und nochmal nachgeguckt, das Element ist nur einmal drin. Es wird einmal der horizontalen Gruppe und dann der vertikalen Gruppe zugeordnet. Kenne mich mit GroupLayouts nicht so gut aus, aber fügt man das da nicht beiden hinzu?
 
Soweit ich die GroupLayouts kenne muss man dort die Element 2x hinzufügen.
Damit definiert man jeweils die horizontale Position als auch die vertikale Position.
 
Ich habe gerade die beiden Codeschnipsel zu einem Quelltext zusammengeschnitten. Die Klasse DiceUi ist jetzt nicht mehr public. Ausserdem habe ich alle Verweise auf DiceMath rausgeschmissen.
Ergebnis: der Code läuft ohne visuelle Artefakte.
Kann es sein, dass im Hintergrund eine Exception geworfen wird, so daß bestimmte Programmteile nicht ausgeführt werden?
 
Hmm, wenn ich das public rausnehme, dann kommt bei MyFrame ein Fehler: "cannot be accessed from outside package".

Was kann das damit denn zu tun haben? Ich habe noch nie mit nicht öffentlichen Klassen gearbeitet. Ich habs jetzt erstmal ins selbe Package geschoben, ums zum Laufen zu kriegen, aber der Fehler tritt weiterhin auf.

In der Konsole wurde zumindest kein Fehler geworfen und die Berechnungen (nichts anderes macht DiceMath) funktionieren auch einwandfrei.
 
Bei mir läuft folgender Code einwandfrei. Den ganzen Listener-Kram habe ich mal entfernt.
Java:
package swingawt.dice;

import java.awt.EventQueue;
import java.util.ArrayList;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


public class DiceMain extends javax.swing.JFrame {

    public DiceUi dice1;

    public DiceMain() {
        dice1 = new DiceUi();
        initComponents();
// pnlDiceBox.add(dice1);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        pnlDiceBox = new javax.swing.JPanel();
        diceUi1 = new DiceUi();
        diceUi2 = new DiceUi();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        pnlDiceBox.add(diceUi1);
        pnlDiceBox.add(diceUi2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(pnlDiceBox, javax.swing.GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(281, Short.MAX_VALUE)
                        .addComponent(pnlDiceBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see <a href="http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html" target="_blank">How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)</a>
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DiceMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DiceMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DiceMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DiceMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
//</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DiceMain().setVisible(true);
            }
        });
    }

// Variables declaration - do not modify
    private DiceUi diceUi1;
    private DiceUi diceUi2;
    private javax.swing.JPanel pnlDiceBox;
// End of variables declaration
}

class DiceUi extends javax.swing.JPanel {

//CONSTRUCTORS----------------------CONSTRUCTORS----------------------CONSTRUCTORS----------------------CONSTRUCTORS
/* Create the panel */
    public DiceUi() {
        count = 1;
        mode = 6;
        bonus = 0;
        name = "Dice " + id;
        initComponents();
    }
//END CONSTRUCTORS

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        lblHeadline = new javax.swing.JLabel();
        lblCalculation = new javax.swing.JLabel();
        countBox = new javax.swing.JTextField();
        lblD = new javax.swing.JLabel();
        modeBox = new javax.swing.JTextField();
        lblPlus = new javax.swing.JLabel();
        bonusBox = new javax.swing.JTextField();
        lblEquals = new javax.swing.JLabel();
        lblResult = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtSingleResults = new javax.swing.JTextArea();
        btnRoll = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        lblHeadline.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblHeadline.setText("Dice 1");

        lblCalculation.setText("10D6 + 15 = 100");

        lblD.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblD.setText("D");

        modeBox.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblPlus.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblPlus.setText("+");

        bonusBox.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblEquals.setText("=");

        lblResult.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblResult.setForeground(new java.awt.Color(255, 0, 0));
        lblResult.setText("100");

        txtSingleResults.setColumns(20);
        txtSingleResults.setRows(5);
        jScrollPane1.setViewportView(txtSingleResults);

        btnRoll.setBackground(new java.awt.Color(255, 0, 51));
        btnRoll.setText("Roll dice(s)!");
        btnRoll.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[]{"Item 1", "Item 2", "Item 3", "Item 4"}));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(lblHeadline)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(countBox, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lblD)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(modeBox, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lblPlus)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(bonusBox, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lblEquals)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(lblResult)
                                        .addGap(18, 18, 18)
                                        .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(lblCalculation)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(btnRoll))
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblHeadline)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(lblCalculation)
                                .addComponent(btnRoll))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(countBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblD)
                                .addComponent(modeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblPlus)
                                .addComponent(bonusBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblEquals)
                                .addComponent(lblResult)
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(9, 9, 9)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>



//METHODS--------------------METHODS--------------------METHODS--------------------METHODS--------------------METHODS
    /**
     * Updates count to the value typed into the countBox textfield.
     */
//END STRINGS

//ATTRIBUTES------------------ATTRIBUTES------------------ATTRIBUTES------------------ATTRIBUTES------------------ATTRIBUTES
    /**
     * Stores the result of every dice-roll. Has as many entrys as count.
     */
    public ArrayList<Integer> resultList = new ArrayList<Integer>();
    private int result;
    private int count; // how many dices
    private int mode; // which kind of dice
    private int bonus;
    private int id;
    private String name;
    private int x, y, w, h;
    private boolean error;

    static private int diceCount; // counts the amount of dice-engines used

// Variables declaration - do not modify
    private javax.swing.JTextField bonusBox;
    private javax.swing.JButton btnRoll;
    private javax.swing.JTextField countBox;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblCalculation;
    private javax.swing.JLabel lblD;
    private javax.swing.JLabel lblEquals;
    private javax.swing.JLabel lblHeadline;
    private javax.swing.JLabel lblPlus;
    private javax.swing.JLabel lblResult;
    private javax.swing.JTextField modeBox;
    private javax.swing.JTextArea txtSingleResults;
// End of variables declaration
//END ATTRIBUTES
}
 
Zuletzt bearbeitet:
Woran es letztendlich lag, kann ich nicht sagen. Ich habe den Code, den du gepostest hast, für das UI genommen. Die Funktionalität habe ich komplett in eine andere Klasse ausgelagert (davor waren es nur die mathematischen Berechnungen, die Variablen z.B., die davon betroffen sind, waren immer noch in diceUi).

So funktioniert es auf jeden Fall und ist ein wenig übersichtlicher.
 

Neue Themen


Zurück
Oben