output string using java textfield.setText() by using for loop - java

The question is, I try to make second textfield (textFieldGen) to print out the exact result likes console. Currently, second textfield shows one string only.
This is my first coding on java GUI.
(extra info, I built it using Eclipse with WindowBuilder + GEF )
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.TextField;
import java.awt.Label;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class PassGenerator {
private JFrame frmPasswordGenerator;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PassGenerator window = new PassGenerator();
window.frmPasswordGenerator.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PassGenerator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmPasswordGenerator = new JFrame();
frmPasswordGenerator.setTitle("Password Generator");
frmPasswordGenerator.setBounds(100, 100, 419, 229);
frmPasswordGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmPasswordGenerator.getContentPane().setLayout(null);
final TextField textFieldGen = new TextField();
final TextField textFieldPass = new TextField();
textFieldPass.setBounds(74, 60, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldPass);
Label labelPass = new Label("Password Length:");
labelPass.setBounds(74, 33, 177, 21);
frmPasswordGenerator.getContentPane().add(labelPass);
Button genButton = new Button("Generate");
genButton.setBounds(262, 60, 86, 23);
frmPasswordGenerator.getContentPane().add(genButton);
// Add action listener to button
genButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
//System.out.println("You clicked the button");
String getTxt = textFieldPass.getText();
boolean y = true;
do{
try{
int c = Integer.parseInt(getTxt);
Random r = new Random();
String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x","y","z"};
int nc = 0-c;
int c2 = c/2;
int nc2 = 0-c2;
int ncm = (nc+1)/2;
if (c%2 == 0){
for(int x = nc2; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
}
else {
for(int x = ncm; x<0;x++){
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
int numNum = r.nextInt(10);
System.out.print(numNum);
textFieldGen.setText(Integer.toString(numNum));
}
y = false;
}
catch (NumberFormatException e1 ){
int messageType = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(null, "Please Enter Integer only", "Error!!", messageType);
y = false;
}
}while (y);
}
});
Label labelGen = new Label("Generated Password:");
labelGen.setBounds(74, 109, 149, 21);
frmPasswordGenerator.getContentPane().add(labelGen);
textFieldGen.setBounds(74, 136, 149, 19);
frmPasswordGenerator.getContentPane().add(textFieldGen);
Button copyButton = new Button("Copy");
copyButton.setBounds(262, 136, 86, 23);
frmPasswordGenerator.getContentPane().add(copyButton);
}
}

Use textFieldGen.setText (textFieldGen.getText () + "\n" + Integer.toString(numNum))

I don't see why you are setting the contents of the text field twice. I would just do:
int alphaNum = r.nextInt(26);
System.out.print(alphabet[alphaNum]);
String alpha = alphabet[alphaNum];
//textFieldGen.setText(alpha.toString());
int numNum = r.nextInt(10);
System.out.print(numNum);
//textFieldGen.setText(Integer.toString(numNum));
textFieldGen.setText(alpha + Integer.toString(numNum));
In general it is not a good practice to replace the entire text when all you want to do is append some characters to the text field. If you don't like the above then you can do:
textField.setText(alpha);
...
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), Integer.toString(numNum), null);
Edit:
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JTextField textField = new JTextField(20);
add( textField );
textField.setText( "testing: " );
try
{
Document doc = textField.getDocument();
doc.insertString(doc.getLength(), "1", null);
}
catch(Exception e) {}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

Related

Swing Components invisible

