Simple quiz not showing next answer - java

I'm trying to make a "Simple" quiz in Java using a JFrame. Basically long story short... When the user clicks the "NEXT" button after question 2, it doesn't show the next question...
How can I get the code to proceed to question 3?
CODE
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SimpleQuiz implements KeyListener, ActionListener
{
static final int WIDTH = 900, HEIGHT = 600;
static final Font FONT = new Font("Arial", Font.BOLD, 20);
static final Color DARKGREEN = new Color(0, 140, 0);
int correct = 0;
boolean start = false , Q1 = false , Q2 = false, Q3 = false;
JFrame window;
JMenuBar Menu;
JMenu startMenu;
JMenuItem GoAction;
JRadioButton radButton1;
JRadioButton radButton2;
JRadioButton radButton3;
JRadioButton radButton4;
JLabel question1;
JLabel question2;
JLabel question3;
JLabel score;
JButton next1;
JButton next2;
JButton finish;
JCheckBox checkBox1;
JCheckBox checkBox2;
JCheckBox checkBox3;
JCheckBox checkBox4;
JList listBox;
public static void main(String[] args)
{
new SimpleQuiz();
}
public SimpleQuiz()
{
window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(null);
window.setSize(WIDTH, HEIGHT);
window.setTitle("Quiz");
window.getContentPane().setBackground(Color.WHITE);
window.setLocationRelativeTo(null);
window.setResizable(false);
//
//
//Question 1
//
//
radButton1 = new JRadioButton();
radButton1.setFont(new Font("Arial", Font.BOLD, 14));
radButton1.setForeground(Color.BLACK);
radButton1.setSize(160, 30);
radButton1.setText("Los Angeles");
radButton1.setLocation(300, 180);
radButton1.setFocusable(false);
radButton1.setVisible(false);
window.add(radButton1);
radButton2 = new JRadioButton();
radButton2.setFont(new Font("Arial", Font.BOLD, 14));
radButton2.setForeground(Color.BLACK);
radButton2.setSize(160, 30);
radButton2.setText("Detroit");
radButton2.setLocation(300, 210);
radButton2.setFocusable(false);
radButton2.setVisible(false);
window.add(radButton2);
radButton3 = new JRadioButton();
radButton3.setFont(new Font("Arial", Font.BOLD, 14));
radButton3.setForeground(Color.BLACK);
radButton3.setSize(160, 30);
radButton3.setText("Shanghai");
radButton3.setLocation(300, 240);
radButton3.setFocusable(false);
radButton3.setVisible(false);
window.add(radButton3);
radButton4 = new JRadioButton();
radButton4.setFont(new Font("Arial", Font.BOLD, 14));
radButton4.setForeground(Color.BLACK);
radButton4.setSize(160, 30);
radButton4.setText("New York City");
radButton4.setLocation(300, 270);
radButton4.setFocusable(false);
radButton4.setVisible(false);
window.add(radButton4);
question1 = new JLabel();
question1.setSize(550, 30);
question1.setLocation(160, 120);
question1.setFont(new Font("Arial", Font.BOLD, 16));
question1.setText("Which one of these cities is not located in the United states of America:");
question1.setOpaque(true);
question1.setBackground(Color.WHITE);
question1.setForeground(Color.BLACK);
question1.setVisible(false);
window.add(question1);
next1 = new JButton();
next1.setFont(new Font("Arial", Font.BOLD, 28));
next1.setForeground(Color.BLACK);
next1.setSize(160, 30);
next1.setText("NEXT");
next1.setActionCommand("q2");
next1.setLocation(700, 500);
next1.setFocusable(false);
next1.setVisible(false);
next1.addActionListener(this);
window.add(next1);
//
//
//Question 2
//
//
checkBox1 = new JCheckBox();
checkBox1.setFont(new Font("Arial", Font.BOLD, 14));
checkBox1.setForeground(Color.BLACK);
checkBox1.setSize(160, 30);
checkBox1.setText("13");
checkBox1.setLocation(300, 180);
checkBox1.setFocusable(false);
checkBox1.setVisible(false);
window.add(checkBox1);
checkBox2 = new JCheckBox();
checkBox2.setFont(new Font("Arial", Font.BOLD, 14));
checkBox2.setForeground(Color.BLACK);
checkBox2.setSize(160, 30);
checkBox2.setText("79");
checkBox2.setLocation(300, 210);
checkBox2.setFocusable(false);
checkBox2.setVisible(false);
window.add(checkBox2);
checkBox3 = new JCheckBox();
checkBox3.setFont(new Font("Arial", Font.BOLD, 14));
checkBox3.setForeground(Color.BLACK);
checkBox3.setSize(160, 30);
checkBox3.setText("14");
checkBox3.setLocation(300, 240);
checkBox3.setFocusable(false);
checkBox3.setVisible(false);
window.add(checkBox3);
checkBox4 = new JCheckBox();
checkBox4.setFont(new Font("Arial", Font.BOLD, 14));
checkBox4.setForeground(Color.BLACK);
checkBox4.setSize(160, 30);
checkBox4.setText("87");
checkBox4.setLocation(300, 270);
checkBox4.setFocusable(false);
checkBox4.setVisible(false);
window.add(checkBox4);
question2 = new JLabel();
question2.setSize(550, 30);
question2.setLocation(160, 120);
question2.setFont(new Font("Arial", Font.BOLD, 16));
question2.setText("Select the prime number(s):");
question2.setOpaque(true);
question2.setBackground(Color.WHITE);
question2.setForeground(Color.BLACK);
question2.setVisible(false);
window.add(question2);
next2 = new JButton();
next2.setFont(new Font("Arial", Font.BOLD, 28));
next2.setForeground(Color.BLACK);
next2.setSize(160, 30);
next2.setText("EXT");
next2.setActionCommand("q3");
next2.setLocation(700, 500);
next2.setFocusable(false);
next2.setVisible(false);
next2.addActionListener(this);
window.add(next2);
//
//
//Question 3
//
//
listBox = new JList();
listBox.setFont(new Font("Arial", Font.BOLD, 14));
listBox.setForeground(Color.BLACK);
listBox.setSize(160, 30);
listBox.setLocation(300, 210);
listBox.setFocusable(false);
listBox.setVisible(false);
window.add(listBox);
question3 = new JLabel();
question3.setSize(550, 30);
question3.setLocation(160, 120);
question3.setFont(new Font("Arial", Font.BOLD, 16));
question3.setText("Of the people listed, who was not a US President:");
question3.setOpaque(true);
question3.setBackground(Color.WHITE);
question3.setForeground(Color.BLACK);
question3.setVisible(false);
window.add(question3);
finish = new JButton();
finish.setFont(new Font("Arial", Font.BOLD, 28));
finish.setForeground(Color.BLACK);
finish.setSize(160, 30);
finish.setText("FINISH");
finish.setActionCommand("end");
finish.setLocation(700, 500);
finish.setFocusable(false);
finish.setVisible(false);
finish.addActionListener(this);
window.add(finish);
//
//
//End
//
//
score = new JLabel();
score.setSize(550, 30);
score.setLocation(160, 120);
score.setFont(new Font("Arial", Font.BOLD, 16));
score.setText("your score is: " + correct + "/3");
score.setOpaque(true);
score.setBackground(Color.WHITE);
score.setForeground(Color.BLACK);
score.setVisible(false);
window.add(score);
//
//
//Extra
//
//
Menu = new JMenuBar();
startMenu = new JMenu("Start");
Menu.add(startMenu);
GoAction = new JMenuItem("Go");
GoAction.setActionCommand("q1");
GoAction.addActionListener(this);
startMenu.add(GoAction);
//exitMenuItem.addActionListener(this);
window.setVisible(true);
window.setJMenuBar(Menu);
//if (getActionCommand() == "BeginQuiz")
//System.out.println(Q1);
}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("q1"))
{
start = true;
radButton1.setVisible(true);
radButton2.setVisible(true);
radButton3.setVisible(true);
radButton4.setVisible(true);
question1.setVisible(true);
next1.setVisible(true);
System.out.println("Q1");
}
if (e.getActionCommand().equals("q2"))
{
{
radButton1.setVisible(false);
radButton2.setVisible(false);
radButton3.setVisible(false);
radButton4.setVisible(false);
question1.setVisible(false);
next1.setVisible(false);
System.out.println("Q2");
checkBox1.setVisible(true);
checkBox2.setVisible(true);
checkBox3.setVisible(true);
checkBox4.setVisible(true);
question2.setVisible(true);
next2.setVisible(true);
}
if (e.getActionCommand().equals("q3"))
{
{
next2.setVisible(false);
checkBox1.setVisible(false);
checkBox2.setVisible(false);
checkBox3.setVisible(false);
checkBox4.setVisible(false);
question2.setVisible(false);
System.out.println("Q3");
question3.setVisible(true);
finish.setVisible(true);
}
if (e.getActionCommand().equals("end"))
{
{
question3.setVisible(false);
finish.setVisible(false);
score.setVisible(true);
finish.setVisible(true);
}
}
}
}
}
}
As always, thanks for helping me out!

