Hi, I want to write a custom widget which will act similarly to a JPanel (i.e it can contain other Components), but semantically it's not a kind of JPanel so it shouldn't extend from it.
Here is some sample code showing what I'm trying to achieve:
Effectively I expect to see a JLabel with the message "This is a test" as well as a JButton "foo".
What am I doing wrong? Is this possible? Also, I am aware it would be easier to just extend JPanel - but it's not as nice.
ProgramEntryPoi nt.java
-----------------------------------
import java.awt.Dimens ion;
import java.awt.Graphi cs;
import javax.swing.JBu tton;
import javax.swing.JCo mponent;
import javax.swing.JFr ame;
import javax.swing.JLa bel;
import javax.swing.JPa nel;
public class ProgramEntryPoi nt {
public static void main(String[] args)
{
new ProgramEntryPoi nt();
}
public ProgramEntryPoi nt()
{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.add(n ew JLabel("This is a test..."));
mainPanel.add(n ew TestComponent() );
frame.getConten tPane().add(mai nPanel);
frame.setSize(n ew Dimension(800,6 00));
frame.setVisibl e(true);
}
public class TestComponent extends JComponent
{
private JPanel panel;
public TestComponent()
{
this.panel = new JPanel();
this.panel.add( new JButton("foo")) ;
this.panel.setV isible(true);
}
public void paint(Graphics g)
{
this.panel.doLa yout();
this.panel.pain t(g);
}
}
}
Here is some sample code showing what I'm trying to achieve:
Effectively I expect to see a JLabel with the message "This is a test" as well as a JButton "foo".
What am I doing wrong? Is this possible? Also, I am aware it would be easier to just extend JPanel - but it's not as nice.
ProgramEntryPoi nt.java
-----------------------------------
import java.awt.Dimens ion;
import java.awt.Graphi cs;
import javax.swing.JBu tton;
import javax.swing.JCo mponent;
import javax.swing.JFr ame;
import javax.swing.JLa bel;
import javax.swing.JPa nel;
public class ProgramEntryPoi nt {
public static void main(String[] args)
{
new ProgramEntryPoi nt();
}
public ProgramEntryPoi nt()
{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.add(n ew JLabel("This is a test..."));
mainPanel.add(n ew TestComponent() );
frame.getConten tPane().add(mai nPanel);
frame.setSize(n ew Dimension(800,6 00));
frame.setVisibl e(true);
}
public class TestComponent extends JComponent
{
private JPanel panel;
public TestComponent()
{
this.panel = new JPanel();
this.panel.add( new JButton("foo")) ;
this.panel.setV isible(true);
}
public void paint(Graphics g)
{
this.panel.doLa yout();
this.panel.pain t(g);
}
}
}
Comment