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());
}
}
Related
I'm trying to setup a system where when I press a button the JLabel text will change, but I can't seem to make it work. I've already tested that the action listener works by doing 'system.out.println("test");'. It works fine, but when trying to change a JComponent text it doesn't work. I've already searched for answers and found nothing that works.
Main class:
package com.fcs.app;
public class A {
public static void main(String args[]) {
window w = new window();
w.drawWindow();
}
}
JFrame and JPanel class:
package com.fcs.app;
import java.awt.*;
import javax.swing.*;
public class window extends JPanel {
JFrame jf = new JFrame();
JPanel jp = new JPanel();
JButton b1 = new JButton();
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JLabel plus = new JLabel();
JLabel equals = new JLabel();
JLabel rt = new JLabel();
int Result = 10;
public void drawWindow() {
//JFrame setup
jf.setSize(400, 400);
jf.setUndecorated(true);
jf.setLayout(null);
jf.setContentPane(jp);
jf.setLocation(100, 100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
//JPanel setup
jp.setSize(400, 400);
jp.setLocation(0, 0);
jp.setBackground(Color.WHITE);
jp.add(b1);
jp.add(tf1);
jp.add(tf2);
jp.add(plus);
jp.add(equals);
jp.add(rt);
jp.setLayout(null);
jp.setVisible(true);
//JButton setup
b1.setFont(new Font("Times", Font.PLAIN, 15));
b1.setText("Calculate!");
b1.setSize(100, 40);
b1.setLocation(150, 350);
b1.addActionListener(new Listener());
b1.setVisible(true);
//TextField 1 setup
tf1.setSize(120, 50);
tf1.setLocation(140, 20);
tf1.setFont(new Font("Times", Font.PLAIN, 25));
tf1.setHorizontalAlignment(JTextField.CENTER);
tf1.setVisible(true);
//TextField 2 setup
tf2.setSize(120, 50);
tf2.setLocation(140, 120);
tf2.setFont(new Font("Times", Font.PLAIN, 25));
tf2.setHorizontalAlignment(JTextField.CENTER);
tf2.setVisible(true);
//Plus sign Setup
plus.setSize(120, 50);
plus.setLocation(140, 70);
plus.setHorizontalAlignment(JLabel.CENTER);
plus.setFont(new Font("Times", Font.PLAIN, 40));
plus.setText("+");
plus.setVisible(true);
//Equals sign Setup
equals.setSize(120, 50);
equals.setLocation(140, 170);
equals.setHorizontalAlignment(JLabel.CENTER);
equals.setFont(new Font("Times", Font.PLAIN, 40));
equals.setText("=");
equals.setVisible(true);
//Result text
rt.setSize(400, 50);
rt.setLocation(0, 250);
rt.setHorizontalAlignment(JLabel.CENTER);
rt.setFont(new Font("Times", Font.PLAIN, 60));
rt.setText("");
rt.setVisible(true);
}
}
ActionListener class:
package com.fcs.app;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Listener implements ActionListener {
window w = new window();
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
w.rt.setText("Test");
}
}
You are creating new references of Window like window w = new window();
it will create a new instance of window and you are trying to change newly created window.
Try to pass the window object you have created before in window class or
implement an anonymous ActionListener in the window class.
b1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
rt.setText("Test");
}
}
});
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.
I want to make a "simple" program. it consists of three buttons and when you click on one of them i want a picture to show up, but i don't know how to add the image properly.
If anyone has played pokemon i want to make the start where you select your starter pokemon.
Here is my code.
public LayoutLek(){
super("Starter");
panel=new JPanel();
panel.setLayout(new GridLayout(2,1));
top_p=new JPanel();
label1=new JLabel("Make a choice");
label1.setFont(new Font("Arial", Font.BOLD, 30));
label1.setForeground(Color.black);
ImageIcon green = new ImageIcon("Bilder/bulbasaur.jpg"); //Dont know if it is correct but...
JLabel label2 = new JLabel(green);
top_p.setBackground(Color.yellow);
top_p.add(label1);
bottom_p=new JPanel();
bottom_p.setLayout(new GridLayout(1,3));
panel.add(top_p);
panel.add(bottom_p);
button1=new JButton("Button 1");
button1.setBackground(Color.green);
button1.setForeground(Color.black);
button1.setFont(new Font("Arial", Font.BOLD, 24));
button2=new JButton("Button 2");
button2.setBackground(Color.red);
button2.setForeground(Color.black);
button2.setFont(new Font("Arial", Font.BOLD, 24));
button3=new JButton("Button 3");
button3.setBackground(Color.blue);
button3.setForeground(Color.black);
button3.setFont(new Font("Arial", Font.BOLD, 24));
bottom_p.add(button1);
bottom_p.add(button2);
bottom_p.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
this.add(panel);
//this.setSize(350, 300);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setAlwaysOnTop(true);
}
public static void main(String[] args) {
new LayoutLek();
}
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked"); //Just to test
Object src = e.getSource();
if(src==button1){
//Here should the image show up
}
else if(src==button2){
}
else if(src==button3){
}
}
If anyone can help i would be thankful!
Images that are embedded into your program should be loaded from the class path, not the file system. When you pass a String to the ImageIcon your telling the program to look in the file system. To load from the class path, use
new ImageIcon(getClass().getResource("/Bilder/bulbasaur.jpg");
where Bilder need to be in the src
Your JLabel label2 is locally scoped within the constructor, so you can't access it from outside the constructor, i.e. the actionPerformed. You need to declare it outside the constructor, as class members, as you seem to have done with your other objects.
Have all three ImageIcons already initialized As class members also.
Just use label2.setIcon(oneOfTheImageIcons); in the actionPerformed to change the icon of the JLabel
Swing apps should be run from the Event Dispatch Thread. You can do so by wrapping your new LayoutLek(); in a SwingUtilities.invokeLater... See Initial Threads for complete details.
You never add your label2 to a visible conainter.
After fixing all the above mentioned points, here is a runnable refactor. You just need to change your file paths accordingly.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LayoutLek extends JFrame implements ActionListener {
JPanel panel;
JPanel top_p;
JLabel label1;
JPanel bottom_p;
JButton button1;
JButton button2;
JButton button3;
ImageIcon green;
ImageIcon blue;
ImageIcon red;
JLabel label2;
public LayoutLek() {
super("Starter");
green = new ImageIcon(getClass().getResource("/path/to/imgage"));
blue = new ImageIcon(getClass().getResource("/path/to/imgage"));
red = new ImageIcon(getClass().getResource("/path/to/imgage"));
label2 = new JLabel(green);
panel = new JPanel();
panel.setLayout(new GridLayout(2, 1));
top_p = new JPanel();
label1 = new JLabel("Make a choice");
label1.setFont(new Font("Arial", Font.BOLD, 30));
label1.setForeground(Color.black);
top_p.setBackground(Color.yellow);
top_p.add(label1);
bottom_p = new JPanel();
bottom_p.setLayout(new GridLayout(1, 3));
panel.add(top_p);
panel.add(bottom_p);
button1 = new JButton("Button 1");
button1.setBackground(Color.green);
button1.setForeground(Color.black);
button1.setFont(new Font("Arial", Font.BOLD, 24));
button2 = new JButton("Button 2");
button2.setBackground(Color.red);
button2.setForeground(Color.black);
button2.setFont(new Font("Arial", Font.BOLD, 24));
button3 = new JButton("Button 3");
button3.setBackground(Color.blue);
button3.setForeground(Color.black);
button3.setFont(new Font("Arial", Font.BOLD, 24));
bottom_p.add(button1);
bottom_p.add(button2);
bottom_p.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
this.add(panel);
this.add(label2, BorderLayout.PAGE_START);
//this.setSize(350, 300);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setAlwaysOnTop(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new LayoutLek();
}
});
}
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked"); //Just to test
Object src = e.getSource();
if (src == button1) {
label2.setIcon(green);
} else if (src == button2) {
label2.setIcon(blue);
} else if (src == button3) {
label2.setIcon(red);
}
}
}
Firstly, src.equals(button1). It's better practise to use the object-based equals method, == is better applied to primitive comparison (i.e. int, long, boolean, etc).
Secondly, you can do a couple of things.
Add the image to a container, then remove it and add another each time a button is clicked.
Add all three images to a container, set them all to invisible (setVisible(false)) and then in src.equals(button1/2/3) you set the appropriate image to visible. Container may need to be repainted.
Hope this helps!
I would write on a JPanel a String much bigger respect than other element.which could be the way to paint a string in terms of simply?There is a method to do this?
You could add the text as a JLabel component and change its font size.
public static void main(String[] args) {
NewJFrame1 frame = new NewJFrame1();
frame.setLayout(new GridBagLayout());
JPanel panel = new JPanel();
JLabel jlabel = new JLabel("This is a label");
jlabel.setFont(new Font("Verdana",1,20));
panel.add(jlabel);
panel.setBorder(new LineBorder(Color.BLACK)); // make it easy to see
frame.add(panel, new GridBagConstraints());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(NewJFrame1.EXIT_ON_CLOSE);
frame.setVisible(true);
}
The code will run and look like this :
see also Java layout manager vertical center for more info
JLabel supports HTML 3.2 formating, so you can use header tags if you don't want to mess with fonts.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HtmlHeadersSample extends JFrame {
public HtmlHeadersSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setLocation(100, 100);
JLabel label1 = new JLabel();
label1.setText("simple text");
label1.setBounds(0, 0, 200, 50);
JLabel label2 = new JLabel();
label2.setText("<html><h1>header1 text</h1></html>");
label2.setBounds(0, 20, 200, 50);
JLabel label3 = new JLabel();
label3.setText("<html><h2>header2 text</h2></html>");
label3.setBounds(0, 40, 200, 50);
JLabel label4 = new JLabel();
label4.setText("<html><h3>header3 text</h3></html>");
label4.setBounds(0, 60, 200, 50);
add(label1);
add(label2);
add(label3);
add(label4);
setVisible(true);
}
public static void main(String[] args) {
new HtmlHeadersSample();
}
}
Here's how it looks like:
Just set the size of your font
JLabel bigLabel = new JLabel("Bigger text");
bigLabel.setFont(new Font("Arial", 0, 30));
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