You've got your if (action command equals q3) if block buried within the previous if block and so it will never be reached when it is in a true state.
e.g. you have something like:
if (e.getActionCommand().equals("q2"))
{
{ // this block is unnecessary
// bunch of stuff in here
}
// this block is buried within the if block above, and so will never be true
if (e.getActionCommand().equals("q3"))
{
{ // again this block is unnesseary
// more bunch of code
}
// again this block is buried within the previous two!
if (e.getActionCommand().equals("end"))
{
To solve the immediate problem, each if block should be at the same block code level and not nested in the prior block.
For example, a simple fix would be to change this:
if (e.getActionCommand().equals("q2")) {
{
radButton1.setVisible(false);
radButton2.setVisible(false);
radButton3.setVisible(false);
radButton4.setVisible(false);
question1.setVisible(false);
next1.setVisible(false);
System.out.println("Q2");
checkBox1.setVisible(true);
checkBox2.setVisible(true);
checkBox3.setVisible(true);
checkBox4.setVisible(true);
question2.setVisible(true);
next2.setVisible(true);
}
if (e.getActionCommand().equals("q3")) {
{
next2.setVisible(false);
checkBox1.setVisible(false);
checkBox2.setVisible(false);
checkBox3.setVisible(false);
checkBox4.setVisible(false);
question2.setVisible(false);
System.out.println("Q3");
question3.setVisible(true);
finish.setVisible(true);
}
if (e.getActionCommand().equals("end")) {
{
question3.setVisible(false);
finish.setVisible(false);
score.setVisible(true);
finish.setVisible(true);
}
}
}
}
to this:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("q1")) {
start = true;
radButton1.setVisible(true);
radButton2.setVisible(true);
radButton3.setVisible(true);
radButton4.setVisible(true);
question1.setVisible(true);
next1.setVisible(true);
System.out.println("Q1");
}
if (e.getActionCommand().equals("q2")) {
radButton1.setVisible(false);
radButton2.setVisible(false);
radButton3.setVisible(false);
radButton4.setVisible(false);
question1.setVisible(false);
next1.setVisible(false);
System.out.println("Q2");
checkBox1.setVisible(true);
checkBox2.setVisible(true);
checkBox3.setVisible(true);
checkBox4.setVisible(true);
question2.setVisible(true);
next2.setVisible(true);
}
if (e.getActionCommand().equals("q3")) {
next2.setVisible(false);
checkBox1.setVisible(false);
checkBox2.setVisible(false);
checkBox3.setVisible(false);
checkBox4.setVisible(false);
question2.setVisible(false);
System.out.println("Q3");
question3.setVisible(true);
finish.setVisible(true);
}
if (e.getActionCommand().equals("end")) {
question3.setVisible(false);
finish.setVisible(false);
score.setVisible(true);
finish.setVisible(true);
}
}
But more importantly your code is very repetitive and mixes data with code in an unhealthy way. I would first concentrate on creating an OOP-compliant Question class, and only after doing that and testing it, building a GUI around this class. Also rather than swap components, consider swapping the data that the components display. This will make extending and debugging your code much easier.
For example, I'd start with this:
public class Question {
private String question;
private String correctAnswer;
private List<String> wrongAnswers = new ArrayList<>();
public Question(String question, String correctAnswer) {
this.question = question;
this.correctAnswer = correctAnswer;
}
public void addWrongAnswer(String wrongAnswer) {
wrongAnswers.add(wrongAnswer);
}
public boolean testAnswer(String possibleAnswer) {
return correctAnswer.equalsIgnoreCase(possibleAnswer);
}
public List<String> getAllRandomAnswers() {
List<String> allAnswers = new ArrayList<>(wrongAnswers);
allAnswers.add(correctAnswer);
Collections.shuffle(allAnswers);
return allAnswers;
}
public String getQuestion() {
return question;
}
public String getCorrectAnswer() {
return correctAnswer;
}
// toString, equals and hashCode need to be done too
}
Then I'd
Create a class to hold an ArrayList<Question>, that could give questions as needed, that could tally responses, correct vs. incorrect.
Create file I/O routines to store questions in a file, perhaps as a simple text file or better as an XML file or best as a database.
Then create a class that creates a JPanel that can display any question and that can get user input.
Then a GUI to hold the above JPanel that can get the Question collection from file, that can test the user.

Related

Is there a way to select multiple check boxes in java?

I have been programming this small app that the user can select one of the a font colors, blue , red and black, so i used JradioButton for them. also the user can choose a style to the font whether bold or italic or both at the same time, so i used Jcheckbox. the problem is that i tried to let the user choose both italic and bold but nothing changed, is there a way to do that?
private void jRadioBlackActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioBlack.isSelected()) {
jTextField1.setForeground(Color.black);
}
if (jCheckBoxBold.isSelected() && jCheckBoxItalic.isSelected()) {
jTextField1.setFont(new Font("Times New Roman", Font.BOLD + Font.ITALIC, 14));
}
}
private void jRadioRedActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioRed.isSelected())
jTextField1.setForeground(Color.red);
}
private void jRadioBlueActionPerformed(java.awt.event.ActionEvent evt) {
if (jRadioBlue.isSelected())
jTextField1.setForeground(Color.blue);
}
private void jCheckBoxBoldItemStateChanged(java.awt.event.ItemEvent evt) {
if (jCheckBoxBold.isSelected()) {
jTextField1.setFont(new Font("Times New Roman", Font.BOLD, 14));
} else {
jTextField1.setFont(new Font("Times New Roman", Font.PLAIN, 14));
}
}
private void jCheckBoxItalicStateChanged(javax.swing.event.ChangeEvent evt) {
}
private void jCheckBoxItalicItemStateChanged(java.awt.event.ItemEvent evt) {
if (jCheckBoxItalic.isSelected()) {
jTextField1.setFont(new Font("Times New Roman", Font.ITALIC, 14));
} else {
jTextField1.setFont(new Font("Times New Roman", Font.PLAIN, 14));
}
}
Example:
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import javax.swing.*;
public class Test {
public void run() {
final JTextField textField = new JTextField(20);
JCheckBox bold = new JCheckBox("Bold");
JCheckBox italic = new JCheckBox("Italic");
JPanel stylePanel = new JPanel();
stylePanel.add(bold);
stylePanel.add(italic);
bold.addItemListener(e -> changeStyle(textField, Font.BOLD, e.getStateChange()));
italic.addItemListener(e -> changeStyle(textField, Font.ITALIC, e.getStateChange()));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(textField, BorderLayout.NORTH);
frame.add(stylePanel, BorderLayout.SOUTH);
frame.setSize(800, 600);
frame.setVisible(true);
}
private void changeStyle(JTextField textField, int style, int stateChange) {
if (stateChange == ItemEvent.DESELECTED) {
removeStyle(textField, style);
} else {
addStyle(textField, style);
}
}
private void addStyle(JTextField textField, int style) {
Font current = textField.getFont();
int newStyle = current.getStyle() | style;
textField.setFont(current.deriveFont(newStyle));
}
private void removeStyle(JTextField textField, int style) {
Font current = textField.getFont();
int newStyle = current.getStyle() & ~style;
textField.setFont(current.deriveFont(newStyle));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Test().run());
}
}

