我有一个简单的 java 程序,当我使用 eclipse 运行它时,它会显示我已设置为布局的 3 个 JButton。这些按钮设置为更改布局的对齐方式。因此,您按向左键可左对齐,按右键可右对齐,按居中键可居中对齐。
当按钮执行此操作时,窗口中的对齐方式不会改变,直到您调整窗口大小。
我尝试过更新 jdk 和 eclipse,但没有什么区别,而且我看不出代码本身有问题。
有人知道这是为什么吗?
导入javax.swing.JFrame;
public class Main {
public static void main(String []args){
Layout_buttonsAndActionEvents layout = new Layout_buttonsAndActionEvents();
layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
layout.setSize(300,300);
layout.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Layout_buttonsAndActionEvents extends JFrame {
private static final long serialVersionUID = 1L;
private JButton leftButton;
private JButton rightButton;
private JButton centerButton;
private FlowLayout layout;
private Container container;
public Layout_buttonsAndActionEvents(){
super("The Title");
layout = new FlowLayout();
container = new Container();
setLayout(layout);
leftButton = new JButton("Left");
add(leftButton);
//Align to the left
leftButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
layout.setAlignment(FlowLayout.LEFT);
layout.layoutContainer(container);
}
});
centerButton = new JButton("Center");
add(centerButton);
//Align to the right
centerButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
layout.setAlignment(FlowLayout.CENTER);
layout.layoutContainer(container);
}
});
rightButton = new JButton("Right");
add(rightButton);
//Align to the right
rightButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
layout.setAlignment(FlowLayout.RIGHT);
layout.layoutContainer(container);
}
});
}
}
最佳答案
因为您要将按钮添加到 JFrame 的内容中 Pane (通过 add() 方法,这实际上是对 getContentPane().add() 在幕后)你需要调用 revalidate() 内容 Pane 。
在三个 Action 监听器中,更改:
layout.setAlignment(FlowLayout.XXX);
layout.layoutContainer(container);
至:
layout.setAlignment(FlowLayout.XXX);
getContentPane().revalidate();
此外,您还可以删除对名为“container”的变量的所有引用,因为它在您的示例中不执行任何操作。
关于Java 程序不会对窗口大小调整使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44974220/