本文介绍了JButton调整所有屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
c li>
仅在
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/ **
* @see http://stackoverflow.com/a/37366846/230513
* /
public class Test {
private static final int PAD = 50;
private void display(){
JFrame f = new JFrame(Test);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p = new JPanel(new GridLayout(0,1,PAD,PAD));
p.setBorder(BorderFactory.createEmptyBorder(PAD,PAD,PAD,PAD));
p.add(new JButton(Test Button 1));
p.add(new JButton(Test Button 2));
f.add(p,BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String [] args){
EventQueue.invokeLater(new Test():: display);
}
}
I have the following code
JFrame frame = new JFrame("Organizer"); frame.setBounds(100, 100, 700, 700); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); JButton testbutton = new JButton("testbutton"); testbutton.setBounds(0, 0, 55, 55); JButton testbutton2 = new JButton("tdestbutton2"); testbutton2.setBounds(55, 0, 44, 44); frame.add(testbutton2); frame.add(testbutton);
and the result sometimes is correct and sometimes is this
what im doing wrong?
解决方案
Don't use setBounds(); do use a layout manager.
Invoke setVisible() after adding components to the enclosing container.
Construct and manipulate Swing GUI objects only on the event dispatch thread.
The example below adds a panel having an empty border and a GridLayout that is padded to match. For such an application, also consider JToolBar for the buttons and CardLayout for the working screens.
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * @see http://stackoverflow.com/a/37366846/230513 */ public class Test { private static final int PAD = 50; private void display() { JFrame f = new JFrame("Test"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(new GridLayout(0, 1, PAD, PAD)); p.setBorder(BorderFactory.createEmptyBorder(PAD, PAD, PAD, PAD)); p.add(new JButton("Test Button 1")); p.add(new JButton("Test Button 2")); f.add(p, BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Test()::display); } }
这篇关于JButton调整所有屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!