【发布时间】:2016-03-15 23:11:40
【问题描述】:
我做了以下问答中的内容,但没有一个对我有用。
只想将JFrame 调整为设定的大小,但似乎不知道如何操作。阅读一些文档,但我仍然缺少一些东西,希望这里有人可以帮助我。谢谢你。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class CAUnit8Ch18 extends JFrame{
private JTextField txtfield;
private JLabel label;
public CAUnit8Ch18() {
setTitle("Color Change Frame");
//setSize(900,500); this does not seem to work
setPreferredSize(new Dimension(500,300));
pack();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
}
private void createContents() {
JPanel jp = new JPanel();
label = new JLabel("What is your name:");
txtfield = new JTextField(20);
jp.setOpaque(false);
Container contentPane = getContentPane();
Random rand = new Random();
int n = rand.nextInt(4);
switch(n){
case 0:
contentPane.setBackground(Color.RED);
label.setForeground(Color.WHITE);
break;
case 1:
contentPane.setBackground(Color.WHITE);
break;
case 2:
contentPane.setBackground(Color.YELLOW);
break;
case 3:
contentPane.setBackground(Color.GREEN);
label.setForeground(Color.BLUE);
break;
case 4:
contentPane.setBackground(Color.BLUE);
label.setForeground(Color.WHITE);
break;
}
jp.add(label);
jp.add(txtfield);
txtfield.addActionListener(new Listener());
add(jp);
}
private class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String message = "Thanks for playing, " + txtfield.getText();
txtfield.setVisible(false);
label.setText(message);
}
}
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,
"The following window color will be randomly chosen from\nRed, White, Yellow, Green, Blue");
new CAUnit7Ch17();
}
}
【问题讨论】:
-
那些货号什么也没告诉我们。
-
“只是想将 JFrame 调整为设定的大小” 鉴于框架 'chrome' 在不同的外观和感觉上会有不同的大小,这意味着内容的大小窗格必须更改以适应固定大小的框架!通常最好的方法是指定内容的首选大小,使用布局填充和空白边框,然后
pack()框架,不用担心它的确切大小! -
BTW - 你知道这个类的
main(..)方法没有创建CAUnit8Ch18类的实例吗?先解决这个问题.. ;)