JFrame, JPanel, paintComponent how to

本小妞迷上赌 提交于 2019-12-30 14:42:12

问题


  1. Hi I have following classes, I want display content (paintComponentor that panel with this rectangle from paint class) inside my JFrame. I try already find out how to achieve this by looking at different examples posted on this forum however this doesn't help me I need simple example like panel inside frame with paint component or something similar to understand how should work! ps. don't hang me on tree because I am newbie jut ask question!!!

    [I want something like this][1]

    package scp;
    
    import java.awt.*;
    
    import javax.swing.*;
    
    public class Panel extends JPanel {
        public Panel() {
            //this.setPreferredSize(new Dimension(200,200));
            //panel = new Panel();
            setVisible(true);
            setLayout(new FlowLayout());
            setSize(200, 300);
            getRootPane();
        }
        @Override
        public void paintComponent(Graphics g){
            g.drawString("HEY",20,20);
            g.drawRect(200, 200, 200, 200); 
        }
    
    }
    
    and
    
    package scp;
    
    import javax.swing.JFrame;
    import javax.swing.JButton;
    
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.beans.EventHandler;
    
    public class Frame extends JFrame {
    
        JButton redButton;
        JButton blueButton;
    
        public Frame()
        {
            super("EventHandling");
            setLayout(new FlowLayout());
            redButton = new JButton("Red");
            add(redButton);
            blueButton = new JButton("Blue");
            add(blueButton);
    
            EventHandler h = new EventHandler();
    
            redButton.addActionListener(h);
            blueButton.addActionListener(h);
    
        }
    
        private class EventHandler implements ActionListener
        {
            public void actionPerformed(ActionEvent e)
            {
                if (e.getSource()==redButton)
                    getContentPane().setBackground(Color.RED);
                else if(e.getSource()==blueButton)
                    getContentPane().setBackground(Color.BLUE);
            }
        }
    
    }
    
    and
    
    package scp;
    
    import javax.swing.JFrame;
    
    public class EventHandling {
    
        public static void main(String[] args) {
    
            Frame f = new Frame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(800,600);
            f.setVisible(true);
            f.getContentPane().add(new Panel());
        }
    
    }
    

    [1]: http://i.stack.imgur.com/OJTrq.png


回答1:


Start by taking a look at:

  • Painting in AWT and Swing
  • Performing Custom Painting
  • 2D Graphics

This is probably the simplest I can make it...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int width = getWidth() - 100;
            int height = getHeight() - 100;
            int x = (getWidth() - width) / 2;
            int y = (getHeight() - height) / 2;
            g2d.setColor(Color.RED);
            g2d.drawRect(x, y, width, height);
            g2d.dispose();
        }

    }

}

Compound Example

This example uses an outer panel, which has an empty border applied to it, this pushes the content of the edges of the outer panel.

The inner panel (which is unchanged from the last example), as a light gray border applied to it so you can see it, the red rectangle is still been painted by the panels paintComponent method.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

public class Test {

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

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

                JPanel outer = new JPanel(new BorderLayout()) {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(400, 400);
                    }
                };

                outer.setBorder(new EmptyBorder(50, 50, 50, 50));

                TestPane tp = new TestPane();
                tp.setBorder(new LineBorder(Color.LIGHT_GRAY));

                outter.add(tp);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(outer);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int width = getWidth() - 100;
            int height = getHeight() - 100;
            int x = (getWidth() - width) / 2;
            int y = (getHeight() - height) / 2;
            g2d.setColor(Color.RED);
            g2d.drawRect(x, y, width, height);
            g2d.dispose();
        }

    }

}


来源:https://stackoverflow.com/questions/27179739/jframe-jpanel-paintcomponent-how-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!