When I run my code there is only the empty frame. To see the JButton and the JTextFields I have to search and click on them before they are visible. I searched everywhere on the Internet but I found nothing. I also set the visibility to true and added the JComponents. Here is my Code:
Frame Fenster = new Frame();
And this...
package me.JavaProgramm;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
public class Frame extends JFrame {
private JButton bChange;
private JTextField tvonEur;
private JTextField tzuOCur; //andere Währung (other Currency)
private JTextField tzuEur;
private JTextField tvonOCur;
private JComboBox cbCur; //Wärhung wählen
private String curName;
private double faktorUSD;
private double faktorGBP;
private static String[] comboCur = {"USD", "GBP"};
public Frame() {
setLayout(null);
setVisible(true);
setSize(400, 400);
setTitle("Währungsrechner");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Font schrift = new Font("Serif", Font.PLAIN + Font.ITALIC, 30);
tvonEur = new JTextField("Euro");
tvonEur.setSize(80, 25);
tvonEur.setLocation(20, 50);
tvonEur.requestFocusInWindow();
tvonEur.selectAll();
tzuEur = new JTextField("Euro");
tzuEur.setSize(80, 25);
tzuEur.setLocation(20, 150);
tzuEur.requestFocusInWindow();
tzuEur.selectAll();
bChange = new JButton("Euro zu US-Dollar");
bChange.setSize(120, 25);
bChange.setLocation(110, 50);
tzuOCur = new JTextField("US-Dollar");
tzuOCur.setSize(80, 25);
tzuOCur.setLocation(240, 50);
tzuOCur.requestFocusInWindow();
tzuOCur.selectAll();
tvonOCur = new JTextField("US-Dollar");
tvonOCur.setSize(80, 25);
tvonOCur.setLocation(240, 50);
tvonOCur.requestFocusInWindow();
tvonOCur.selectAll();
cbCur = new JComboBox(comboCur);
cbCur.setSize(100, 20);
cbCur.setLocation(100, 100);
tvonEur.setVisible(true);
tzuEur.setVisible(true);
tzuOCur.setVisible(true);
tvonOCur.setVisible(true);
bChange.setVisible(true);
cbCur.setVisible(true);
add(tvonEur);
add(bChange);
add(tzuOCur);
add(cbCur);
Currency currency = new Currency();
String strUSD = currency.convertUSD();
try {
NumberFormat formatUSD = NumberFormat.getInstance(Locale.GERMANY);
Number numberUSD = formatUSD.parse(strUSD);
faktorUSD = numberUSD.doubleValue();
System.out.println(faktorUSD);
} catch (ParseException e) {
System.out.println(e);
}
String strGBP = currency.convertGBP();
try {
NumberFormat formatGBP = NumberFormat.getInstance(Locale.GERMANY);
Number numberGBP = formatGBP.parse(strGBP);
faktorGBP = numberGBP.doubleValue();
System.out.println(faktorGBP);
} catch (ParseException e) {
System.out.println(e);
}
cbCur.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cbCur = (JComboBox) e.getSource();
curName = (String) cbCur.getSelectedItem();
if (curName == "USD") {
tzuOCur.setText("US-Dollar");
} else if (curName == "GBP") {
tzuOCur.setText("British-Pound");
}
}
});
bChange.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (curName == "USD") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleUSD = doubleEUR * faktorUSD;
tzuOCur.setText(Double.toString(roundScale3(doubleUSD)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
} else if (curName == "GBP") {
try {
Double doubleEUR = Double.parseDouble(tvonEur.getText());
Double doubleGBP = doubleEUR * faktorGBP;
tzuOCur.setText(Double.toString(roundScale3(doubleGBP)));
} catch (NumberFormatException nfe) {
System.out.println("Gebe einen richten Wert ein!");
}
}
}
});
}
public static double roundScale3(double d) {
return Math.rint(d * 1000) / 1000.;
}
}
Try moving setVisible(true) after you add the children to the parent container.
Generally with Swing it's considered good practice to put code that updates visible components in the event dispatching thread, like this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame.this.setVisible(true);
}
});

Swing delay between calls

