GridLayout面板上带有按钮和第二个面板上的JRadioButton的问题

时间:2018-08-30 19:46:58

标签: java swing

我在使用JRadioButton,JCheckBox和其他类似组件时遇到了问题。我有9个按钮的窗格,第二个有JRadioButtons组的窗格。当我将鼠标悬停在JRadioButton上时,或者如果我选择一个,它将出现在第二个buttonPane上。我一直在寻找答案,但我显然不知道该如何命名。

框架代码:

JFrame frame = new JFrame("TicTacToe");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel buttonPane = new JPanel(new GridLayout(3,3));
    PlayButton b1 = new PlayButton();
    buttonPane.add(b1);
    PlayButton b2 = new PlayButton();
    buttonPane.add(b2);
    PlayButton b3 = new PlayButton();
    buttonPane.add(b3);
    PlayButton b4 = new PlayButton();
    buttonPane.add(b4);
    PlayButton b5 = new PlayButton();
    buttonPane.add(b5);
    PlayButton b6 = new PlayButton();
    buttonPane.add(b6);
    PlayButton b7 = new PlayButton();
    buttonPane.add(b7);
    PlayButton b8 = new PlayButton();
    buttonPane.add(b8);
    PlayButton b9 = new PlayButton();
    buttonPane.add(b9);

    JPanel chosePane = new JPanel(new GridLayout(3,1));
    frame.add(chosePane, BorderLayout.EAST);
    chosePane.add(new JLabel("Chose symbol which starts game:  "));
    ButtonGroup group = new ButtonGroup();
    JRadioButton rb1 = new JRadioButton("First");
    JRadioButton rb2 = new JRadioButton("Second");
    group.add(rb1);
    group.add(rb2);
    chosePane.add(rb1);
    chosePane.add(rb2);
    frame.add(buttonPane, BorderLayout.WEST);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

和按钮代码:

public class PlayButton extends JButton

 public PlayButton()
{
    this.setPreferredSize(new Dimension(100,100));
    //this.setBorder();
    repaint();
}

public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(new BasicStroke(5));
    g2.drawLine(4,4,95,95);
    g2.drawLine(4,95,95,4);
    g2.setStroke(new BasicStroke(1));


}

enter image description here

1 个答案:

答案 0 :(得分:1)

public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(new BasicStroke(5));
    g2.drawLine(4,4,95,95);
    g2.drawLine(4,95,95,4);
    g2.setStroke(new BasicStroke(1));
}

自定义绘画时,您需要调用

super.paintComponent(g);

作为该方法中要确保清除背景的第一条语句,否则可能会留下绘画瑕疵。

当然,如果这样做,您将获得JButton的默认绘画。所以也许您需要为自定义绘画扩展JComponent?

此外,请勿在类的构造函数中调用repaint():

  1. 不执行任何操作,因为尚未将组件添加到可见框架中
  2. Swing将确定何时需要重新绘制组件,因此除非您执行动画之类的操作并且需要组件重新绘制自身,否则您很少调用此方法。

编辑:

好像您只是想在按钮上绘制一个“ X”。您实际上不应该为此类扩展JButton。您仅应在添加新功能时扩展组件。

JButton已经支持显示Icon,因此,您真正想要做的就是创建一个可以在按钮上使用的Icon

BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bi.createGraphics();
g2.setColor( Color.BLACK );
g2.setStroke(new BasicStroke(5));
g2.drawLine(4,4,95,95);
g2.drawLine(4,95,95,4);
ImageIcon icon = new ImageIcon( bi );

现在,图标可以在支持图标显示的任何组件上使用:

JButton button = new JButton( icon );
button.setFocusPainted( false );
button.setBorder( null );