【发布时间】:2021-10-23 20:42:38
【问题描述】:
这几天在学Java,我的第一个项目是做一个“围棋板”,9*9的行列,在十字路口放黑白石子。
我创建了一个 9 * 9 行和列的板,现在我必须使用 JButton 组件创建黑白石头。
除了第一行按钮的颜色、大小和位置 (setLayout) 之外,我无法将按钮变成圆形并将石头放在交叉点上。
通过多次搜索相关指南,我注意到有一些我不熟悉的独特结构用于创建和设计按钮。
现在我的问题来了 - 我需要创建什么代码结构才能生成一个圆形按钮,大小为 65 * 65,黑色或白色?我需要为此创建一个新课程吗?我应该如何以及在哪里集成JPanel?
public class Main {
public static void main(String[] args) {
Board board = new Board(900, 900, "Go board");
}
}
import java.awt.*;
import javax.swing.*;
public class Board extends JPanel {
private int width;
private int height;
private String title;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Board(int width, int height, String title) {
super();
this.width = width;
this.height = height;
this.title = title;
this.initBoard();
}
public Board() {
super();
}
public void initBoard() {
JFrame f = new JFrame(this.getTitle());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// f.getContentPane().setBackground(Color.getHSBColor(25, 75, 47));
f.setSize(this.getWidth(), this.getHeight());
// f.setLocation(550, 25);
f.add(this, BorderLayout.CENTER);
f.setVisible(true);
JButton stone = new JButton(" ");
f.add(stone);
f.setLayout(new FlowLayout());
stone.setBackground(Color.BLACK.darker());
stone.setBorder(BorderFactory.createDashedBorder(getForeground()));
stone.setPreferredSize(new Dimension(65, 65));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 10; i++) {
g.drawLine(0, 10 + (i * ((this.getWidth() - 20) / 9)), this.getWidth(),
10 + (i * ((this.getWidth() - 20) / 9)));
g.drawLine(10 + (i * ((this.getHeight() - 20) / 9)), 0, 10 + (i * ((this.getHeight() - 20) / 9)),
this.getHeight());
}
}
}
在上传帖子之前,我阅读了以下帖子:
- Design Button in Java (like in CSS)
- How can I set size of a button?
- Java: JButton with custom Shape: Fill with Metal Look and Feel Gradient
- How to Use Borders
- Java JButton
- How to use
setUImethod injavax.swing.JButton
注意:我不想访问解释如何制作“围棋板”的帖子,在这种情况下的学习过程是我的目标。
【问题讨论】:
-
通常,您使用普通的 Java getter / setter 类创建围棋棋盘的逻辑模型。您使用绘图 JPanel 在 GUI 中创建围棋棋盘并绘制圆圈来表示棋子。 Oracle 教程Creating a GUI With Swing 将向您展示创建 Swing GUI 的步骤。跳过 Netbeans 部分。
-
使用自定义绘画(覆盖
paintComponent)创建一个圆圈板是一种方法。使用JButtons(或JLables)构建电路板,通常使用GridLayout放置是不同的(参见示例here) -
“我需要创建什么代码结构才能生成圆形按钮,大小为 65 * 65,黑色或白色?” I 'd 改为使用使用圆形图像形成的方形按钮,并删除按钮装饰和边距。对于移除的部分,请参阅this answer。围棋棋盘的网格将由其他 9 个不同的图标组成。每个方向有 4 x
T形状,4 x 角图标,以及所有其余按钮的+图标。所以最终它会是一个 9x9 的按钮网格布局,调整后看起来像...所描述的模型。 -
.. @GilbertLeBlanc 在第一条评论中。 “我需要为此创建一个新类吗?” 不需要。一个普通的旧 Java
JButton就可以了,它只需要根据需要进行调整(使用其现有方法)。 “我应该如何以及在哪里集成JPanel?” 什么?我不确定我是否理解,但游戏板将是(再次标准)JPanel和 9 x 9GridLayout。
标签: java swing user-interface jpanel jbutton