I'm trying to make a program that load 4 images, put it in 4 labels and change the icons of each label in the frame regarding the random number in the list, like if it was blinking the images. It need to blink each image in the order that is sorted in comecaJogo() but when I press the btnComecar in the actionPerformed all imagens seems to change at the same time:
Here is my logic class:
public class Logica {
List<Integer> seqAlea = new ArrayList<Integer>();
List<Integer> seqInsere = new ArrayList<Integer>();
int placar = 0;
boolean cabouGame = false;
Random geraNumero = new Random();
int numero;
Timer timer = new Timer(1500,null);
public void comecaJogo() {
for (int i = 0; i < 4; i++) {
numero = geraNumero.nextInt(4) + 1;
seqAlea.add(numero);
}
}
public void piscaImagen(ImageIcon img1, ImageIcon img1b, JLabel lbl) {
timer.addActionListener(new ActionListener() {
int count = 0;
#Override
public void actionPerformed(ActionEvent evt) {
if(lbl.getIcon() != img1){
lbl.setIcon(img1);
} else {
lbl.setIcon(img1b);
}
count++;
if(count == 2){
((Timer)evt.getSource()).stop();
}
}
});
timer.setInitialDelay(1250);
timer.start();
}
}
In the frame:
public class Main extends JFrame implements ActionListener {
JLabel lblImg1 = new JLabel();
JButton btnImg1 = new JButton("Economize Energia");
final URL resource1 = getClass().getResource("/br/unip/IMGs/img1.jpg");
final URL resource1b = getClass().getResource("/br/unip/IMGs/img1_b.png");
ImageIcon img1 = new ImageIcon(resource1);
ImageIcon img1b = new ImageIcon(resource1b);
JButton btnImg2 = new JButton("Preserve o Meio Ambiente");
JLabel lblImg2 = new JLabel("");
final URL resource2 = getClass().getResource("/br/unip/IMGs/img2.jpg");
final URL resource2b = getClass().getResource("/br/unip/IMGs/img2_b.jpg");
ImageIcon img2 = new ImageIcon(resource2);
ImageIcon img2b = new ImageIcon(resource2b);
JButton btnImg3 = new JButton("N\u00E3o \u00E0 polui\u00E7\u00E3o!");
JLabel lblImg3 = new JLabel("");
final URL resource3 = getClass().getResource("/br/unip/IMGs/img3.jpg");
final URL resource3b = getClass().getResource("/br/unip/IMGs/img3_b.jpg");
ImageIcon img3 = new ImageIcon(resource3);
ImageIcon img3b = new ImageIcon(resource3b);
JButton btnImg4 = new JButton("Recicle!");
JLabel lblImg4 = new JLabel("");
final URL resource4 = getClass().getResource("/br/unip/IMGs/img4.jpg");
final URL resource4b = getClass().getResource("/br/unip/IMGs/img4_b.jpg");
ImageIcon img4 = new ImageIcon(resource4);
ImageIcon img4b = new ImageIcon(resource4b);
Logica jogo = new Logica();
JButton btnComecar = new JButton("Come\u00E7ar");
public static void main(String[] args) {
Main window = new Main();
window.setVisible(true);
}
public Main() {
lblImg1.setIcon(img1b);
lblImg1.setBounds(78, 48, 250, 200);
add(lblImg1);
btnImg1.setBounds(153, 259, 89, 23);
btnImg1.addActionListener(this);
add(btnImg1);
setBounds(100, 100, 800, 600);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btnImg2.setBounds(456, 272, 186, 23);
btnImg2.addActionListener(this);
lblImg2.setIcon(img2b);
lblImg2.setBounds(421, 61, 250, 200);
add(btnImg2);
add(lblImg2);
btnImg3.setBounds(114, 525, 186, 23);
btnImg3.addActionListener(this);
lblImg3.setIcon(img3b);
lblImg3.setBounds(78, 314, 250, 200);
add(lblImg3);
add(btnImg3);
btnImg4.setBounds(456, 525, 186, 23);
btnImg4.addActionListener(this);
lblImg4.setIcon(img4b);
lblImg4.setBounds(421, 314, 250, 200);
add(lblImg4);
add(btnImg4);
btnComecar.setBounds(68, 14, 89, 23);
btnComecar.addActionListener(this);
add(btnComecar);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource().equals(btnImg1)) {
jogo.piscaImagen(img1, img1b, lblImg1);
} else if (e.getSource().equals(btnComecar)) {
jogo.comecaJogo();
System.out.println(jogo.seqAlea);
for (int i = 0; i < jogo.seqAlea.size(); i++) {
switch (jogo.seqAlea.get(i)) {
case 1:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img1, img1b, lblImg1);
break;
case 2:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img2, img2b, lblImg2);
break;
case 3:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img3, img3b, lblImg3);
break;
case 4:
System.out.println("Posição: " + i + " " + jogo.seqAlea.get(i));
jogo.piscaImagen(img4, img4b, lblImg4);
break;
}
}
}
}
}
Thanks for the help!
one at time, like a memory game :)
There are multitudes of ways this might work, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main extends JFrame implements ActionListener {
JButton btnImg1 = new JButton();
JButton btnImg2 = new JButton();
JButton btnImg3 = new JButton();
JButton btnImg4 = new JButton();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Main();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public Main() {
JPanel buttons = new JPanel(new GridLayout(2, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
buttons.add(btnImg1);
buttons.add(btnImg2);
buttons.add(btnImg3);
buttons.add(btnImg4);
add(buttons);
JButton play = new JButton("Play");
add(play, BorderLayout.SOUTH);
play.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
List<JButton> sequence = new ArrayList<>(Arrays.asList(new JButton[]{btnImg1, btnImg2, btnImg3, btnImg4}));
Collections.shuffle(sequence);
Timer timer = new Timer(1000, new ActionListener() {
private JButton last;
#Override
public void actionPerformed(ActionEvent e) {
if (last != null) {
last.setBackground(null);
}
if (!sequence.isEmpty()) {
JButton btn = sequence.remove(0);
btn.setBackground(Color.RED);
last = btn;
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setInitialDelay(0);
timer.start();
}
}
This just places all the buttons into a List, shuffles the list and then the Timer removes the first button from the List until all the buttons have been "flashed".
Now this is just using the button's backgroundColor, so you'd need to create a class which allows you to associate the JButton with "on" and "off" images, these would then be added to the List and the Timer executed in a similar manner as above

Check if the jlabel icons are the same and compare with the components of the drawing lines

Hello I have to finish a project but I can't get further. The project is about having jlabels with icons generated dynamically on two sides (left and right) .
The icons are in different order on each side and there is a one to one icon relationship.
As an example one picture : link
Now you can draw lines from the left to the right between those pictures and after clicking on the check button it should tell you if its true or false :
Again one picture : link
My question is how can I compare the icons to know which combination is the right one and after comparing the drawings?
I already created two lists to know the component combination of the drawings.
Here is the code so far -
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class CatSameCoins{
public static JLabel label;
public ActionListener btn1Listener;
public ActionListener btn2Listener;
public ActionListener btn3Listener;
public ActionListener btn4Listener;
public ActionListener btn5Listener;
public ActionListener btn6Listener;
public JButton btn1;
public JButton btn2;
public JButton btn3;
public JButton btn4;
public JButton btn5;
public JButton btn6;
public JButton btnCheck;
public ArrayList<String> listto = new ArrayList<String>();
public ArrayList<String> listfrom = new ArrayList<String>();
public static boolean drawing = false;
public static List<Shape> shapes = new ArrayList<Shape> ();
public static Shape currentShape = null;
static Component fromComponent;
private JLabel lblCheck;
public void drawLine(Component from , Component to){
listfrom.add(from.getName()); //first list with component names from where the drawing start
listto.add(to.getName()); //second list with component names where the drawing ends
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX()+from.getWidth()/2; //get middle
fromPoint.y = from.getY()+from.getHeight()/2; //get middle
toPoint.x = to.getX()+to.getWidth()/2;
toPoint.y = to.getY()+to.getHeight()/2;
currentShape = new Line2D.Double (fromPoint, toPoint);
shapes.add (currentShape);
label.repaint();
drawing = false;
}
public CatSameCoins(){
JFrame frame = new JFrame ();
frame.getContentPane().setLayout(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
listfrom.removeAll(listfrom);
drawing= false;
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("btn1");
btn1.setBounds(21, 88, 45, 97);
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
btn1.removeActionListener(this);
}
};
btn1.addActionListener(btn1Listener);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("btn2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
btn2.removeActionListener(this);
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("btn3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
btn3.removeActionListener(this);
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("btn4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn4);
drawing = false;
btn4.removeActionListener(this);
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("btn5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn5);
drawing = false;
btn5.removeActionListener(this);
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("btn6");
btn6.setBounds(407, 307, 45, 91);
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(drawing == true){
drawLine(fromComponent,btn6);
drawing = false;
btn6.removeActionListener(this);
}
}
};
btn6.addActionListener(btn6Listener);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0;i< listfrom.size();i++){
System.out.println(listfrom.get(i)+" - "+listto.get(i));
}
lblCheck.setText("False");
//if().... lblCheck.setText("True")
//else lblCheck.setText("False")
/*if(btn6.getIcon().toString().equals(btn1.getIcon().toString())){
System.out.println("yes");
}
else{
System.out.println("neah");
}*/
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel (){
protected void paintComponent ( Graphics g )
{
Graphics2D g2d = ( Graphics2D ) g;
g2d.setPaint ( Color.black);
g2d.setStroke(new BasicStroke(5));
for ( Shape shape : shapes )
{
g2d.draw ( shape );
repaint();
}
}
} ;
label.setSize(500,500);
frame.getContentPane().add (label);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize ( 500, 500 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
public static void main ( String[] args )
{
new CatSameCoins();
}
}
Would really appreciate for any help ;) .
Its done,
Solution : you can try it just change icon names for the second hashmap
I know this is not the best solution but at least i tried. I will try to improve it.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
public class Hashmap {
private JLabel label;
private ActionListener btn1Listener;
private ActionListener btn2Listener;
private ActionListener btn3Listener;
private ActionListener btn4Listener;
private ActionListener btn5Listener;
private ActionListener btn6Listener;
private JButton btn1;
private JButton btn2;
private JButton btn3;
private JButton btn4;
private JButton btn5;
private JButton btn6;
private JButton btnCheck;
private JButton btnNext;
private boolean drawing = false;
private Shape currentShape = null;
private Component fromComponent;
private JLabel lblCheck;
private List<Shape> shapes = new ArrayList<Shape>();
private HashMap<String, String> userLines = new HashMap<String, String>();
private HashMap<String, String> resultLines = new HashMap<String, String>();
private HashMap<String, String> icons = new HashMap<String, String>();
public void drawLine(Component from, Component to) {
userLines.put(from.getName(), to.getName());
Point fromPoint = new Point();
Point toPoint = new Point();
fromPoint.x = from.getX() + from.getWidth() / 2; // get middle
fromPoint.y = from.getY() + from.getHeight() / 2; // get middle
toPoint.x = to.getX() + to.getWidth() / 2;
toPoint.y = to.getY() + to.getHeight() / 2;
currentShape = new Line2D.Double(fromPoint, toPoint);
shapes.add(currentShape);
label.repaint();
drawing = false;
}
#SuppressWarnings("serial")
public Hashmap() {
loadIcons();
JFrame frame = new JFrame();
frame.getContentPane().setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
JButton btnremove = new JButton("remove-drawings");
btnremove.setBounds(139, 39, 216, 23);
btnremove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
shapes.removeAll(shapes);
drawing = false;
userLines.clear();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
frame.getContentPane().add(btnremove);
btn1 = new JButton("1");
btn1.setName("1");
btn1Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn1;
}
};
btn1.addActionListener(btn1Listener);
btn1.setBounds(21, 88, 45, 97);
frame.getContentPane().add(btn1);
btn2 = new JButton("2");
btn2.setName("2");
btn2Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn2;
}
};
btn2.addActionListener(btn2Listener);
btn2.setBounds(21, 196, 45, 97);
frame.getContentPane().add(btn2);
btn3 = new JButton("3");
btn3.setName("3");
btn3Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
drawing = true;
fromComponent = btn3;
}
};
btn3.addActionListener(btn3Listener);
btn3.setBounds(21, 307, 45, 97);
frame.getContentPane().add(btn3);
btn4 = new JButton("4");
btn4.setName("4");
btn4Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn4);
drawing = false;
btn4.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn4.addActionListener(btn4Listener);
btn4.setBounds(407, 88, 45, 97);
frame.getContentPane().add(btn4);
btn5 = new JButton("5");
btn5.setName("5");
btn5Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn5);
drawing = false;
btn5.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn5.addActionListener(btn5Listener);
btn5.setBounds(407, 202, 45, 91);
frame.getContentPane().add(btn5);
btn6 = new JButton("6");
btn6.setName("6");
btn6Listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (drawing == true) {
drawLine(fromComponent, btn6);
drawing = false;
btn6.removeActionListener(this);
if (fromComponent.equals(btn1)) {
btn1.removeActionListener(btn1Listener);
}
if (fromComponent.equals(btn2)) {
btn2.removeActionListener(btn2Listener);
}
if (fromComponent.equals(btn3)) {
btn3.removeActionListener(btn3Listener);
}
}
}
};
btn6.addActionListener(btn6Listener);
btn6.setBounds(407, 307, 45, 91);
frame.getContentPane().add(btn6);
btnCheck = new JButton("check");
btnCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (resultLines.equals(userLines) && !userLines.isEmpty()) {
lblCheck.setText("true");
} else {
lblCheck.setText("false");
}
}
});
btnCheck.setBounds(171, 405, 143, 46);
frame.getContentPane().add(btnCheck);
btnNext = new JButton("next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userLines.clear();
resultLines.clear();
shapes.removeAll(shapes);
drawing = false;
changeCombination();
btn1.addActionListener(btn1Listener);
btn2.addActionListener(btn2Listener);
btn3.addActionListener(btn3Listener);
btn4.addActionListener(btn4Listener);
btn5.addActionListener(btn5Listener);
btn6.addActionListener(btn6Listener);
}
});
btnNext.setBounds(335, 435, 117, 25);
frame.getContentPane().add(btnNext);
lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.CENTER);
lblCheck.setBounds(84, 405, 80, 46);
frame.getContentPane().add(lblCheck);
label = new JLabel() {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.black);
g2d.setStroke(new BasicStroke(3));
for (Shape shape : shapes) {
g2d.draw(shape);
repaint();
}
}
};
label.setSize(frame.getWidth(), frame.getHeight());
frame.getContentPane().add(label);
frame.setVisible(true);
}
private void loadIcons() {
icons.clear();
icons.put("money/coin2/1_Cent.png", "money/coin2/1_Cent.png");
icons.put("money/coin2/5_Cent.png", "money/coin2/5_Cent.png");
icons.put("money/coin2/10_Cent.png", "money/coin2/10_Cent.png");
icons.put("money/coin2/20_Cent.png", "money/coin2/20_Cent.png");
icons.put("money/coin2/50_Cent.png", "money/coin2/50_Cent.png");
icons.put("money/coin2/2_Euro.png", "money/coin2/2_Euro.png");
icons.put("money/coin2/1_Euro.png", "money/coin2/1_Euro.png");
}
public void changeCombination() {
Random randLeftSide = new Random();
Random randRightSide = new Random();
while (resultLines.size() < 3) {
int left = randLeftSide.nextInt(3 - 1 + 1) + 1;
int right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("leftside: "+left+"rightside: "+y);
while (resultLines.containsKey(String.valueOf(left))) {
if (resultLines.size() > 3) {
break;
} else {
left = randLeftSide.nextInt(3 - 1 + 1) + 1;
// System.out.println("leftside : "+left);
}
}
while (resultLines.containsValue(String.valueOf(right))) {
if (resultLines.size() > 3) {
break;
} else {
right = randRightSide.nextInt(6 - 4 + 1) + 4;
// System.out.println("rightside: "+right);
}
}
resultLines.put(String.valueOf(left), String.valueOf(right));
}
// System.out.println("TOTAL MAP: "+resultLines.toString());
changeImages();
}
private void changeImages() {
List<Integer> randomIcon = new ArrayList<Integer>(); //creating array list for the icon random numbers
List<Integer> randomLines = new ArrayList<Integer>(); //creating array list for the lines random numbers
for (int i = 0; i < resultLines.size(); i++) {
int randomIndexIcon = new Random().nextInt(icons.size()); //generate random number for the icons from the hashmap
while (randomIcon.contains(randomIndexIcon)) { //while the list contains the random number generate a new one to prevent printing same pictures
randomIndexIcon = new Random().nextInt(icons.size());
}
randomIcon.add(randomIndexIcon); //add to the array list of the icon random numbers the generated random number
int randomIndexResult = new Random().nextInt(resultLines.size()); //generate random number for the lines
while (randomLines.contains(randomIndexResult)) { //while for second list to prevent generating same numbers
randomIndexResult = new Random().nextInt(resultLines.size());
}
randomLines.add(randomIndexResult); //add to the array list of the lines random numbers the generated random number
Object iconValue = icons.values().toArray()[randomIndexIcon]; //this is to get the icon string
Object valueLeft = resultLines.keySet().toArray()[randomIndexResult]; //this is to get the random key value from the resultLines map (left side)
if (valueLeft.equals("1")) { //check conditions
btn1.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("2")) {
btn2.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueLeft.equals("3")) {
btn3.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
Object valueRight = resultLines.values().toArray()[randomIndexResult]; //get the values from the hashmap (right side)
if (valueRight.equals("4")) { //check conditions
btn4.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("5")) {
btn5.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
if (valueRight.equals("6")) {
btn6.setIcon(new ImageIcon(getClass().getResource(
iconValue.toString())));
}
}
}
public static void main(String[] args) {
new Hashmap();
}
}

How to search for mulitple words then count them. Made code for only one word

i have this code that i made and i`m having a problem with the program.
This program is a Word counter with a interface that i created.
It counts how many times i wrote in test.txt word "Vlad Enache" *(my name) . The problem is i don't know how can i make this to search for multiple words , let`s say Vlad Enache, and word dog and cat. And i wanna know how can i define these words from user input in another frame with fields.
Thanks:)
import java.awt.Color;
import java.awt.EventQueue;
import java.io.*;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JTextArea;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class Andreea {
private JFrame frame;
private JTextField textField;
private JButton btnNewButton;
private JLabel lblNewLabel;
private JTextArea txtrVlad;
private JMenuBar menuBar_2;
private JMenu menu;
private JMenuItem menuItem;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Andreea window = new Andreea();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Read from file
* #throws IOException
*/
public int ReadFromFile() throws IOException{
BufferedReader br;
Scanner ob;
br = new BufferedReader(new FileReader("D:/test.txt"));
ob = new Scanner("PULA");
String str=ob.next();
String str1="",str2="";
int count=0;
while((str1=br.readLine())!=null)
{
str2 +=str1;
}
int index = str2.indexOf(str);
while (index != -1) {
count++;
str2 = str2.substring(index + 1);
index = str2.indexOf(str);
}
return count;
}
/**
* Create the application.
* #throws IOException
*/
public Andreea() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(255, 255, 255));
frame.setBounds(100, 100, 497, 399);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBackground(new Color(255, 255, 255));
textField.setForeground(new Color(0, 204, 204));
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setEditable(false);
textField.setFont(new Font("Georgia", Font.BOLD | Font.ITALIC, 20));
textField.setBounds(129, 190, 223, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnCount = new JButton("Count");
btnCount.setFont(new Font("Verdana", Font.BOLD | Font.ITALIC, 10));
btnCount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int count=0;
try {
count = ReadFromFile();
} catch (IOException e) {
e.printStackTrace();
}
String str="";
str += count;
textField.setText(str + " Times" );
}
});
btnCount.setBounds(60, 270, 130, 45);
frame.getContentPane().add(btnCount);
btnNewButton = new JButton("Reseteaza Counter");
btnNewButton.setFont(new Font("Verdana", Font.BOLD | Font.ITALIC, 10));
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(null);
}
});
btnNewButton.setBounds(293, 267, 130, 45);
frame.getContentPane().add(btnNewButton);
lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("C:/...."));
lblNewLabel.setBounds(0, 0, 480, 179);
frame.getContentPane().add(lblNewLabel);
txtrVlad = new JTextArea();
txtrVlad.setText("\u00A9 2014 Vlad Enache (4594)");
txtrVlad.setBounds(310, 338, 204, 22);
frame.getContentPane().add(txtrVlad);
menuBar_2 = new JMenuBar();
frame.setJMenuBar(menuBar_2);
menu = new JMenu("New menu");
menuBar_2.add(menu);
menuItem = new JMenuItem("New menu item");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
menu.add(menuItem);
}
}
Here is one possible solution. Note that this code assume one token per line. You can go back to String.indexOf if it is not the case.
public int[] ReadFromFile(final String[] tokens) throws IOException
{
final int[] counters = new int[tokens.length];
BufferedReader br;
br = new BufferedReader(new FileReader("D:/test.txt"));
String str1 = "";
while ((str1 = br.readLine()) != null)
{
for (int i = 0; i < tokens.length; i++)
if (str1.contains(tokens[i]))//if the line contains the token
counters[i]++;// increase counter for the index of the token
}
return counters;
}
...
public void actionPerformed(ActionEvent arg0)
{
//final String[] tokens = new String[] { "Vlad Enache", "dog", "cat" };
final String[] tokens = textField.getText().split(", ");//get token directly from JTextfield.
// Would make more sense to use a different JtextField for input and output.
//This is just an example
try
{
int[] count;
count = ReadFromFile(tokens);
final StringBuilder sb = new StringBuilder();//storing the result in a stringbuilder
/* to display the utterance of each token
for (int i = 0; i < count.length; i++)
sb.append(tokens[i] + " is repeated " + count[i] + " times\n");
textField.setText(sb.toString());//displaying result
*/
//to sum up all count value
int sum = 0;
for(int c : count)
sum+=c;
textField.setText(sum+" times");
}
catch (IOException e)
{
e.printStackTrace();
}
}
final String[] tokens = textField.getText().split(", ");
i got this that get`s token directly from JTextfield.
let`s say i got textField_1 in another form that it is in another class. how to use final String[] tokens = textField_1.getText().split(", ");??????

