只是试图理解简单的 Java 事物。Can'get this thing to work。警告:大量错误代码传入。
import java.awt.*;
import java.lang.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
class DrawFrame {
public DrawFrame(){
DrawPanels panelFrame=new DrawPanels();
JFrame mainFrame=new JFrame();
mainFrame.setLayout(new GridLayout(1,3));
mainFrame.setVisible(true);
mainFrame.setSize(480, 800);
mainFrame.setTitle("Title");
mainFrame.setResizable(false);
mainFrame.add(panelFrame.panel1);
mainFrame.add(panelFrame.panel2);
mainFrame.add(panelFrame.panel3);
//panelFrame.panel1.getGraphics();
panelFrame.panel1.add(new DrawBlock());
panelFrame.panel2.add(new DrawBlock());
panelFrame.panel3.add(new DrawBlock());
mainFrame.revalidate();
mainFrame.repaint();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class DrawPanels extends JPanel{
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
public DrawPanels(){
panel1.setBackground(Color.ORANGE);
panel2.setBackground(Color.BLACK);
panel3.setBackground(Color.RED);
panel1.setVisible(true);
panel2.setVisible(true);
panel3.setVisible(true);
panel1.setBorder(new LineBorder(Color.BLACK));
panel2.setBorder(new LineBorder(Color.BLACK));
panel3.setBorder(new LineBorder(Color.BLACK));
}
}
class DrawBlock extends JPanel{
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(1, 1,15,15);
}
}
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
DrawFrame Windos=new DrawFrame();
}}
如果我的 DrawBlock 类扩展了 JPanel,每个 JPanel 都会有一个白色的小方块,但是,paintComponent() 方法没有反应。如果我将 DrawBlock 扩展到 JComponent,则根本不会有正方形。这可能是初学者的问题,但我无法解决。