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.
 

zap

Mitglied
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?
 

Joose

Top Contributor
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.
 

Harry Kane

Top Contributor
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?
 

zap

Mitglied
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.
 

Harry Kane

Top Contributor
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:

zap

Mitglied
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.
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
C (Swing)GUI-Elemente werden nicht aktualisiert. AWT, Swing, JavaFX & SWT 2
T Alle Swing-Elemente anzeigen AWT, Swing, JavaFX & SWT 9
S JVM von Oracle/Sun soll für AWT/SWING Elemente die die Optimierungen der NVidia Treiber verwenden AWT, Swing, JavaFX & SWT 3
H [gelöst] Swing Elemente verdecken AWT, Swing, JavaFX & SWT 14
S Nachträglich Swing-Elemente in JFrame erzeugen AWT, Swing, JavaFX & SWT 18
F Dynamische Swing Elemente AWT, Swing, JavaFX & SWT 10
S Zugriff auf Elemente funktioniert mit SWING nicht mehr AWT, Swing, JavaFX & SWT 5
J FAQ programmieren, welche Swing-Elemente AWT, Swing, JavaFX & SWT 7
M Java mit Swing - Elemente erst nach klick sichtbar AWT, Swing, JavaFX & SWT 13
Juelin javax.swing in javafx AWT, Swing, JavaFX & SWT 1
A Eclipse 2023 und Swing AWT, Swing, JavaFX & SWT 4
W 2 JTables in einem Swing-Fenster? AWT, Swing, JavaFX & SWT 5
H Swing Componente zur Läufzeit ändern AWT, Swing, JavaFX & SWT 3
B Actionlistener mit Java Swing AWT, Swing, JavaFX & SWT 2
W Gibt es einen "automatischen Listener" in Swing oder JTable oder der ATM-Klasse? AWT, Swing, JavaFX & SWT 14
H Swing Buttons erst nach Klick sichtbar AWT, Swing, JavaFX & SWT 13
ExceptionOfExpectation Anpassung von JKomponentengrößen (Swing) AWT, Swing, JavaFX & SWT 3
thor_norsk AWT SWING Aufgabe AWT, Swing, JavaFX & SWT 7
U Zwei Fragen zu eienr Swing Aufgabe AWT, Swing, JavaFX & SWT 2
M Swing Bilder in Swing anzeigen AWT, Swing, JavaFX & SWT 9
H Swing , GridLayout, Größenbestimmung der Komponenten im Layout AWT, Swing, JavaFX & SWT 8
H Simple Animation mit Swing AWT, Swing, JavaFX & SWT 2
Guybrush Threepwood Einfachste Möglichkeit zum Abspielen eines Videos in Swing AWT, Swing, JavaFX & SWT 4
A Swing ProgressBar über 2 parallel laufende Threads AWT, Swing, JavaFX & SWT 2
M Swing GridLayout AWT, Swing, JavaFX & SWT 2
O return-Statement mit Swing AWT, Swing, JavaFX & SWT 6
O Ein Java-Programm mit Swing steuern AWT, Swing, JavaFX & SWT 1
Monokuma Swing zu JavaFX AWT, Swing, JavaFX & SWT 5
J Swing Slider AWT, Swing, JavaFX & SWT 11
G Thread starten Swing AWT, Swing, JavaFX & SWT 5
G Swing JPasswordField AWT, Swing, JavaFX & SWT 12
L Swing Button Farbe ändern/wechseln AWT, Swing, JavaFX & SWT 2
C Swing AWT GUI Anfänger Aufgabe AWT, Swing, JavaFX & SWT 7
W Inject bei einem Swing Frontend AWT, Swing, JavaFX & SWT 8
L Kommunikation zwischen Klassen / Konstruktoren bei Swing AWT, Swing, JavaFX & SWT 9
M Feldvalidierung swing AWT, Swing, JavaFX & SWT 4
E Swing Componenten werden nach Änderung des display modes verzerrt dargestellt AWT, Swing, JavaFX & SWT 8
D [Swing] Anordnung von Komponenten mit GridLayout Manager AWT, Swing, JavaFX & SWT 13
O Zukunft von Swing und JavaFX ? AWT, Swing, JavaFX & SWT 3
S Swing Fenster State Machine AWT, Swing, JavaFX & SWT 1
T Swing Swing an Bildschirm anpassen AWT, Swing, JavaFX & SWT 3
S Swing Panel wird nicht neu gezeichnet AWT, Swing, JavaFX & SWT 3
M Swing Java Swing/AWT Combobox Bug AWT, Swing, JavaFX & SWT 3
M Swing GUI mittels erben sowie variabler Dateninhalt AWT, Swing, JavaFX & SWT 1
W Swing Multitouch mit Swing AWT, Swing, JavaFX & SWT 6
S Swing-Applikation die ein Numpad nachbildet samt Keybindings..? AWT, Swing, JavaFX & SWT 5
S Swing Java Swing AWT, Swing, JavaFX & SWT 6
Blender3D Problem mit € Symbol Font Gotham Windows 10 Swing AWT, Swing, JavaFX & SWT 11
J Swing oder JavaFX AWT, Swing, JavaFX & SWT 21
D Swing Anwendung ohne JPanel erstellen AWT, Swing, JavaFX & SWT 1
D SQL Statements mit Java Swing benutzen AWT, Swing, JavaFX & SWT 4
Damtonix BufferStrategy flackert (Swing) AWT, Swing, JavaFX & SWT 9
D DatePicker für Java Swing AWT, Swing, JavaFX & SWT 2
B JavaFX oder swing AWT, Swing, JavaFX & SWT 3
T Java Swing - kleines Rechteck unter dem cursor AWT, Swing, JavaFX & SWT 5
L 2D-Grafik Swing paint|paintComponent AWT, Swing, JavaFX & SWT 2
L Swing Größe automatisch anpassen AWT, Swing, JavaFX & SWT 14
G Swing Swing Binding JList funktioniert nicht AWT, Swing, JavaFX & SWT 5
Blender3D Meine Swing Anwendung läuft unter Windows 10 und Ubuntu aber nicht auf Windows 7 AWT, Swing, JavaFX & SWT 16
B Bar Plot in Swing JPanel AWT, Swing, JavaFX & SWT 0
D Swing in Kombination mit JGraphX und JGraphT AWT, Swing, JavaFX & SWT 0
F main-Funktion bei Swing AWT, Swing, JavaFX & SWT 4
S Java Swing Print() method AWT, Swing, JavaFX & SWT 4
S Java Swing auf Windows Phone AWT, Swing, JavaFX & SWT 6
I JAVAFX - Übergabe der Inhalte an eine Scene - Wo ist der Vorteil gegenüber Swing? AWT, Swing, JavaFX & SWT 2
S Manuelles Menu in Swing AWT, Swing, JavaFX & SWT 3
T Custom Window ohne Swing / AWT / FX..?! AWT, Swing, JavaFX & SWT 1
MaxG. Swing Swing Komponenten zur Laufzeit hinzufügen AWT, Swing, JavaFX & SWT 2
Java_RY Bin Ratlos bzgl Malen in Swing AWT, Swing, JavaFX & SWT 5
offi Swing Shuttle List AWT, Swing, JavaFX & SWT 9
I Graph mit Swing zeichnen AWT, Swing, JavaFX & SWT 8
D Swing Swing Objekte sehen im Entwurf anders aus als beim Ausführen AWT, Swing, JavaFX & SWT 3
S Swing & Clean und build Problem AWT, Swing, JavaFX & SWT 12
javampir Swing repaint in JavaFX Anwendung AWT, Swing, JavaFX & SWT 3
K Mit JavaFX angefangen. Lohnt sich Swing? AWT, Swing, JavaFX & SWT 28
B Swing Update Swing Komponente bevor Methode startet. AWT, Swing, JavaFX & SWT 4
B Swing Tabelle(JTable) filtern swing GUI AWT, Swing, JavaFX & SWT 3
M Swing Swing-Widgets und paintComponent() AWT, Swing, JavaFX & SWT 2
B Swing WindowBuilde: Menu -> anderes Panel wechseln AWT, Swing, JavaFX & SWT 1
K eigener button in swing AWT, Swing, JavaFX & SWT 3
A JavaFX DatePicker in Swing beim Start nicht sichtbar AWT, Swing, JavaFX & SWT 2
windl Bufferstrategy in Swing nachstellen AWT, Swing, JavaFX & SWT 0
M Kamera in Java Swing einbinden AWT, Swing, JavaFX & SWT 4
Z Swing Swing und die Progressbar AWT, Swing, JavaFX & SWT 1
J Frage zur objektorentierten Swing Programmierung AWT, Swing, JavaFX & SWT 10
Xanny 2D-Grafik Beginner! Probleme mit Swing, Gprahics class und paint AWT, Swing, JavaFX & SWT 13
F Java Swing Rechteck in JPanel zeichnen AWT, Swing, JavaFX & SWT 7
N Swing Benötige Hilfe um ein Swing Canvas zu speichern AWT, Swing, JavaFX & SWT 4
stylegangsta JButton Fehelr javax.swing.ImageIcon.<init>(Unknown Source) AWT, Swing, JavaFX & SWT 24
RalleYTN Swing JavaFX VideoPlayer in Swing einbetten. Ich komm nicht an die Dimension des Videos! AWT, Swing, JavaFX & SWT 0
T swing läuft nur beding flüssig AWT, Swing, JavaFX & SWT 1
A Sonderzeichen bei Swing AWT, Swing, JavaFX & SWT 3
L DoubleBuffering unter Swing AWT, Swing, JavaFX & SWT 0
N Programm mit Swing und Thread, Figur bewegen sich nicht AWT, Swing, JavaFX & SWT 6
D Java Swing, Label lässt sich nicht mit Checkboxen/Knopf verändern AWT, Swing, JavaFX & SWT 2
J Swing Basics - JButton funktioniert nicht. AWT, Swing, JavaFX & SWT 1
J Swing/AWT | Dynamisch erzeugte Objekte ansprechen AWT, Swing, JavaFX & SWT 1
N JavaFX Umstieg von Swing auf Java FX AWT, Swing, JavaFX & SWT 6
J GUI Anfänger einfaches Program AWT, Swing, JavaFX & SWT AWT, Swing, JavaFX & SWT 3
M Swing Grundlegende Frage zu SWING mit WindowBuilder AWT, Swing, JavaFX & SWT 11

Ähnliche Java Themen

Neue Themen


Oben