扩展JPanels的问题 [英] Problems extending JPanels
问题描述
我正在解决一个问题,我在Swing中遇到了一些问题。我在使用扩展JFrame或JComponent的类时没有任何问题,但是当我尝试使用我编写的扩展JPanel的类时,它将不会显示,并且我在该面板上调用的任何内容都不显示,包括添加自定义JComponents到它。创建JPanel扩展类然后将其设置为要在JFrame中使用的内容窗格的一般过程是什么?
Hi I'm working on a problem and I'm having some issues working in Swing. I have no issues working with classes that extend either JFrame or JComponent, but when I try to use a class that I write that extends JPanel, it won't ever show up and nothing that I call on that panel shows up, including adding custom JComponents to it. What is the general procedure for creating a JPanel extendting class and then setting it as the content pane to use in a JFrame?
推荐答案
我(我的个人观点)看不出扩展 JComponent
为 JComponent
, JPanel
, JLabel
,更多继承与组合,例如
I (my personal view) can't see nothing wrong with extends JComponent
as JComponent
, JPanel
, JLabel
, more Inheritance versus composition, for example
import java.awt.*;
import javax.swing.*;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
setTitle("Custom Component Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new CustomComponents());
pack();
setMinimumSize(getSize());// enforces the minimum size of both frame and component
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
CustomComponent main = new CustomComponent();
//main.display();
}
});
}
}
class CustomComponents extends JComponent {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
这篇关于扩展JPanels的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!