Clicking on the search button in JFrame is not opening the JDialog

I have a jframe with page navigation buttons,print,search buttons.When i clicked on the print button it is perfectly opening the window and i am able to print the page also.But when i clicked on search button i am not able to get the window.My requirement is clicking on the Search button should open a window(same as print window) with text field and when i enter the search data then it should display the matches and unmatches.
I have tried the below code but i am not succeed.
import com.google.common.base.CharMatcher;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import com.sun.pdfview.PagePanel;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import static com.google.common.base.Strings.isNullOrEmpty;
public class PdfViewer extends JPanel {
private static enum Navigation {
GO_FIRST_PAGE, FORWARD, BACKWARD, GO_LAST_PAGE, GO_N_PAGE
}
private static final CharMatcher POSITIVE_DIGITAL = CharMatcher.anyOf("0123456789");
private static final String GO_PAGE_TEMPLATE = "%s of %s";
private static final int FIRST_PAGE = 1;
private int currentPage = FIRST_PAGE;
private JButton btnFirstPage;
private JButton btnPreviousPage;
private JTextField txtGoPage;
private JButton btnNextPage;
private JButton btnLastPage;
private JButton print;
private JButton search;
private PagePanel pagePanel;
private PDFFile pdfFile;
public PdfViewer() {
initial();
}
private void initial() {
setLayout(new BorderLayout(0, 0));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
add(topPanel, BorderLayout.NORTH);
btnFirstPage = createButton("|<<");
topPanel.add(btnFirstPage);
btnPreviousPage = createButton("<<");
topPanel.add(btnPreviousPage);
txtGoPage = new JTextField(10);
txtGoPage.setHorizontalAlignment(JTextField.CENTER);
topPanel.add(txtGoPage);
btnNextPage = createButton(">>");
topPanel.add(btnNextPage);
btnLastPage = createButton(">>|");
topPanel.add(btnLastPage);
print = new JButton("print");
topPanel.add(print);
search = new JButton("search");
topPanel.add(search);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
JPanel viewPanel = new JPanel(new BorderLayout(0, 0));
scrollPane.setViewportView(viewPanel);
pagePanel = new PagePanel();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
pagePanel.setPreferredSize(screenSize);
viewPanel.add(pagePanel, BorderLayout.CENTER);
disableAllNavigationButton();
btnFirstPage.addActionListener(new PageNavigationListener(Navigation.GO_FIRST_PAGE));
btnPreviousPage.addActionListener(new PageNavigationListener(Navigation.BACKWARD));
btnNextPage.addActionListener(new PageNavigationListener(Navigation.FORWARD));
btnLastPage.addActionListener(new PageNavigationListener(Navigation.GO_LAST_PAGE));
txtGoPage.addActionListener(new PageNavigationListener(Navigation.GO_N_PAGE));
print.addActionListener(new PrintUIWindow());
search.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
}
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setPreferredSize(new Dimension(55, 20));
return button;
}
private void disableAllNavigationButton() {
btnFirstPage.setEnabled(false);
btnPreviousPage.setEnabled(false);
btnNextPage.setEnabled(false);
btnLastPage.setEnabled(false);
}
private boolean isMoreThanOnePage(PDFFile pdfFile) {
return pdfFile.getNumPages() > 1;
}
private class PageNavigationListener implements ActionListener {
private final Navigation navigation;
private PageNavigationListener(Navigation navigation) {
this.navigation = navigation;
}
public void actionPerformed(ActionEvent e) {
if (pdfFile == null) {
return;
}
int numPages = pdfFile.getNumPages();
if (numPages <= 1) {
disableAllNavigationButton();
} else {
if (navigation == Navigation.FORWARD && hasNextPage(numPages)) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_LAST_PAGE) {
goPage(numPages, numPages);
}
if (navigation == Navigation.BACKWARD && hasPreviousPage()) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_FIRST_PAGE) {
goPage(FIRST_PAGE, numPages);
}
if (navigation == Navigation.GO_N_PAGE) {
String text = txtGoPage.getText();
boolean isValid = false;
if (!isNullOrEmpty(text)) {
boolean isNumber = POSITIVE_DIGITAL.matchesAllOf(text);
if (isNumber) {
int pageNumber = Integer.valueOf(text);
if (pageNumber >= 1 && pageNumber <= numPages) {
goPage(Integer.valueOf(text), numPages);
isValid = true;
}
}
}
if (!isValid) {
JOptionPane.showMessageDialog(PdfViewer.this,
format("Invalid page number '%s' in this document", text));
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
}
}
}
}
private void goPage(int pageNumber, int numPages) {
currentPage = pageNumber;
PDFPage page = pdfFile.getPage(currentPage);
pagePanel.showPage(page);
boolean notFirstPage = isNotFirstPage();
btnFirstPage.setEnabled(notFirstPage);
btnPreviousPage.setEnabled(notFirstPage);
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
boolean notLastPage = isNotLastPage(numPages);
btnNextPage.setEnabled(notLastPage);
btnLastPage.setEnabled(notLastPage);
}
private boolean hasNextPage(int numPages) {
return (++currentPage) <= numPages;
}
private boolean hasPreviousPage() {
return (--currentPage) >= FIRST_PAGE;
}
private boolean isNotLastPage(int numPages) {
return currentPage != numPages;
}
private boolean isNotFirstPage() {
return currentPage != FIRST_PAGE;
}
}
private class PrintUIWindow implements Printable, ActionListener {
/*
* (non-Javadoc)
*
* #see java.awt.print.Printable#print(java.awt.Graphics,
* java.awt.print.PageFormat, int)
*/
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int pagenum = pageIndex+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) graphics;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) pageFormat.getImageableWidth (),
(int) pageFormat.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) pageFormat.getImageableX (),
(int) pageFormat.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) graphics, bounds,
null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
//JOptionPane.showMessageDialog (this, ie.getMessage ());
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (pageFormat.getImageableX (),
pageFormat.getImageableY (),
pageFormat.getImageableWidth (),
pageFormat.getImageableHeight ()));
return PAGE_EXISTS;
}
/*
* (non-Javadoc)
*
* #see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
* )
*/
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Inside action performed");
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
try
{
HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
//attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (printJob.printDialog (attset))
printJob.print (attset);
}
catch (PrinterException pe)
{
//JOptionPane.showMessageDialog (this, pe.getMessage ());
}
}
}
public PagePanel getPagePanel() {
return pagePanel;
}
public void setPDFFile(PDFFile pdfFile) {
this.pdfFile = pdfFile;
currentPage = FIRST_PAGE;
disableAllNavigationButton();
txtGoPage.setText(format(GO_PAGE_TEMPLATE, FIRST_PAGE, pdfFile.getNumPages()));
boolean moreThanOnePage = isMoreThanOnePage(pdfFile);
btnNextPage.setEnabled(moreThanOnePage);
btnLastPage.setEnabled(moreThanOnePage);
}
public static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
public static void main(String[] args) {
try {
long heapSize = Runtime.getRuntime().totalMemory();
System.out.println("Heap Size = " + heapSize);
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load a pdf from a byte buffer
File file = new File("/home/swarupa/Downloads/2626OS-Chapter-5-Advanced-Theme.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
final PDFFile pdffile = new PDFFile(buf);
PdfViewer pdfViewer = new PdfViewer();
pdfViewer.setPDFFile(pdffile);
frame.add(pdfViewer);
frame.pack();
frame.setVisible(true);
PDFPage page = pdffile.getPage(0);
pdfViewer.getPagePanel().showPage(page);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Where i am doing wrong.Can any one point me.
I think, that this should solve your problem ;) You've forgotten to set the window to be visible :)
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
parent.setVisible(true);
}
}
Btw-why do you create that JDialog?
You create JDialog and JFrame, why? You never call setVisible(true), why?
What you expect from the Action1?
Sorry for posting this answer to your comment as a new post, but it was too long to post it as a comment. You just can't remove close and minimize buttons from JFrame. If you want some window without those buttons, you have to create and customize your own JDialog. Nevertheless there will still be a close button (X). You can make your JDialog undecorated and make it to behave more like JFrame when you implement something like this:
class CustomizedDialog extends JDialog {
public CustomizedDialog(JFrame frame, String str) {
super(frame, str);
super.setUndecorated(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
And then you can call it in your code with this:
CustomizedDialog myCustomizedDialog = new CustomizedDialog(new JFrame(), "My title");
JPanel panel = new JPanel();
panel.setSize(256, 256);
myCustomizedDialog.add(panel);
myCustomizedDialog.setSize(256, 256);
myCustomizedDialog.setLocationRelativeTo(null);
myCustomizedDialog.setVisible(true);
I hope, this helps :)

Categories