2012-03-23 60 views
0

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

My game

这些是9个JPanels与自定义图中,它们中的每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); 
} 

回答

2

当对子组件的更改需要重绘部分面板时,只需绘制该组件重叠的区域。当你做g.getClipBounds()时,你正在绘制该区域,而不是整个面板的边界。您可能只想使用getWidth()getHeight()

+0

啊,当然。现在我也学到了一些关于java绘画的新东西;)谢谢! – 2012-03-23 20:25:08

+0

+1我不知道g.getClipBounds()在做什么。 – david 2012-03-23 20:35:28

0

我不知道为什么,但添加一个ActionListener迫使面板的重绘按钮似乎帮助:

rotateLeft.addActionListener(new ActionListener() { 

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

}); 

只要我按住按钮的线是不可见的,但是当actionListener被触发,然后行被重绘。

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

+0

这种方法很有效,但是这种方法很有效;我的代码的问题是,他在错误的区域重新绘制,你的修复是事后重绘正确的区域,而不是在第一个地方画错误的区域:) – 2012-03-24 00:14:28