简体   繁体   English

如何让我的按钮在其他类中可见

[英]How can i make my buttons visible in other classes

I'm writing simple d&d dice manager for practice, and I'm wondering how can i get access to my buttons outside of their own class:我正在编写简单的 d&d 骰子管理器以进行练习,我想知道如何在他们自己的课程之外访问我的按钮:

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我想在 DandDice 类中访问例如 d4

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.该逻辑属于 Buttoner 类的构造函数。

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. JFrame 只是一个容纳子组件的容器。 You should not have any application logic in the class that creates the frame.在创建框架的类中不应该有任何应用程序逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM