java - 将滚动条添加到 jframe 网格

标签 java swing graphics awt

我有一个带有矩形的网格,我将在其中填充值。但是,根据输入,网格可能会很大,所以我想向图像添加滚动条选项。下面的代码似乎没有达到我想要的效果?如有任何帮助,我们将不胜感激。

   class Cube extends JComponent 
   {
public void paint(Graphics g) 
{   

    for (int i = 0; i < 10; i++) 
    {
        for (int j = 0; j < 10; j++) 
        {
            g.setColor(Color.GRAY);
            g.fillRect(i*40, j*40, 40, 40);
        }
    }

    for (int i = 0; i < 50; i++) 
    {
        for (int j = 0; j < 50; j++) 
        {
            g.setColor(Color.BLACK);
            g.drawRect(i*40, j*40, 40, 40);
        }
    }

}
public static void main(String[] a) 
{
    // CREATE SCROLLBAR
    JScrollPane scroller = new JScrollPane();
    JFrame window = new JFrame();
    window.setSize(200,200);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().add(new Cube());
    //ADD THE SCROLLBAR 
    window.getContentPane().add(scroller, BorderLayout.CENTER);
    window.setVisible(true);
}

}

最佳答案

一些提示:

  1. 您需要将 Cube 添加到滚动 Pane 。您可能会发现this tutorial about scrollpane有帮助。
  2. You should use event dispatcher thread when using swing.

我将你的程序重写如下。

class Cube extends JComponent
{
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                g.setColor(Color.GRAY);
                g.fillRect(i*40, j*40, 40, 40);
            }
        }

        for (int i = 0; i < 50; i++)
        {
            for (int j = 0; j < 50; j++)
            {
                g.setColor(Color.BLACK);
                g.drawRect(i*40, j*40, 40, 40);
            }
        }   
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(1000, 1000);
    }

    public static void main(String[] a){
        // use event dispatcher thread
        EventQueue.invokeLater(
            new Runnable() {
                public void run() {
                    Cube cube = new Cube();
                    JScrollPane scroller = new JScrollPane(cube);
                    JFrame window = new JFrame();
                    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    // set the content pane
                    window.setContentPane(scroller);
                    window.pack();
                    window.setVisible(true);
                }
        });
    }
}

关于java - 将滚动条添加到 jframe 网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24736653/

相关文章:

java - 如何创建获取 4 个数字并返回最大数字的 max 方法?

java - Eclipse Alfresco 中的快速应用程序开发(热重载)

java - "java $SOME_ENV_VAR -jar application.jar"和 "java -jar $SOME_ENV_VAR application.jar"之间的区别

java - JTable多行选择只选择一列

java - 使 JFrame 不重绘

r - 如何将对象传递给 R mtext()?

java - 提高网络抓取效率

Java Swing ActionListener 不工作并停止构造函数

ios - 如何将上下文旋转90度并将原点设置为左上角?

java - JButtons 在 paintComponent() 中起作用