Search code examples
javaswingjframeawtjbutton

Maiking buttons visible in other classes


I'm writing simple d&d dice manager for practice, and I'm wondering how can i access my buttons outside of their own class:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

class Buttoner extends JPanel{
public JButton d4, d6, d8, d12, d20, d100;
Buttoner(){
    this.add(d4 = new JButton("d4"));
    this.add(d6 = new JButton("d6"));
    this.add(d8 = new JButton("d8"));
    this.add(d12 = new JButton("d12"));
    this.add(d20 = new JButton("d20"));
    this.add(d100 = new JButton("d100"));
}
}

class Framer extends JFrame {
Framer(){
    int DEFAULT_WIDTH = 200;
    int DEFAULT_HEIGHT = 140;
    this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    this.setVisible(true);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    this.setTitle("D&Dice");
    JButton display = new JButton("0");
    display.setEnabled(false);
    this.add(display, BorderLayout.NORTH);
}
}

public class DandDice extends Framer {
public static void main(String[] args)
{
    Buttoner panel = new Buttoner();
    panel.setLayout(new GridLayout(3, 2));
    Framer ramka = new Framer();
   ramka.add(panel, BorderLayout.SOUTH);
}

}

And I'd like to get acess to for example d4 in DandDice class


Solution

  • Not related to your question but:

    Buttoner panel = new Buttoner();
    panel.setLayout(new GridLayout(3, 2));
    

    The layout manager of the panel should be set BEFORE you add the buttons to the panel.

    That logic belongs in the constructor of your Buttoner class.

    how can i get access to my buttons outside of their own class:

    Not sure why you would want to do that.

    The JFrame is just a container to hold the child components. You should not have any application logic in the class that creates the frame.