Search code examples
javaswingjpaneljava-threads

Add graphics on a Jpanel Object with Thread


I want to add graphics in this program. The graphics will be drawn on "drawPanel" object. I have to use thread here.

No idea for drawing in a Jpanel object with thread. What will be the good efficient way to draw graphics on that Jpanel Object?

How thread and paintComponent() going to interact.Thanks.

Code:

public class LinearSearch extends JPanel{

    private final Font LABEL_FONT = new Font("courier", Font.BOLD, 30);

    private JPanel mainPanel;
    private JPanel centerPanel;
    private JPanel inputPanel;
    private JPanel drawPanel;

    private JLabel lblTitle;
    private Button btnBack;

    public LinearSearch(JPanel mainPanel) {
        this.mainPanel = mainPanel;

        setBackground(Color.WHITE);

        initialize_All();
    }

    private void initialize_All() {
        lblTitle = new JLabel("\"Linear Search\"", SwingConstants.CENTER);
        lblTitle.setFont(LABEL_FONT);

        ///Center Panel
        centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout());

        ///Input Panel
        inputPanel = new JPanel();
        inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS));


        ///Draw Panel
        drawPanel = new JPanel();
        drawPanel.setLayout(new FlowLayout());

        /// I want to add graphics on this drawPanel Jpanel

        btnBack = new Button("Back");
        btnBack.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                setVisible(false);
                removeAll();

                mainPanel.add(new CatagoriesMenu(mainPanel));
            }
        });


        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        setLayout(new BorderLayout(10, 10));

        add(lblTitle, BorderLayout.PAGE_START);
        add(centerPanel, BorderLayout.CENTER);
        add(btnBack, BorderLayout.PAGE_END);

        centerPanel.add(inputPanel, BorderLayout.PAGE_START);
        centerPanel.add(drawPanel, BorderLayout.CENTER);

    }
}

Solution

  • I must need to add graphics on "drawPanel" Jpanel Object.

    Then you need to extend the JPanel and override the paintComponent(...) method to do your custom painting.

    Read the section from the Swing tutorial on Custom Painting for more information and working examples to get you started.