简体   繁体   English

创建多个类似按钮/面板的正确方法

[英]proper way to create multiple similar buttons/panels

I have the below Code which I tried to do, but it only shows(the minus/plus button) on the last GridLayout (Intelligence stat): 我尝试执行以下代码,但仅在最后一个GridLayout (智能统计)上显示(减号/加号按钮):

JButton plusButton = new JButton("+");
JButton minusButton = new JButton("-");

statStrengthGridPanel = new JPanel(new GridLayout(1,3));
statStrengthGridPanel.add(minusButton);
statStrengthGridPanel.add(new JLabel("10"));
statStrengthGridPanel.add(plusButton);

statConstitutionGridPanel = new JPanel(new GridLayout(1,3));
statConstitutionGridPanel.add(minusButton);
statConstitutionGridPanel.add(new JLabel("10"));
statConstitutionGridPanel.add(plusButton);

statDexterityGridPanel = new JPanel(new GridLayout(1,3));
statDexterityGridPanel.add(minusButton);
statDexterityGridPanel.add(new JLabel("10"));
statDexterityGridPanel.add(plusButton);

statIntelligenceGridPanel = new JPanel(new GridLayout(1,3));
statIntelligenceGridPanel.add(minusButton);
statIntelligenceGridPanel.add(new JLabel("10"));
statIntelligenceGridPanel.add(plusButton);

I know I can do something like I did for the Panel names(have multiple ones), but I do not want to do that for the Panels in the first place. 我知道我可以为面板名称做一些事情(有多个名称),但是我不想一开始就为面板名称做。 I am trying to use best practice and don't want my code to be repetitive. 我正在尝试使用最佳实践,并且不希望我的代码重复。 Any suggestions?? 有什么建议么??

The goal is to have 4 stats, to assign points to, with decrement and increment buttons(I decided against sliders). 我们的目标是要有4个统计数据,并使用递减和递增按钮来分配点(我根据滑块决定)。 Eventually I will have their have upper and lower limits, decrement the "unused" label, and all of that good stuff, but I just want not to be repetitive. 最终,我将使它们有上限和下限,减少“未使用”的标签,以及所有这些好东西,但我只是不想重复。

The reason why its not working is that you are adding the same buttons to different gridpanels. 它不起作用的原因是您将相同的按钮添加到不同的网格面板。 I think that you need to create new ones for every place you want to see them. 我认为您需要为每个想要看到它们的地方创建新的。 Try something like 尝试类似

statStrengthGridPanel = new JPanel(new GridLayout(1,3));
statStrengthGridPanel.add(new JButton("-"));
statStrengthGridPanel.add(new JLabel("10"));
statStrengthGridPanel.add(new JButton("+"));

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

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