将JRadioButton添加到图形对象

时间:2012-10-15 01:58:22

标签: java swing graphics jpanel jradiobutton

我有一个现有的图形对象,我正在尝试在它上面添加一个JRadioButton。程序运行后,按钮不会显示,我认为这是因为没有办法将JPanel添加到Graphics对象。我将JRadiobutton添加到其相应的ButtonGroup,然后我将按钮添加到JPanel,但我还没有看到任何方法在我的图形对象上添加按钮。

有没有办法向图形对象添加单选按钮?我继续使用这个图形对象很重要。让我知道如果看到代码会有所帮助,我想我只需要更好的方法来解决这个问题。

private void redrawTitle(Graphics gc) {
    gc.setColor(Color.yellow);
    gc.fillRect(0, 0, view_width, view_height);
    gc.setFont(largeBannerFont);
    FontMetrics fm = gc.getFontMetrics();
    gc.setColor(Color.red);
    centerString(gc, fm, "Start", 100);
    gc.setColor(Color.blue);
    gc.setFont(smallBannerFont);
    fm = gc.getFontMetrics();
    centerString(gc, fm, "by DavidVee", 160);
    centerString(gc, fm, "a;lskdf", 190);
    gc.setColor(Color.black);
    centerString(gc, fm, "To start, select a skill level.", 250);

    JRadioButton kruskalButton = new JRadioButton("Kruskal");
    ButtonGroup group = new ButtonGroup();
    group.add(kruskalButton);
    JPanel panel = new JPanel();
    panel.add(kruskalButton);

    centerString(gc, fm, "(Press a number from 0 to 9,", 300);
    centerString(gc, fm, "or a letter from A to F)", 320);
    centerString(gc, fm, "v1.2", 350);
}

1 个答案:

答案 0 :(得分:1)

此方法将组件“绘制”到提供的图形上下文中,它不再是组件的“橡皮图章”/“快照”,无法进行交互(无需您自己编码)。

public class PaintControls {

    public static void main(String[] args) {
        new PaintControls();
    }

    public PaintControls() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new PaintPane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public class PaintPane extends JPanel {

        private JRadioButton radioButton = new JRadioButton("I'm painted...");

        @Override
        protected void paintComponent(Graphics g) {

            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g.create();

            Dimension dim = radioButton.getPreferredSize();
            int x = (getWidth() - dim.width) / 2;
            int y = (getHeight() - dim.height) / 2;

            radioButton.setBounds(x, y, dim.width, dim.height);

            g2d.translate(x, y);
            radioButton.printAll(g);
            g2d.translate(-x, -y);

            g2d.dispose();
        }
    }
}

要向父窗格添加新内容,请使用容器的“添加”方法,但不要在paintXxx方法中执行此操作...