[英]Java Swing Die drawing
我正在繪制一個模具,當您單擊它並重繪它時,它會模擬一個新的隨機滾動。 我有一個帶有靜態最終字段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();
}
}
..什么是繪制點的更有效方法。
使用表示Die Faces的現有Unicode字符。 它們從代碼點9856開始。
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.