Java 调整大小时JButton消失
有人知道或者知道为什么我的按钮在我调整小程序大小后消失了吗 这是我的代码:Java 调整大小时JButton消失,java,swing,jbutton,Java,Swing,Jbutton,有人知道或者知道为什么我的按钮在我调整小程序大小后消失了吗 这是我的代码: import java.awt.event.*; import javax.swing.*; import acm.program.*; public class button extends ConsoleProgram { public void init(){ hiButton = new JButton("hi"); add(hiButton, SOUTH);
import java.awt.event.*;
import javax.swing.*;
import acm.program.*;
public class button extends ConsoleProgram {
public void init(){
hiButton = new JButton("hi");
add(hiButton, SOUTH);
addActionListeners();
}
public void actionPerformed(ActionEvent e){
if(hiButton == e.getSource()){
println("hello") ;
}
}
private JButton hiButton;
}
您是否声明了重新绘制方法 您正在使用swing。它需要声明重新绘制 请定义自定义重绘mwthod假设
- 您的控制台程序(直接或间接)扩展了JApplet
- 您将SOUTH声明为静态最终变量,其值为BorderLayout.SOUTH(否则代码将无法编译)
要重新调整小程序中按钮的大小,请执行以下操作:
public class Button extends JApplet implements ActionListener {
private JButton button;
public void init() {
Container container = getContentPane();
container.setLayout(null);
container.setBackground(Color.white);
button = new JButton("Press Me");
button.setSize(getWidth()/2,20);
button.setLocation(getWidth()/2-button.getSize().width/2, getHeight()/2-button.getSize().height/2);
container.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
int width = (button.getSize().width == getWidth()/2) ? getWidth()/4 : getWidth()/2;
int height = button.getSize().height;
button.setSize(width,height);
button.setLocation(getWidth()/2-width/2, getHeight()/2-height/2);
}
}
要在JFrame中重新调整按钮的大小,请执行以下操作:
public class Button extends JFrame implements ActionListener {
private JButton button;
public Button(String title) {
Container container = getContentPane();
container.setLayout(null);
container.setBackground(Color.white);
setTitle(title);
setSize(400,400);
button = new JButton("Press Me");
button.setSize(getWidth()/2,20);
button.setLocation(getWidth()/2-button.getSize().width/2,
getHeight()/2-button.getSize().height/2);
container.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
int width = (button.getSize().width == getWidth()/2) ? getWidth()/4 : getWidth()/2;
int height = button.getSize().height;
button.setSize(width,height);
button.setLocation(getWidth()/2-width/2, getHeight()/2-height/2);
}
public static void main(String[] args) {
Button button = new Button("Test");
button.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.setVisible(true);
}
}
我不确定重新定义init方法是否是一个好主意。当我查看时,我希望您只实现了run方法。不调用super.init()重写init对我来说很奇怪
在小程序编程的第一步中,我最好直接从JApplet派生。您是否尝试过在init()开始时调用super.init()方法?尝试显式使用控制台布局,然后使用相对定位。你确定这是一个小程序吗?是一个
JApplet
?是的,上面说它是一个小程序。但是,是的,它是一个acm程序。闪烁或完全消失?这不是家庭作业。只是通过斯坦福大学youtube频道学习java。无论如何,答案似乎不是使用ACM lol。。你可以尝试在Java 1.5下运行它,就像他们一样。-1推荐空布局(又名:手动调整组件大小/定位):不管是什么问题,这都不是解决方案的摇摆方式。@kleopatra使用空布局进行“绝对定位”有什么问题。它在文档()中,我的代码就是一个例子。主要问题是,当影响布局的任何子级上的任何属性发生更改时,您必须重新执行所有计算-这正是管理员所做的。手动执行不仅浪费时间(您必须重新编写大量代码)但也很难做到正确:您需要听取所有这些更改,但仍然可能无法得到所有更改的通知(缺少手动重新/验证,f.i.)