Рисование компонентов на вложенных JPanels (Java) - PullRequest
2 голосов
/ 15 марта 2012

Кто-нибудь знает, как я могу нарисовать круг на JPanel внутри JPanel?

По сути, у меня есть JPanel внутри другого, и я создал новый класс Circle, который расширяет JComponent.Затем я добавил это к одной из панелей и попытался перекрасить, но ничего не отображается.Есть идеи?Вот мой код:

      class Circle extends JComponent 
{       
    @Override     public void paintComponent(Graphics g)
{
        super.paintComponent(g);
        g.drawOval(10,10, 11, 11);
        g.setColor(Color.RED);
        g.fillOval(10,10, 11, 11);                  
  } 
}


public void drawTest()
{
    Circle circle = new Circle();
    circle.setOpaque(false);
    circle.setSize(22, 22);
    circle.setVisible(true);
    circle.setBounds(11,11,11,5);
    jpanel.add(circle); 
    jpanel.repaint();

}

Код работает, когда я добавляю круг на главную панель [добавить (круг)], но отказывается для любых подпанелей.

Ответы [ 2 ]

1 голос
/ 15 марта 2012

Вам нужно переопределить getPreferredSize (...) метод, как вы делаете это с методом paintComponent(...), пусть это будет что-то вроде:

public Dimension getPreferredSize()
{
    return (new Dimension(300, 300));
}

Вот один примерпрограмма для вашей дальнейшей помощи:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TwoButtons
{
    private int x;
    private int y;
    private int count = 0;

    private Timer timer;

    private ActionListener actionTimer; 

    public static void main(String args[])
    {
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                TwoButtons gui = new TwoButtons();
                gui.go();
            }
        };      
        SwingUtilities.invokeLater(runnable);
    }

    public void go()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();

        /*
         * Class Name : 
         * Java Naming Convention says that class names 
         * should be in Pascal Case, i.e. the first
         * letter of the class name should be capitalized
         * and every new word must start with a capitalized 
         * Alphabet.
         * For Example : 
         * public class ClassName{...}
         * ----------------------------------------------------------
         * Variable Name : 
         * Java Naming Convention says that the variable name
         * should be in Camel Case, i.e. the first letter of 
         * the variable name should be small case or _ (underscore)
         * and every new word must start with a capitalized
         * Alphabet.
         * ---------------------------------------------------------
         */
        final MyDraw drawPanel = new MyDraw(70, 70);
        x = drawPanel.getXValue();
        y = drawPanel.getYValue();
        contentPane.add(drawPanel);

        actionTimer = new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {               
                x++;
                y++;
                if (count < 100)
                    drawPanel.setXYValues(x, y, count);
                else if (count == 100)
                    timer.stop();
                count++;
            }
        };

        frame.getContentPane().add(contentPane);
        frame.setSize(300,300);
        frame.setVisible(true);        

        timer = new Timer(40, actionTimer);
        timer.start();
    }
    class MyDraw extends JComponent
    {
        private int x;
        private int y;
        private int count = 0;
        private Timer timer;

        public MyDraw(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        public int getXValue()
        {
            return x;
        }

        public int getYValue()
        {
            return y;
        }

        public void setXYValues(int x, int y, int count)
        {
            this.x = x;
            this.y = y;
            this.count = count;
            repaint();
        }

        public Dimension getPreferredSize()
        {
            return (new Dimension(300, 300));
        }

        public void paintComponent(Graphics g)
        {
            g.setColor(Color.green);
            g.fillOval(x, y, 40, 40);
        }
    }
}
1 голос
/ 15 марта 2012

При расширении JComponent.

нужно написать немало методов.

Если вы расширите JPanel и переопределите метод paintComponent, вам повезет, если ваш класс Circle будет хорошо играть с другими компонентами Swing.

...