create a login form and change password from hide to visible

I'm trying to create a login form and I have some problems at getting the showPassword checkBox work. When showPassword is selected I want the content of the JPasswordField, passwordField, to be visible and when showPassword is not selected I want it to be "hide". I don't understant why my code doesn't work. I write the code this way because I want to implement it in the future as a Model View Controller. I'd prefer not to change any attribute from private in public if possible. Any ideas why this doesn't work? Thanks!
package project3;
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class LogInWindow extends JFrame {
private Container container = getContentPane();
private JLabel titleLabel = new JLabel("WarehouseApp");
private JLabel userLabel = new JLabel("USERNAME");
private JLabel passwordLabel = new JLabel("PASSWORD");
private JTextField userTextField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
private JButton loginButton = new JButton("LOGIN");
private JCheckBox showPassword = new JCheckBox("Show Password");
private JLabel logInAsLabel = new JLabel("LOGIN AS");
private JComboBox<String> logInAsComboBox = new JComboBox<String>();
public LogInWindow() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(10, 10, 370, 370);
this.setName("Login Form");
this.setResizable(false);
this.setLocationRelativeTo(null);
container.setLayout(null);
titleLabel.setBounds(80, -10, 200, 100);
userLabel.setBounds(50, 80, 100, 30);
userTextField.setBounds(150, 80, 150, 30);
passwordLabel.setBounds(50, 130, 100, 30);
passwordField.setBounds(150, 130, 150, 30);
logInAsLabel.setBounds(50, 180, 100, 30);
logInAsComboBox.setBounds(150, 180, 150, 30);
showPassword.setBounds(150, 220, 150, 30);
loginButton.setBounds(150, 260, 100, 30);
Font font = new Font("Times New Roman", Font.BOLD, 30);
titleLabel.setFont(font);
logInAsComboBox.addItem("ADMIN");
logInAsComboBox.addItem("CLIENT");
logInAsComboBox.setSelectedIndex(-1);
container.add(titleLabel);
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(logInAsLabel);
container.add(logInAsComboBox);
container.add(showPassword);
container.add(loginButton);
}
public void showPasswordWhenClicked(ActionListener listenForPassword) {
showPassword.addActionListener(listenForPassword);
}
public boolean getPasswordStatus() {
if (showPassword.isSelected()==true)
return true;
return false;
}
public void setPasswordVisible() {
passwordField.setEchoChar((char) 0);
}
public void setPasswordInvisible() {
passwordField.setEchoChar('*');
}
}
package project3;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Controller {
private LogInWindow theView;
public Controller(LogInWindow theView) {
this.theView = theView;
this.theView.showPasswordWhenClicked(new showPasswordListener());
}
public class showPasswordListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
if (theView.getPasswordStatus()==true) {
theView.setPasswordVisible();
} else {
theView.setPasswordInvisible();
}
}
}
public static void main(String[] args) {
LogInWindow logIn = new LogInWindow();
logIn.setVisible(true);
}
}
Your code does not create an instance of Controller, so that class’s constructor is never called. Therefore, showPasswordWhenClicked is never called.
Try adding this line to your main method:
new Controller(logIn);

