我需要帮助在某个面板上绘制/绘制对象。我想在“drawPanel”JPanel中绘制内容。有人可以看看这个并告诉我我错过了什么吗?我很感激,如果我错过了一些明显的东西,我很抱歉。
当我运行程序时,什么都没画。
package redball;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class drawTest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
drawTest frame = new drawTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public drawTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel leftPanel = new JPanel();
contentPane.add(leftPanel, BorderLayout.WEST);
JLabel lblNewLabel = new JLabel("some stuff");
leftPanel.add(lblNewLabel);
JPanel drawPanel = new JPanel(); //this is where I want to draw stuff
contentPane.add(drawPanel, BorderLayout.CENTER);
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.setColor(Color.black);
g.fillRect(25, 500, 100, 20);
}
}
答案 0 :(得分:1)
一般提示(前两个有助于解决此问题):
EachWordUpperCaseClass
,firstWordLowerCaseMethod()
,firstWordLowerCaseAttribute
,除非它是UPPER_CASE_CONSTANT
)并一致地使用它。这是实施上述建议的结果,以及代码中的评论中提到的一些提示。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class DrawTest extends JFrame {
private JPanel contentPane;
public DrawTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// instead pack() once components are added
// setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.CYAN);
contentPane.add(leftPanel, BorderLayout.LINE_START);
JLabel lblNewLabel = new JLabel("some stuff");
leftPanel.add(lblNewLabel);
JPanel drawPanel = new JPanel() {
Dimension preferredSize = new Dimension(300, 100);
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
// 500? That's much deeper than the panel shows on-screen!
//g.fillRect(25, 500, 100, 20);
g.fillRect(25, 50, 100, 20);
}
@Override
public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
if (d.width<50 || d.height<50) {
return preferredSize;
} else {
System.out.println("d: " + d);
return d;
}
}
};
drawPanel.setBackground(Color.YELLOW);
contentPane.add(drawPanel, BorderLayout.CENTER);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DrawTest frame = new DrawTest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}