为什么它在我的JPanel上没有画出任何重叠?

时间:2016-05-16 16:27:55

标签: java swing jframe

嗨伙计们(抱歉我的英语不好),

我正忙着为学校做运动。我无法在我的JPanel上获得重新绘制...任何在我的代码中看到问题的人?我希望它在我的右侧面板上绘制。 BTW东部位于西部,西部位于东部。谢谢你的帮助:)!

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


public class P1027 extends JFrame {

private JButton button;
private JTextField field;
private JPanel east;
private JPanel west;
//static Graphics g;

public P1027() {

    init();

}

public void init() {

    final int FRAME_WIDHT = 800;
    final int FRMAE_HEIGHT = 1000;
    int input = 3;

    final JFrame frame = new JFrame();
    frame.setSize(FRAME_WIDHT, FRAME_WIDHT);
    frame.setTitle("Frame");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    west = new JPanel();
    west.setSize(600, 900);
    west.setBorder(BorderFactory.createLineBorder(Color.black));

    east = new JPanel();
    button = new JButton("Add squares");

    button.addActionListener(new java.awt.event.ActionListener() {

        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jt1ActionPerformed(evt);
        }

        public void jt1ActionPerformed(ActionEvent evt) {

            //int aantalRect = Integer.parseInt(field.getText());
            MyDrawing draw = new MyDrawing();
            east.add(draw);
            System.out.println("hoi");

        }
    });

    field = new JTextField(5);
    east.add(button);
    east.add(field);
    east.setSize(300, 1000);
    button.setSize(100, 50);

    east.setBorder(BorderFactory.createLineBorder(Color.black));

    frame.add(east);
    frame.add(west);

    frame.setResizable(true);
    frame.setVisible(true);

}

public static void main(String[] a) {

    P1027 form = new P1027();

}

}

class MyDrawing extends JComponent {

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.setColor(Color.BLUE);
    g.fillRect(25, 25, 100, 100);

    g.drawRect(50, 100, 50, 50);
    g.drawRect(300, 150, 100, 50);

}

}

1 个答案:

答案 0 :(得分:1)

问题:

  • 将一个组件(MyDrawing JComponent)添加到容器(东JPanel)后,您应该为容器调用revalidate()repaint()来布局添加的组件并重绘本身,清理任何“脏”的像素。
  • 您的MyDrawing JComponent的preferredSize为[0,0],因此当您将其添加到FlowLayout-using容器时,它可能会保留[0,0]。您需要覆盖其getPreferredSize()方法(根据Kleopatra首选)或设置其preferredSize。