Print JFrame with setVisible(false)

I create a Swing application with 2 JFrame windows and I want to 1st frame as main page. I set print button in 1st frame to print 2nd frame.
How can I print the second frame with frame.setVisible(false);? How can I solve it?
I put my code below:
package printuiwindow;
/**
*
* #author Saravanan Ponnusamy
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.print.*;
class PrintUIWindow implements Printable, ActionListener {
JFrame frameToPrint;
public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY()-55);
frameToPrint.print(g);
return PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
System.out.println(ex);
}
}
}
public PrintUIWindow(JFrame f) {
frameToPrint = f;
}
public static void main(String args[]) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f = new JFrame("Print UI Example");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
//Printing frame design start
JFrame frame = new JFrame("Print UI Example");
JLabel label11=new JLabel("Selling Bill",JLabel.CENTER);
JLabel label21=new JLabel("Customer Name :",JLabel.LEFT);
JLabel label31=new JLabel("Buying Date :",JLabel.LEFT);
JLabel label41=new JLabel("Book Buyed :",JLabel.LEFT);
JLabel label51=new JLabel("Number :",JLabel.LEFT);
JLabel label61=new JLabel("Total Price :",JLabel.LEFT);
label11.setFont(new Font("Courier New", Font.BOLD, 13));
label21.setFont(new Font("Courier New", Font.BOLD, 13));
label31.setFont(new Font("Courier New", Font.BOLD, 13));
label41.setFont(new Font("Courier New", Font.BOLD, 13));
label51.setFont(new Font("Courier New", Font.BOLD, 13));
label61.setFont(new Font("Courier New", Font.BOLD, 13));
JPanel panel1=new JPanel();
panel1.setLayout(new GridLayout(6,1));
panel1.add(label11);
panel1.add(label21);
panel1.add(label31);
panel1.add(label41);
panel1.add(label51);
panel1.add(label61);
frame.setSize(300,300);
frame.setLocationRelativeTo(null);
frame.add(panel1,BorderLayout.CENTER);
panel1.setBackground(Color.WHITE);
frame.setResizable(false);
frame.setVisible(true);
//printing frame design end
//first frame design start
JLabel label1=new JLabel("Selling Bill",JLabel.CENTER);
JLabel label2=new JLabel("Customer Name :",JLabel.LEFT);
JLabel label3=new JLabel("Buying Date :",JLabel.LEFT);
JLabel label4=new JLabel("Book Buyed :",JLabel.LEFT);
JLabel label5=new JLabel("Number :",JLabel.LEFT);
JLabel label6=new JLabel("Total Price :",JLabel.LEFT);
label1.setFont(new Font("Courier New", Font.BOLD, 13));
label2.setFont(new Font("Courier New", Font.BOLD, 13));
label3.setFont(new Font("Courier New", Font.BOLD, 13));
label4.setFont(new Font("Courier New", Font.BOLD, 13));
label5.setFont(new Font("Courier New", Font.BOLD, 13));
label6.setFont(new Font("Courier New", Font.BOLD, 13));
JButton printButton = new JButton("Print This Window");
//print button code
printButton.addActionListener(new PrintUIWindow(frame));
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(6,1));
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(label6);
f.setSize(300,300);
f.setLocationRelativeTo(null);
f.add(panel,BorderLayout.CENTER);
f.add(printButton,BorderLayout.SOUTH);
panel.setBackground(Color.WHITE);
f.setResizable(false);
f.setVisible(true);
}
}
How I hate printing components, seriously, either learn to do it by hand or use something like Jasper Reports.
You have a series of issues...
Components can only have one parent, so when you create your second window and add the components to it, you're removing them from the first window;
You can't paint an invisible component;
You really shouldn't be printing the frame anyway, better to print the panel instead;
Unless it's been realised on the screen, you'll be responsible for ensure that the component is properly laid out before it's printed
You really don't want to print the frame, you actually want to print the panel instead, it's just a lot simpler and you don't get the frame. If you want to print the frame as well, you will need to make the frame visible.
So, based on this previous answer
So, basically, this adds a simple factory method to create the base panel. This will make two instances of this panel, one to print and one to display (technically you could use one, but you get the idea).
The printing process will update the layout of the panel while it's printing to make sure that it's contents are properly laid, so that they are actually rendered.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
class PrintUIWindow implements Printable, ActionListener {
JPanel frameToPrint;
boolean fill = false;
public int print(Graphics g, PageFormat pf, int page) throws
PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
double width = (int) Math.floor(pf.getImageableWidth());
double height = (int) Math.floor(pf.getImageableHeight());
if (!fill) {
width = Math.min(width, frameToPrint.getPreferredSize().width);
height = Math.min(height, frameToPrint.getPreferredSize().height);
}
System.out.println(width + "x" + height);
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
System.out.println(width + "x" + height);
frameToPrint.setBounds(0, 0, (int) Math.floor(width), (int) Math.floor(height));
if (frameToPrint.getParent() == null) {
frameToPrint.addNotify();
}
frameToPrint.validate();
frameToPrint.doLayout();
frameToPrint.printAll(g2d);
if (frameToPrint.getParent() != null) {
frameToPrint.removeNotify();
}
return PAGE_EXISTS;
}
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
System.out.println(ex);
}
}
}
public PrintUIWindow(JPanel f) {
frameToPrint = f;
}
public static void forceLayout(JPanel panel) {
if (panel.getParent() == null) {
panel.addNotify();
}
panel.validate();
panel.doLayout();
if (panel.getParent() != null) {
panel.removeNotify();
}
}
public static JPanel makePanel() {
JLabel label11 = new JLabel("Selling Bill", JLabel.LEFT);
JLabel label21 = new JLabel("Customer Name :", JLabel.LEFT);
JLabel label31 = new JLabel("Buying Date :", JLabel.LEFT);
JLabel label41 = new JLabel("Book Buyed :", JLabel.LEFT);
JLabel label51 = new JLabel("Number :", JLabel.LEFT);
JLabel label61 = new JLabel("Total Price :", JLabel.LEFT);
label11.setFont(new Font("Courier New", Font.BOLD, 13));
label21.setFont(new Font("Courier New", Font.BOLD, 13));
label31.setFont(new Font("Courier New", Font.BOLD, 13));
label41.setFont(new Font("Courier New", Font.BOLD, 13));
label51.setFont(new Font("Courier New", Font.BOLD, 13));
label61.setFont(new Font("Courier New", Font.BOLD, 13));
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(6, 1));
panel1.add(label11);
panel1.add(label21);
panel1.add(label31);
panel1.add(label41);
panel1.add(label51);
panel1.add(label61);
panel1.setBackground(Color.WHITE);
return panel1;
}
public static void main(String args[]) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame f = new JFrame("Print UI Example");
JButton printButton = new JButton("Print This Window");
JPanel toPrint = makePanel();
System.out.println(toPrint.getPreferredSize());
forceLayout(toPrint);
System.out.println(toPrint.getPreferredSize());
printButton.addActionListener(new PrintUIWindow(toPrint));
JPanel panel = makePanel();
f.add(panel, BorderLayout.CENTER);
f.add(printButton, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
System.out.println(panel.getPreferredSize());
System.out.println(panel.getSize());
}
}

What is wrong with this Java random software code?

I have made software in Java that generates random number in range. But it don't work. Sorry for strange language and comments. I have three classes: main, for generating and GUI. When I click button to generate it shows 0 on screen. Please help me.
public class glavnaKlasa {
static public int broj;
public static void main(String[] args) {
GUI guiObject = new GUI();
guiObject.mainGUI();
generisanje generisanjeObject = new generisanje();
broj = generisanjeObject.glavno(guiObject.min, guiObject.max);
}
}
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUI {
private JFrame frmNasumicniBroj;
private JTextField textField;
private JTextField textField_1;
private JLabel lblNasumicniBroj;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void mainGUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frmNasumicniBroj.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public int min, max;
private void initialize() {
frmNasumicniBroj = new JFrame();
frmNasumicniBroj.setTitle("Nasumicni broj");
frmNasumicniBroj.getContentPane().setBackground(Color.CYAN);
frmNasumicniBroj.setBounds(100, 100, 400, 300);
frmNasumicniBroj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmNasumicniBroj.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Donja granica: ");
lblNewLabel.setForeground(Color.YELLOW);
lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNewLabel.setBounds(10, 11, 154, 14);
frmNasumicniBroj.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setBounds(200, 8, 154, 20);
frmNasumicniBroj.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblGornjaGranica = new JLabel("Gornja granica: ");
lblGornjaGranica.setForeground(Color.YELLOW);
lblGornjaGranica.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblGornjaGranica.setBounds(10, 36, 165, 14);
frmNasumicniBroj.getContentPane().add(lblGornjaGranica);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(200, 33, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_1);
lblNasumicniBroj = new JLabel("Nasumicni broj: ");
lblNasumicniBroj.setForeground(Color.YELLOW);
lblNasumicniBroj.setFont(new Font("Wide Latin", Font.PLAIN, 12));
lblNasumicniBroj.setBounds(10, 144, 180, 14);
frmNasumicniBroj.getContentPane().add(lblNasumicniBroj);
textField_2 = new JTextField();
textField_2.setEditable(false);
textField_2.setBounds(200, 141, 154, 20);
frmNasumicniBroj.getContentPane().add(textField_2);
textField_2.setColumns(10);
JButton btnNewButton = new JButton("GENERISI");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
glavnaKlasa glKlasa = new glavnaKlasa();
String brString = Integer.toString(glKlasa.broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 14));
btnNewButton.setBounds(10, 61, 345, 72);
frmNasumicniBroj.getContentPane().add(btnNewButton);
JLabel lblVerzija = new JLabel("Verzija: 1.0");
lblVerzija.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
lblVerzija.setBounds(10, 180, 71, 14);
frmNasumicniBroj.getContentPane().add(lblVerzija);
JLabel label_1 = new JLabel("Autor: Djordje Milanovic");
label_1.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_1.setBounds(10, 205, 141, 14);
frmNasumicniBroj.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Copyright: Alfin Informatics");
label_2.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 11));
label_2.setBounds(9, 236, 166, 14);
frmNasumicniBroj.getContentPane().add(label_2);
}}
import java.util.Random;
import javax.swing.JOptionPane;
public class generisanje {
public static int glavno(int min, int max){
if (min >= max) {
JOptionPane.showMessageDialog(null, "Maksimalni broj mora biti veci od minimalnog");
}
Random rnd = new Random();
return rnd.nextInt((max - min) + 1) + min;
}
}
This:
glavnaKlasa glKlasa = new glavnaKlasa();
creates the object with empty constructor, your main will not run there, so broj remains uninitialized.
Actually, you don't need to instantiate this class there, just this:
public void actionPerformed(ActionEvent arg0) {
try{
min = Integer.parseInt(textField.getText());
max = Integer.parseInt(textField_1.getText());
int broj = generisanje.glavno(guiObject.min, guiObject.max);
String brString = Integer.toString(broj);
textField_2.setText(brString);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Also consider working according to Java coding standards ( class name first uppercase and so on, it will be much easier to maintain the code).

Error with logic or repaint/revalidate Java JFrame

What I am trying to do is this,
when I enter the details it will validate if the textFiled is empty when a button is pressed, if it is empty it will display a message saying that.
Then it will move to the next textFile similar to many web based registration forms,
what I am trying to find out is why wont the message change?
Pasting this code into an ecilpse file and running it should display the simple frame and what I am trying to do.
The message displays on the bottom of the frame when the firstname field is empty,
can anyone explain why it doesn't show the next message when the firstname field containes text and the middlename contains no text?
Most of the logic is at the bottom of the code.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Color;
import javax.swing.UIManager;
import javax.swing.JPanel;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class start {
private JFrame frame;
private JTextField tfFirstname;
private JTextField tfMiddlenames;
private JTextField tfSurname;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
start window = new start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public start() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 505, 429);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
final JPanel panelClientNew = new JPanel();
panelClientNew.setBackground(new Color(0, 102, 255));
panelClientNew.setBounds(10, 11, 469, 299);
frame.getContentPane().add(panelClientNew);
panelClientNew.setLayout(null);
JLabel lblFirstname = new JLabel("Firstname :");
lblFirstname.setHorizontalAlignment(SwingConstants.RIGHT);
lblFirstname.setVerticalAlignment(SwingConstants.BOTTOM);
lblFirstname.setForeground(new Color(255, 255, 255));
lblFirstname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblFirstname.setBounds(10, 16, 163, 14);
panelClientNew.add(lblFirstname);
tfFirstname = new JTextField();
tfFirstname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfFirstname.setBounds(177, 10, 282, 27);
panelClientNew.add(tfFirstname);
tfFirstname.setColumns(10);
JLabel lblMiddlenames = new JLabel("Middlenames :");
lblMiddlenames.setHorizontalAlignment(SwingConstants.RIGHT);
lblMiddlenames.setForeground(new Color(255, 255, 255));
lblMiddlenames.setFont(new Font("Tahoma", Font.BOLD, 13));
lblMiddlenames.setBounds(10, 47, 163, 14);
panelClientNew.add(lblMiddlenames);
tfMiddlenames = new JTextField();
tfMiddlenames.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfMiddlenames.setBounds(177, 41, 282, 27);
panelClientNew.add(tfMiddlenames);
tfMiddlenames.setColumns(10);
JLabel lblSurname = new JLabel("Surname :");
lblSurname.setHorizontalAlignment(SwingConstants.RIGHT);
lblSurname.setForeground(new Color(255, 255, 255));
lblSurname.setFont(new Font("Tahoma", Font.BOLD, 13));
lblSurname.setBounds(10, 78, 163, 14);
panelClientNew.add(lblSurname);
tfSurname = new JTextField();
tfSurname.setFont(new Font("Tahoma", Font.PLAIN, 13));
tfSurname.setBounds(177, 72, 282, 27);
panelClientNew.add(tfSurname);
tfSurname.setColumns(10);
JButton btnAdd = new JButton("Add");
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
/*
*
*
*
*I am trying to create a message that validates on certain circumstances
*
*
*
*/
if(tfFirstname.getText().equals(null) || tfFirstname.getText().equals("") || tfFirstname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Firstname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfMiddlenames.getText().equals(null) || tfMiddlenames.getText().equals("") || tfMiddlenames.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Middlenames :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else if (tfSurname.getText().equals(null) || tfSurname.getText().equals("") || tfSurname.getText().equals(false)) {
JPanel panelMessage = new JPanel();
panelMessage.setBackground(new Color(30, 144, 255));
panelMessage.setBounds(10, 321, 469, 29);
frame.getContentPane().add(panelMessage);
JLabel lblPersonSaved = new JLabel("Please Enter Surname :");
lblPersonSaved.setForeground(new Color(255, 255, 255));
lblPersonSaved.setFont(new Font("Tahoma", Font.BOLD, 15));
panelMessage.add(lblPersonSaved);
frame.revalidate();
panelMessage.revalidate();
frame.repaint();
}
else {
//Validation has passed
}
}
});
btnAdd.setBounds(370, 265, 89, 23);
panelClientNew.add(btnAdd);
}
}
I recommend that you use an InputVerifier as this will verify that the contents of the JTextField are correct (any way that you wish to define this) before allowing you to even leave the JTextField. Now it won't stop you from pressing other JButtons and whatnot, so you'll need to take other precautions if you have a submit button. An example of a simple InputVerifier that checks to see if the JTextField is empty is shown below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(true);
JPanel namePanel = new JPanel();
namePanel.add(new JLabel("Name:"));
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
add(warningLabel, BorderLayout.SOUTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty");
warningLabel.setBackground(WARNING_COLOR);
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
have look at DocumentListener,
on start_up to enable only first JTextField, if any (up to you) character was typed into first JTextField, then enable second JTextField, and so on...,
if you want to filtering, change or replace output came from keyboard the to use DocumentFilter
change background for example to Color.red (from DocumentListeners events), in the case that one of JTextFields contains incorect lenght, data e.g.
agree with HFOE about LayoutManagers

Categories