gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:51:55 25 4
gpt4 key购买 nike

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

框架代码:

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

最佳答案

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 );

关于java - 带有按钮的 GridLayout 面板和第二个面板上的 JRadioButton 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com