'Java - JPanel is only one small pixel in the top center of my JFrame
The JPanel called panel only shows up as one small red square up the top center, I have tried to set the size but it doesn't seem to do anything.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JFrame{
private JPanel panel;
public Draw() {
super("title");
setLayout(new FlowLayout());
panel = new JPanel();
panel.setBackground(Color.RED);
add(panel, BorderLayout.CENTER);
}
}
Solution 1:[1]
Try this :
File Draw.java
package com.stackovfl;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
class Draw extends JFrame {
private JPanel panel;
public Draw() {
super("title");
setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(200, 300));
panel.setBackground(Color.RED);
add(panel, BorderLayout.CENTER);
/* Important to get the layout to work */
pack();
/* Center the window */
setLocationRelativeTo(null);
/* Important if you want to see your window :) */
setVisible(true);
}
}
File Test.java (main method to launch the window) : package com.stackovfl;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Draw();
}
});
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mKorbel |