Java grid layout and JPanel
I have a question.
I have the following program and I'm having trouble with one thing. I have created a grid layout, and I'm using JPanel to enter buttons and text with in the grid, but everything seems to change size if my text is very long. Can someone help me with how I can prevent this from happening?
This is my code:
package JFrameTester; import java.awt.*; import javax.swing.*; public class JFrameTester { public JPanel createContentPane (){ JPanel panel = new JPanel(); JButton button1,button2,button3,button4; JPanel mainPanel = new JPanel(new GridLayout(2, 0, 40, 10)); //JPanel red = createSquareJPanel(Color.red, 50); button1 = new JButton ("button1"); button2 = new JButton ("button2"); button3 = new JButton ("button3"); button4 = new JButton ("button4"); Label one = new Label("Rohihtjthjhtjghjghmgfjgjghjghj"); //add(button1); mainPanel.add(button1); mainPanel.add(one); mainPanel.add(button2); mainPanel.add(button3); mainPanel.add(button4); panel.add(mainPanel); panel.setOpaque(true); return panel; } public static void main(String[] args) { JFrame frame = new JFrame("GridLayout"); JFrameTester Display = new JFrameTester(); frame.setContentPane(Display.createContentPane()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
Answers
That's what layout managers do; they allocate enough space for every component. You could try embedding HTML into the JLabel instance in order for it to wrap. Otherwise, you're just going to have to live with it.
It's also important to note that a JPanel instance is opaque by default.