Java JComboBox无法显示

时间:2016-01-17 03:07:45

标签: java swing layout-manager jcombobox

Java新手。我无法显示下拉框。

我最初在按钮之前有代码,但是当我运行代码(intelliJ idea)时,下拉按钮和按钮都没出现。

stackoverflow想要更多细节。不知道要添加什么。我确信它只是语法中的一个noobie错误。

package com.example.guiTest;

import javax.swing.*;
import java.awt.*;

import java.lang.Object;
import java.awt.Component;
import java.awt.Container;
import javax.swing.JComponent;
import javax.swing.JComboBox;

public class Main {

public static void main(String[] args) {

    JFrame window = new JFrame("Position");
    window.setVisible(true);
    window.setSize(500, 500);
    window.setResizable(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    window.setLocation(dim.width/2-window.getSize().width/2, dim.height/2-window.getSize().height/2);;

    JPanel panel = new JPanel();
    panel.setLayout(null);
    window.add(panel);

    JLabel test = new JLabel("This is a test");
    test.setBounds(20,0,120,120);
    panel.add(test);

    JButton button = new JButton("Compile");
    button.setBounds(250, 250, 120, 50);
    panel.add(button);


    String[] noteArray = {"a", "b"};

    JComboBox note = new JComboBox(noteArray);
    note.setPreferredSize(new Dimension(200,130));
    note.setLocation(new Point(200,200));
    note.setEditable(true);
    note.setSelectedIndex(3);
    note.setVisible(true);

    panel.add(note);






}

}

1 个答案:

答案 0 :(得分:3)

您在面板JPanel上使用Class test { public static void main (String args []){ int test = 6; if (test == 9){ System.out.println(“True”); } else { System.out.println(“False”); } } 布局,快速回答是null布局要求您完全指定所有添加组件的大小和位置,即 size preferredSize 。你设定后者,而不是前者。

更好的答案是不使用null布局和null。虽然null布局和setBounds(...)似乎是Swing新手,比如创建复杂GUI的最简单和最好的方法,但是你创建的Swing GUI越多,在使用它们时会遇到更严重的困难。当GUI调整大小时,它们不会调整组件的大小,它们是增强或维护的皇室女巫,当它们被放置在滚动窗格中时它们完全失败,当它们在所有平台上观看时或者与原始平台不同的屏幕分辨率时它们看起来很糟糕

编辑:
或者你最终将JComboBox放在你的JButton上(就像你的代码一样!)。

编辑:
另一个问题:在将所有组件添加到GUI之前,不要在JFrame上调用setBounds()

编辑:
然而另一个问题:setVisible(true)
注释组合框中只有2个项目,那么为什么要尝试将所选索引设置为3?这保证会失败。

例如:

note.setSelectedIndex(3);