【发布时间】:2015-08-29 05:05:03
【问题描述】:
我有一个简单的 JLabel(响应),我想根据来自 JCombobox 的用户交互将它放在我的 JFrame 的中心。 JLabel 响应应该在窗口的中心,而 JLabel 选择项应该在组合框旁边;目前这三个都相邻。首先,我尝试在将 JLabel 添加到 JFrame 时直接将边框布局与 JLabel 一起使用,但这不起作用。然后我尝试在实例化 JLabel 本身时添加它,然后只添加 JLabel。然后我尝试将 JLabel 添加到 JPanel,并将 JPanel 添加到 JFrame,但这也不起作用,并且所有三个都具有相同的结果,所有三个彼此相邻。这是我的代码:
package Buttons;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class sentencewindow extends JFrame {
public static void main(String[] args) {
sentence senobj = new sentence();
senobj.setVisible(true);
senobj.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
senobj.setSize(500, 600);
}
}
class sentence extends JFrame {
String[] abc = { "First string", "Second String", "Third String" };
JComboBox combo = new JComboBox(abc);
JLabel selectone = new JLabel("This should be next to the combobox");
JLabel response = new JLabel("This should change based on combobox selection");
sentence() {
super("TITLE");
setLayout(new FlowLayout());
combo.addItemListener(new ItemChangeListener());
JPanel container = new JPanel();
response.setSize(250, 250);
container.add(response, BorderLayout.CENTER);
add(container, BorderLayout.CENTER);
add (selectone);
add(combo);
}
class ItemChangeListener implements ItemListener {
public void itemStateChanged(ItemEvent event) {
if (combo.getSelectedItem().equals(abc[0])) {
response.setText("You pressed the first option.");
}
if (combo.getSelectedItem().equals(abc[1])) {
response.setText("You pressed the second option.");
}
if (combo.getSelectedItem().equals(abc[2])) {
response.setText("You pressed the third option.");
}
}
}
}
非常感谢您花时间阅读本文,我非常感谢您为帮助其他程序员所做的努力!我知道这是一个初学者问题,但我已经坚持了很长时间,并且已经阅读了几乎所有与此相关的问题。请帮忙,谢谢。
【问题讨论】:
-
你的框架应该有一个BorderLayout吗?你目前正在给它一个 FlowLayout。
-
我试图给 JLabel 本身一个居中的布局。我是布局的新手,但我很确定 JFrame 的布局不会影响该 JFrame 中 JLabel 的定位和大小。请告诉我。谢谢
-
您的框架和
JPanel正在使用BorderLayout。将框架更改为使用BorderLayout,在面板中添加您的选择标签和组合框,将此面板设置为NORTH位置,将您的response标签添加到中心 -
JFrame 的布局控制着组件在 JFrame 中的定位。 JLabel 的布局将控制 JLabel 中组件的定位(其中没有,所以它没有用处)。
-
像这样:combo.addItemListener(new ItemChangeListener()); JPanel 容器 = 新 JPanel(); response.setSize(250, 250); container.add(response, BorderLayout.CENTER);添加(选择);容器。添加(组合); add(container, BorderLayout.NORTH);
标签: java arrays swing layout-manager border-layout