1

我有一个现有的图形对象,我试图在它上面添加一个 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);
}
4

1 回答 1

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方法中执行此操作...

于 2012-10-15T02:52:14.340 回答