我有以下代码:
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
public class ModuleGui extends JComponent {
protected ShapeResizeHandler shapeResizeHandler = new ShapeResizeHandler();
public ModuleGui(){
this.addMouseListener(shapeResizeHandler);
this.addMouseMotionListener(shapeResizeHandler);
}
@Override
public Dimension getPreferredSize() {
return new Dimension (400, 400);
}
@Override
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.red);
g.fillRect(getX(), getY(), getWidth(), getHeight());
}
private class ShapeResizeHandler extends MouseAdapter{
public void mousePressed(MouseEvent e){
System.out.println(e.getPoint().getX() + " " + e.getPoint().getY());
}
public void mouseReleased(){
}
public void mouseDragged(MouseEvent e){
}
}
}
在以下类中使用:
package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Gui {
private JFrame mainFrame = null;
public Gui(){
mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setTitle("--");
mainFrame.setMinimumSize(new Dimension(800, 600));
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.getContentPane().setLayout(new BorderLayout());
ModuleGui moduleGui = new ModuleGui();
moduleGui.setPreferredSize(new Dimension(400, 400));
JPanel aux = new JPanel();
aux.setLayout(new BorderLayout());
aux.add(moduleGui);
mainFrame.getContentPane().add(aux);
mainFrame.pack();
mainFrame.setVisible(true);
}
}
现在我真的不明白为什么如果我保留它或者如果我删除它则根本不显示它会JComponent
在整个屏幕上显示。BorderLayout
JPanel