GridLayout woes

I made a simple program to display a digit using the method drawline ( it's a school project ). The program needs to be an applet, and have a combo box for selecting the background color of the digit, and radial boxes to select the color of the digit it's self.

My problem is that I had this code:

Container c = getContentPane();

c.setLayout(null);

And that made it so I couldn't add in a JTextField, which I needed to capture keystrokes.

I switched over to this code:

c.setLayout(new GridLayout(13,3));

for(int i = 0;i<27;i++)

c.add(new Component(){});

which is, Obvoiusly not optimal coding, but leaves a nice big area for me to draw in with paint()

What I'd like t do is make some sort of image using drawline, and then put that into my Layout manager.

[829 byte] By [Josiah4jca] at [2007-11-26 19:10:45]
# 1

If you think you want to do some drawing on a blank region of the content pane,

what you *really* want to do (trust us) is define a custom component that

draws on itself, and add this component to the appropriate container:

import java.awt.*;

import javax.swing.*;

public class DrawingExample extends JPanel {

protected void paintComponent(Graphics g) {

super.paintComponent(g);

//do drawing here:

g.fillOval(0,0,getWidth(),getHeight());

}

public static void main(String[] args) {

EventQueue.invokeLater(buildApp);

}

static Runnable buildApp = new Runnable() {

public void run() {

JComponent comp = new DrawingExample();

comp.setBackground(Color.BLACK);

comp.setForeground(Color.GREEN);

comp.setPreferredSize(new Dimension(300,100));

JPanel cp = new JPanel(new BorderLayout());

cp.add(comp, BorderLayout.CENTER);

add(cp, BorderLayout.NORTH);

add(cp, BorderLayout.SOUTH);

add(cp, BorderLayout.EAST);

add(cp, BorderLayout.WEST);

JFrame f = new JFrame();

f.setContentPane(cp);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

}

void add(JPanel cp, String constraint) {

JLabel label = new JLabel(constraint, SwingConstants.CENTER);

label.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

cp.add(label, constraint);

}

};

}

DrLaszloJamfa at 2007-7-9 21:07:07 > top of Java-index,Java Essentials,New To Java...
# 2
Thanks, this is just what I was looking for. The one thing I haven't worked out yet is how to make my own methods when I extend the JPanel class, thus setName(String) is now serving a new purpose as a way to recieve input from other classes
Josiah4jca at 2007-7-9 21:07:07 > top of Java-index,Java Essentials,New To Java...
# 3
<shudders/>
DrLaszloJamfa at 2007-7-9 21:07:07 > top of Java-index,Java Essentials,New To Java...