【发布时间】:2013-12-05 05:16:39
【问题描述】:
我对 Java 比较陌生(尤其是 Swing),我正在将 BlueJ IDE 用于一些基本的 Swing 程序。 问题是当我运行它时,代码的输出显示不一致! 有时它会与所有组件一起正确显示,但有时它只显示到绿色面板,而不是我添加的任何组件。如果我最大化或拖动窗口并在这些情况下增加它的大小,组件会突然出现。 我会说只有大约三分之一或四次它运行正确。发生了什么,我该如何预防?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Swing16
{
public static void main()
{
JFrame frame1 = new JFrame("TESTING");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(1000,700);
frame1.setLocation(200,100);
//frame1.setResizable(false);
frame1.setLayout(null);
JPanel pan1 = new JPanel();
pan1.setBackground(Color.green);
pan1.setBounds(0,0,900,600);
frame1.add(pan1);
pan1.setLayout(null);
JButton east = new JButton("East");
JButton west = new JButton("West");
JButton north = new JButton("North");
JButton south = new JButton("South");
Color cr1 = new Color(0,127,0);
Font ft1 =new Font("impact",Font.BOLD,25);
north.setForeground(Color.white);
north.setBackground(cr1);
south.setForeground(Color.white);
south.setBackground(cr1);
east.setForeground(Color.white);
east.setBackground(Color.blue);
east.setFont(ft1);
east.setToolTipText(" This is the EAST zone");
west.setForeground(Color.white);
west.setBackground(Color.blue);
west.setFont(ft1);
west.setToolTipText(" This is the WEST zone");
JLabel lb1 = new JLabel(" Label 1 ");
JLabel lb2 = new JLabel(" Label 2 ");
lb2.setOpaque(true);
lb2.setForeground(Color.white);
lb2.setBackground(Color.black);
lb2.setFont(ft1);
JTextField tf1 =new JTextField(" TextField1");
tf1.setForeground(Color.white);
tf1.setBackground(Color.black);
tf1.setFont(ft1);
//tf1.selectAll();
JTextField tf2 =new JTextField("TextField 2");
//tf2.getFocus();
JTextArea ta1= new JTextArea("Enter TA",5,30);
ta1.setForeground(Color.white);
ta1.setBackground(Color.black);
//ta1.setFont(ft1);
east.setBounds(400,200,80,100);
pan1.add(east);
west.setBounds(20,200,80,100);
pan1.add(west);
north.setBounds(200,10,100,80);
pan1.add(north);
south.setBounds(200,510,100,80);
pan1.add(south);
lb1.setBounds(0,0,100,50);
pan1.add(lb1);
lb2.setBounds(0,80,100,50);
pan1.add(lb2);
tf1.setBounds(10,350,80,30);
pan1.add(tf1);
tf2.setBounds(10,500,80,30);
pan1.add(tf2);
ta1.setBounds(400,10,100,180);
pan1.add(ta1);
}
}
【问题讨论】:
-
看在上帝的份上,下次请格式化你的代码。 Ctrl+Shift+F 用于 Eclipse,Ctrl+Alt+L 用于 IntellijIDEA。
-
P.S.你的问题肯定是在添加组件之前调用
setVisible。 -
是的,解决了。谢谢!你能解释一下为什么吗?
-
然后接受 MadProgrammers 的回答。