kakuro gui布局网格与矩形

时间:2014-06-20 08:37:29

标签: java user-interface puzzle

我是Java图形的新手,我需要一些帮助。我正在尝试为游戏kakuro创建一个gui。在这里,您可以看到电路板的外观图像http://en.wikipedia.org/wiki/Kakuro。我已经有了一些代码来创建带有矩形的网格,但我不知道我究竟能在矩形的中心填充数字,最重要的是我如何在对角线上分割一些矩形,并在需要放置的地方放置一条线其中两个不同的数字与示例相同?

    import java.awt.Graphics;
    import javax.swing.JComponent;
    import javax.swing.JFrame;

    class Grid extends JComponent {
    public void paint(Graphics g) {
    int width=30;
    int height=30;    
    for(int x=0;x<10;x++)
    {
        for(int y=0 ;y < 10;y++)
        {
            // create rectangles
            g.drawRect(x*width,y*height,width,height);
            // Fill in values. However, how to make it in the centre?
            g.drawString("2", x*width,y*height);
        }
    }
   }
  }

   public class Cube {

   public static void main(String[] a) {
    JFrame window = new JFrame();
    window.setSize(200,200);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new Grid());
    window.setVisible(true);
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用JLabel

JButton上使用一对BorderLayout
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class KakuroCorner {

    private JFrame frame;
    private JButton myButton1;
    private JLabel myButton1_Label_E;
    private JLabel myButton1_Label_S;

    public KakuroCorner() {
        myButton1_Label_E = new JLabel("3");
        myButton1_Label_E.setHorizontalAlignment(JLabel.CENTER);
        myButton1_Label_E.setForeground(Color.white);

        myButton1_Label_S = new JLabel("45");
        myButton1_Label_S.setHorizontalAlignment(JLabel.CENTER);
        myButton1_Label_S.setForeground(Color.white);

        myButton1 = new JButton();
        myButton1.setBackground(Color.black);
        myButton1.setLayout(new BorderLayout());
        myButton1.add(myButton1_Label_E, BorderLayout.EAST);
        myButton1.add(myButton1_Label_S, BorderLayout.SOUTH);
        myButton1.setEnabled(false);

        frame = new JFrame();
        frame.add(myButton1);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() { new KakuroCorner(); }
        });
    }
}