GridBagLayout将所有对象放在同一个单元格中

时间:2014-03-12 12:27:14

标签: java swing gridbaglayout

我正在使用gridbaglayout为布局管理器编写一个快速的weatherapplication。然而,gridbag拒绝将JLabel对象放入定义的单独单元格中,而是将所有对象放入一个单元格中。

public class WeatherApp extends JFrame {

private JLabel jDayOfTheWeek;
RSSReader rss = null;
private JLabel jWindDirectionToday;
private JLabel jWindSpeed1;
private JLabel jMaxTemp1;
private JLabel jMinTemp1;
private JLabel jVisibility1;
private JLabel jPressure1;
private JLabel jHumidity1;
private JLabel jWindSpeed2;
private JLabel jMaxTemp2;
private JLabel jMinTemp2;
private JLabel jVisibility2;
private JLabel jPressure2;
private JLabel jHumidity2;
private JLabel jWindSpeed3;
private JLabel jMaxTemp3;
private JLabel jMinTemp3;
private JLabel jVisibility3;
private JLabel jPressure3;
private JLabel jHumidity3;

public WeatherApp() {


    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("Detailed weather");
    this.setSize(320,480);
    GridBagLayout myLayout = new GridBagLayout();
    JPanel mainFrame = new JPanel(myLayout);
    rss = new RSSReader();
    GridBagConstraints c = new GridBagConstraints();



    c.gridwidth = 4;
    c.gridheight = 10;

    jDayOfTheWeek = new JLabel("lelel");
    jDayOfTheWeek.setText(this.getDayOfTheWeek());
    c.anchor = GridBagConstraints.FIRST_LINE_START;
    c.gridx = 0;
    c.gridy = 0;

    c.weightx = 1;
    c.weighty = 1;


    mainFrame.add(jDayOfTheWeek, c);



    jWindDirectionToday = new JLabel(rss.getFirstDay().getWindDirection());
     c.anchor = GridBagConstraints.CENTER;
    c.gridx = 2;
    c.gridy = 2;
     c.weightx = 1;
    c.weighty = 1;
    mainFrame.add(jWindDirectionToday, c);


    jWindSpeed1 = new JLabel(Integer.toString(rss.getFirstDay().getWindSpeed()) + "mph");
    c.gridx = 3;
    c.gridy = 3;
     c.weightx = 1;
    c.weighty = 1;
    mainFrame.add(jWindSpeed1, c);


    jMaxTemp1 = new JLabel(Integer.toString(rss.getFirstDay().getMaxTemp()) + "C");
    c.gridx = 4;
    c.gridy = 4;
     c.weightx = 1;
    c.weighty = 1;
    mainFrame.add(jMaxTemp1, c);



    this.add(mainFrame);



}

public String getDayOfTheWeek() {
    Calendar c = Calendar.getInstance(TimeZone.getDefault());

    Date currentDate = c.getTime();
    return new SimpleDateFormat("EEEE").format(currentDate);



}

public static void main(String[] args) {
    WeatherApp myapp = new WeatherApp();
    myapp.setVisible(true);

}

现在,如果查看代码,JLabel已分配到不同的网格位置:0,0 2,2 3,3和4,4但是编译和执行所有网格位置时的结果将被忽略,但是如果我在锚定后遵循Gridbagconstraints的常量。

2 个答案:

答案 0 :(得分:2)

删除下一行,您的标签位置正确:

c.gridwidth = 4;
c.gridheight = 10;

答案 1 :(得分:0)

我也有这个问题,但是选择的解决方案无法解决我的问题。经过大量研究和艰辛的反复试验,我还发现这可能是由于将同一对象放入多个单元格引起的。

显然,GridBagLayout要求每个单元格都有其自己的单独对象。否则,将仅填充第一个单元格(因为该对象当时是GridBagLayout的新对象)。