我做了以下问答中的内容,但没有一个对我有用。
只是想将 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();
}
}
最佳答案
嗯,您同时使用了frame.setSize() 和frame.pack()。您应该一次使用其中之一。
使用 setSize() 你可以给出你想要的框架大小,但是如果你使用 pack(),它会根据其中组件的大小自动更改框架的大小。它不会考虑您之前提到的大小。
尝试从代码中删除frame.pack()或将其放在设置大小之前,然后运行它。
关于java - JFrame 的 setSize 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34199822/