【问题标题】:Graphics glitches with JPanel's custom drawing with JButtonsJPanel 使用 JButtons 自定义绘图时出现图形故障
【发布时间】:2012-03-23 19:59:03
【问题描述】:

我有一个 JPanel,它实现了自定义绘图来绘制背景。在此之上,应用程序可以放置 JButton 来检测对 JPanel 某些区域的点击。但是,当用鼠标突出显示(非透明)按钮时,底层 JPanel 的图形变得全都出现故障。

这些是 9 个带有自定义绘图的 JPanel,每个 JPanel 都有 2 个填充 JButton(R 和 L)。右上角的块和看起来像它的块是“新鲜的”。右下角的两个按钮都突出显示,中间的只有“R”等。

我这样创建按钮:

rotatePanel = new JPanel();
        rotatePanel.setOpaque(false);
        GridLayout rotateLayout = new GridLayout(1, 2);
        rotatePanel.setLayout(rotateLayout);

        rotateRight = new JButton("R");
        rotateRight.addActionListener(this);
        rotateRight.setOpaque(false);
        rotateRight.setContentAreaFilled(false);
        rotateRight.setBorderPainted(false);
        rotatePanel.add(rotateRight);

        rotateLeft = new JButton("L");
        rotateLeft.addActionListener(this);
        rotateLeft.setOpaque(false);
        rotateLeft.setContentAreaFilled(false);
        rotateLeft.setBorderPainted(false);
        rotatePanel.add(rotateLeft);

这是我的绘图代码:

            public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Rectangle clipRect = g.getClipBounds();
    clipRect.grow(-4, -4);

    int thirdWidth = clipRect.width/3;
    int thirdHeight = clipRect.height/3;
    for (int x = 0; x < Board.DIM; x++) {
        //Draw the columns
        for (int y = 0; y < Board.DIM; y++) {
            //Draw the rows
            g.drawRect(thirdWidth * x, thirdHeight * y, thirdWidth, thirdHeight);
        }
    }

    g.setColor(Color.BLACK);
    g.drawRect(0, 0, clipRect.width, clipRect.height);
}

【问题讨论】:

    标签: java swing drawing


    【解决方案1】:

    当对子组件的更改需要重新绘制面板的一部分时,只需要绘制与该组件重叠的区域。当您执行g.getClipBounds() 时,您将获得要绘制的区域,而不是整个面板的边界。您可能只想使用getWidth()getHeight()

    【讨论】:

    • 啊,当然。现在我也学到了一些关于java绘画的新知识;)谢谢!
    【解决方案2】:

    我不知道为什么,但是将 ActionListener 添加到强制重绘面板的按钮似乎有帮助:

    rotateLeft.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
            rotatePanel.repaint(); // rotatePanel must be final to be used here
        }
    
    });
    

    只要我按住按钮,线条是不可见的,但是当触发 actionListener 时,线条就会重新绘制。

    您还可以将 MouseListener 用于 rotateLeft 按钮,以强制重绘事件 mousePressed、mouseReleased 和 mouseClicked 上的组件。然后按住鼠标按钮时这些线条也应该可见。

    【讨论】:

    • 这行得通,但有点老套;我的代码的问题是他在不正确的区域重新绘制,您的解决方法是之后在正确的区域重新绘制,而不是一开始就不在错误的区域绘制:)
    猜你喜欢
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多