我正在绘制一个骰子,当您单击它并重新绘制它时,它会模拟新的随机滚动。我有一个带有静态最终字段 middleX 和 middleY 的 Die 类,我正在计算这些字段中其他点的坐标。
我的第一个问题是什么是更有效的绘制点的方法,因为我正在切换新生成的数字并且存在大量代码重复。最后,我的最后一个问题是,是否有一种方法可以在不直接使用 die 对象的情况下调用 mouseListener 中 Die 类中的方法。我希望 mouseListener 中的代码能够处理点击,无论点击哪个骰子。
private class MyAdapter extends MouseAdapter
{
public void mouseClicked(MouseEvent event)
{
die.updateVal((int) Math.floor(Math.random()*6) +1);
die.repaint();
}
}
最佳答案
..what is an even more efficient way of drawing the dots..
使用表示骰子面的现有 Unicode 字符。它们从代码点 9856 开始。E.G.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class DieRoll {
private JComponent ui = null;
int dieStart = 9856;
JLabel dieLabel = new JLabel();
Random r = new Random();
DieRoll() {
initUI();
}
public void initUI() {
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
Font dieFont = null;
Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
String firstDie = new String(Character.toChars(dieStart));
for (Font font : fonts) {
if (font.canDisplayUpTo(firstDie)<0) {
// the first font that will render the Die Faces
dieFont = font;
break;
}
}
dieLabel.setFont(dieFont.deriveFont(200f));
ui.add(dieLabel);
setDie();
Action rollDie = new AbstractAction("Roll the Die") {
@Override
public void actionPerformed(ActionEvent e) {
setDie();
}
};
ui.add(new JButton(rollDie), BorderLayout.PAGE_START);
}
private void setDie() {
StringBuilder sb = new StringBuilder("<html><body>");
// convert the numbers to HTML Unicode characters
sb.append(String.format("&#%1s; ", dieStart + r.nextInt(6)));
sb.append(String.format("&#%1s; ", dieStart + r.nextInt(6)));
dieLabel.setText(sb.toString());
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
DieRoll o = new DieRoll();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
关于Java Swing Die绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42361806/