我是Java的新手,并试图用griddbaglayout生成我的第一个GUI。下面的代码,我得到我的全屏,但组件"label_url_eingabe"one_answers"url_eingabe"没有显示(空窗口)。当我最小化窗口时,它们就会显示出来!当我将窗口大小设置为特定值时,我得到了相同的行为。因此,这些组件在程序的初始开始时没有显示。
package ofb_reader_package;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
public class OFB_Reader_GUI extends JFrame {
// Definition der GUI Komponenten
// Eingabefeld URL
JLabel label_url_eingabe;
JTextField url_eingabe;
//this.OFB_Reader_GUI();
// Eigenschaften Hauptfenster "OFB_Reader_GUI"
public OFB_Reader_GUI() {
// Eigenschaften Hauptfenster
setVisible(true);
setSize(500, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("Mark's OFB Reader");
setResizable(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setLayout(null);
this.label_url_eingabe = new JLabel("URL:");
this.url_eingabe = new JTextField(10);
this.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// POSITIONIERUNGEN MIT GRIDBAGLAYOUT
// URL Eingabe Label und Einghabefeld
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.ipadx = 35;
c.weightx = 1.0;
c.weighty = 1.0;
c.anchor = GridBagConstraints.NORTHWEST;
this.getContentPane().add(this.label_url_eingabe, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.ipadx = 35;
c.weightx = 1.0;
c.weighty = 1.0;
c.anchor = GridBagConstraints.NORTHWEST;
add(this.url_eingabe, c);
}
}
this is the main:
package ofb_reader_package;
import javax.swing.*;
public class OFB_Reader_main_class {
public static void main(String[] args){
new OFB_Reader_GUI();
new OFB_Reader_main_class();
}
}
非常感谢您的帮助!!我想我现在明白了:
package ofb_reader_package;
import javax.swing.*;
import java.awt.*;
public class OFB_Reader_GUI_and_Main {
public static void addComponentsToPane(Container pane) {
JLabel label_url_eingabe;
JTextField url_eingabe;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
label_url_eingabe = new JLabel("URL:");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(label_url_eingabe, c);
url_eingabe = url_eingabe = new JTextField(10);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
pane.add(url_eingabe, c);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}