Пишу приложение, используя Java/Swing и столкнулся и проблемой: При отображении JFrame компоненты не отображаются пока на них не наведешь мышкой. JFrame хранит в себе класс Main_GUI который наследуется от JPanel, в самом классе пока что находится кнопка и класс AllPosts_GUI котором находится JTextField.
Класс main:
public class Client
{
public static void main(String[] ar)
{
JFrame jpClientGUI = new JFrame();
jpClientGUI.setSize(800, 500);
jpClientGUI.setTitle("Daily Poster");
jpClientGUI.setLayout(new BorderLayout());
jpClientGUI.add(new Main_GUI());
jpClientGUI.setVisible(true);
}
}
Класс Main_GUI:
public class Main_GUI extends JPanel{
public Main_GUI(){
this.setBackground(new Color(100,230,240));
GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
AllPosts_GUI allPosts = new AllPosts_GUI();
add(allPosts, new GridBagConstraints(0,0,1,1,0.0,1,
GridBagConstraints.FIRST_LINE_START,GridBagConstraints.HORIZONTAL,
new Insets(100,0,0,0), 0,0));
JButton button = new JButton("Add new Post");
add(button, new GridBagConstraints(1,0,1,1,0.0,1,
GridBagConstraints.FIRST_LINE_END,GridBagConstraints.HORIZONTAL,
new Insets(100,150,0,0), 0,0));
this.setVisible(true);
this.validate();
}
public void paint(Graphics g)
{
Font font;
g = (Graphics2D)g;
g.setColor(new Color(200,100,100));
font = new Font(null, Font.ITALIC | Font.BOLD, 30);
g.setFont(font);
g.drawString("Welcome to \"Daily Poster\"", 220, 50);
}
}
Класс AllPosts_GUI:
public class AllPosts_GUI extends JPanel{
public AllPosts_GUI(){
JTextArea ma = new JTextArea();
ma.setMinimumSize(new Dimension(200,200));
ma.setText("texttexttexttexttexttexttexttext\n"
+ "texttexttexttexttexttexttexttext\n"
+ "texttexttexttexttexttexttexttext\n");
add(ma);
this.setVisible(true);
this.validate();
}
public void paint(Graphics g)
{
}
}
Во всех конструкторах специально вызывал методы this.SetVisible(true) а так же this.validate() и т.д. но это не помогло.
Измененный код main:
public static void main(String[] ar)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowMainGUI();
}
});
}
private static void createAndShowMainGUI() {
JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jFrame.setSize(850, 500);
jFrame.setTitle("Daily Poster");
jFrame.setBackground(new Color(100,230,240));
GridBagLayout gbl = new GridBagLayout();
jFrame.setLayout(gbl);
AllPosts_GUI apg = new AllPosts_GUI();
jFrame.getContentPane().add(apg);
jFrame.pack();
jFrame.setVisible(true);
}
}