按钮一个接一个地水平放置。我需要知道如何使它们垂直出现在屏幕上。我尝试添加 SwingConstants.xxxx。然后 item.SwingConstants.xxx 出现水平对齐错误。任何帮助表示赞赏。 (想坚持这种风格的节目)
import java.awt. * ;
import java.awt.event. * ;
import javax.swing. * ;
@SuppressWarnings("serial")
public class Class_GUI_4 extends JFrame {
private JTextField tf; // textfield
private JCheckBox b1; // button 1
private JCheckBox b2; // button2
public Class_GUI_4() {
super("TITLE");
setLayout(new FlowLayout());
tf = new JTextField("A testing Sentence", 20);
tf.setFont(new Font("Serif", Font.PLAIN, 14));
add(tf);
b1 = new JCheckBox("Bold");
b2 = new JCheckBox("Italic");
add(b1);
add(b2);
thehandler handler = new thehandler();
b1.addItemListener(handler);
b2.addItemListener(handler);
}
private class thehandler implements ItemListener {
@Override
public void itemStateChanged(ItemEvent event) {
Font font = null;
if (b1.isSelected() && b2.isSelected()) font = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
else if (b1.isSelected()) font = new Font("Serif", Font.BOLD, 14);
else if (b2.isSelected()) font = new Font("Serif", Font.ITALIC, 14);
else font = new Font("Serif", Font.PLAIN, 14);
tf.setFont(font);
}
}
public static void main(String[] args) {
Class_GUI_4 gui = new Class_GUI_4();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(200, 350);
gui.setVisible(true);
}
}
最佳答案
how to make them come on screen vertically?
尝试使用 BoxLayout
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
而不是 FlowLayout在本例中,它按定向流排列组件,就像段落中的文本行一样。
setLayout(new FlowLayout());
<小时/>
不要在这种情况下使用 GridLayout
来添加相同大小的组件,如下所示:
<小时/>
您可以尝试使用 GridBagLayout 。了解更多关于 How to Use GridBagLayout
示例代码:(根据您的要求以百分比更改高度)
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
//Set the margin between components top, left, bottom, right
//gc.insets=new Insets(5, 5, 5, 5);
tf = new JTextField("A testing Sentence", 20);
tf.setFont(new Font("Serif", Font.PLAIN, 14));
gc.gridx = 0; // 1st row
gc.gridy = 0; // 1st column
gc.weighty = 0.9; // 90%
add(tf, gc);
b1 = new JCheckBox("Bold");
b2 = new JCheckBox("Italic");
gc.gridy = 1; // 2nd column
gc.weighty = 0.05;// 5%
add(b1, gc);
gc.gridy = 2; // 3rd column
gc.weighty = 0.05;// 5%
add(b2, gc);
关于java - 如何对齐按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096507/