I did what's in the following Q&As but none worked for me.
Simply want to size the JFrame
to a set size but can't seem to figure out how. Read some of the docs but I'm still missing something and hope someone here can help me. Thank you.
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();
}
}