print method in java doesn't print content of jtable - java

The print button below displays the printer selection window but it prints nothing ...but the JTable contains data
print_button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
boolean complete = table2.print();
if (complete) {
JOptionPane.showMessageDialog(null, "Done printing");
} else {
JOptionPane.showMessageDialog(null, "printing.....");
}
} catch (PrinterException pe) {
}
}});

You need to give a size to your JTable in order to get printed:
table2.setSize(table2.getPreferredSize());
It's correct that it has data, but it needs to have a size for the priniting to work.

i got the answer
print_button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
MessageFormat header = new MessageFormat("report printing");
MessageFormat footer = new MessageFormat("page{0,number,integer}");
try {
table1.print(JTable.PrintMode.NORMAL,header,footer);
} catch (PrinterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}});

Related

HyperLinkListener not triggering - java swing

I'm trying to implement a JEditorPane with hyperlinks. I'm using a HyperLinkListener but it seems to never trigger.
Code:
JEditorPane editorPane = new JEditorPane("text/html", programInfo);
editorPane.addHyperlinkListener(e -> {
System.out.println("CLICK");
if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED))
try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
});
JOptionPane.showMessageDialog(contentPane, editorPane);
Sample HTML:
<body>
<p><b>Author:</b> James - sample</p>
</body>
This leads to this:
But when I click on the links nothing happens.
Additional Info:
I'm testing this on Ubuntu 14.04.
I have set Look and Feel to system.
EDIT: thanks to #AndrewThompson for finding the real issue.
The reason why it does not trigger events is because the editor pane will only fire events when it is not editable. So, to make your code work you should add this line after the construction of the editorPane:
editorPane.setEditable(false);
Below you can find a self contained example:
public class TestFrame extends JFrame {
public static void main(String[] args) {
JEditorPane editorPane = new JEditorPane("text/html", "test link to example.com");
editorPane.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent e) {
System.out.println("CLICK");
if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED)) try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
}
catch (IOException e1) {
e1.printStackTrace();
}
catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
editorPane.setEditable(false); // otherwise ignores hyperlink events!
JFrame frame = new JFrame("EditorPane Example");
frame.add(editorPane);
frame.setSize(300,200);
frame.setVisible(true);
} }
(sorry, I removed the lambda because I don't have a jdk8 on this PC)

How can I start thread again?

I know time and time again people have asked how to start a thread after it's been stopped and everyone says you can't. This isn't a duplicate to that because I've found no solution for the problem.
private void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
while (running) {
try {
checkPixel();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
#Override
public void nativeKeyPressed(NativeKeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if(NativeKeyEvent.getKeyText(e.getKeyCode()).equals("F9")){
stop();
}
else if(NativeKeyEvent.getKeyText(e.getKeyCode()).equals("F10")){
}
So in my code I'm listening for global key events using JNativeHook. I can successfully stop the checkPixels() using the F9 key but I'm not understanding what I should do using F10 when I wanna start up checkPixel() again.
checkPixel() basically checks for a change in pixel color
ANSWERED Added an if statement for my state variable running and keep the while loop true allows me to turn on/off the method while keeping the thread open. Thank you Jaboyc
private void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
if(running){
try {
checkPixel();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
Would this work
while (true) {
if (running) {
doStuff();
}
}
in the run method?

How to change a FormatedTextField mask dynamically?

So I have this FormatedTextField
JFormattedTextField myFtf = new JFormattedTextField();
which has the following mask, placed in my application constructor
try {
myFtf.setFormatterFactory(
new DefaultFormatterFactory(
new MaskFormatter("###.###.###-##")));
} catch (java.text.ParseException ex) {
ex.printStackTrace();
}
Then, I have a two radio buttons, which should be changing the mask formatter in myFtf.
I have tried the following:
private radioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
myFtf.setFormatterFactory(
new DefaultFormatterFactory(
new MaskFormatter("###.###.###-##")));
} catch (Exception e) {
e.printStackTrace();
}
}
private void radioButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
myFtf.setFormatterFactory(
new DefaultFormatterFactory(
new MaskFormatter("##.###.###/####-##")));
} catch (Exception e) {
e.printStackTrace();
}
}
Which works fine, until I try to change their masks when there is input within the text field. In case there is, it doesn't change the mask anymore. Here are a couple of prints:
OK scenario:
img a:
switching radio buttons gives me this:
img b:
Buggy scenario:
img c:
switching radio buttons gives me this:
img d:
I was expecting img d to be exactly like img a
How can I dynamically change its mask correctly?
Change your action listeners to this:
private radioButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
myFtf.setFormatterFactory(
new DefaultFormatterFactory(
new MaskFormatter("###.###.###-##")));
myFtf.setText("");
} catch (Exception e) {
e.printStackTrace();
}
}
private void radioButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
myFtf.setFormatterFactory(
new DefaultFormatterFactory(
new MaskFormatter("##.###.###/####-##")));
myFtf.setText("");
} catch (Exception e) {
e.printStackTrace();
}
}
That should clear the text fields.
Good luck!
I got it working correctly! All I needed to do was adding a
myFtf.setValue(null);
after setting the new formatter factory. myFtf.setText("") wasn't working as expected, but it was a close shot! :-)

Code tells me I need to implement ActionListener when I already have?

So I am making this code to write to a file based on user clicks. The only problem I have, is that I get an error on "public class prog". The prog name is where I get the error: It says: The type prog must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent). When I do the quickfix of adding the uninherited methods, it adds the action listener method to the end of my code but with nothing in it. If I already have action listeners in the program, why does it tell me I need to implement them? And why when I add it at the end, does it work fine even though nothing is in it?
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.*;
public class prog extends JFrame implements ActionListener {
//create newLine
final String newLine = System.getProperty("line.separator");
//create buttons
JPanel row1 = new JPanel();
JButton oneLeft = new JButton("oneLeft");
JButton oneRight = new JButton("oneRight");
JPanel row2 = new JPanel();
JButton twoLeft = new JButton("twoLeft");
JButton twoRight = new JButton("twoRight");
JPanel row3 = new JPanel();
JButton threeLeft = new JButton("threeLeft");
JButton threeRight = new JButton("threeRight");
public prog() {
super("Prog");
setLookAndFeel();
setSize(400, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout = new GridLayout(3, 2);
setLayout(layout);
//create outStream for writing to file
try {
final File numClicks = new File("numClicks.properties");
final FileOutputStream outStream = new FileOutputStream(numClicks);
//add Listeners
oneLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "oneLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
oneRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "oneRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
twoLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "twoLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
twoRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "twoRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
threeLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "threeLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
threeRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "threeRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
} catch (IOException ioe) {
System.out.println("The file could not be written.");
}
row1.add(oneLeft);
row1.add(oneRight);
row2.add(twoLeft);
row2.add(twoRight);
row3.add(threeLeft);
row3.add(threeRight);
add(row1);
add(row2);
add(row3);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
//ignore error
}
}
void write(FileOutputStream stream, String output) throws IOException {
output = output + newLine;
byte[] data = output.getBytes();
stream.write(data, 0, data.length);
}
public static void main(String[] args) {
prog progApp = new prog();
}
}
Your class shouldn't implement ActionListener. Instead of writing a top-level class that implements the interface, you're writing a bunch of little inline classes (called anonymous inner classes) that do this work for you when you say new ActionListener().
You implement ActionListener it, but you don't actually implement the required methods (i.e., actionPerformed()). Therefore your class is invalid to the compiler.
You need a method like:
#Override
public void actionPerformed(ActionEvent e) {
// ...
}
The way an interface works is that it defines what the classes that implements it have to... well... implement. That way any other process can treat it as an ActionListener and know that certain methods have been defined.
Just another way Java tries to make polymorphism your friend.
To address something from the comment below, it's actually not that uncommon to see a class implement an interface (like KeyListener) and define the method without even using it.
For example, KeyListener requires you to implement three different methods:
public void keyPressed(KeyEvent e);
public void keyReleased(KeyEvent e);
public void keyTyped(KeyEvent e);
Let's say I only really care about keyPressed. Then my class might look something like this:
public class MyKeyListener implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
// do stuff
}
#Override
public void keyReleased(KeyEvent e){}
#Override
public void keyTyped(KeyEvent e){}
}

Enable Jbutton only if Validation is True

What is the best way to validate swing application's input fields such as text fields, comboboxes, etc and let the user to press Save button only if everything is ok. Assume that Search function also in the same interface. So searching for record will also fill up input fields. But Save button should remain disable in that case.
initComponents();
btnSave.setEnabled(false);
txt1.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
}
#Override
public void removeUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
#Override
public void insertUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
public void validate(String enteredText,DocumentEvent e) {
String currText = "";
try {
Document doc = (Document) e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
}
if(enteredText.equals(currText)){
//if validated successfully
btnSave.setEnabled(false);
}else{
btnSave.setEnabled(true);
}
}
});
did you try like this?
final JTextField textField = new JTextField();
final JButton submitBtn = new JButton();
submitBtn.setEnabled(true);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
validate(e);
}
public void removeUpdate(DocumentEvent e) {
validate(e);
}
public void insertUpdate(DocumentEvent e) {
validate(e);
}
public void validate(String enteredText) {
String currText = "";
try {
Document doc = (Document)e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
//validation of currText here
//if validated successfully
submitBtn.setEnabled(true);
//else
submitBtn.setEnabled(false);
}
});
Condition the enabled property of your Save button using setEnabled() in two places:
In your implementation of shouldYieldFocus() in an InputVerifier attached to each relevant component. The tutorial and some examples are cited here.
In your component's normal listener.
Create a method to check if all the inputs are completed or/and all the validations are passed and finally return a boolean.
public boolean validate(...){
//some stuff
if(validated){
return true;
}else{
return false;
}
}
then you can use it like.
button.setEnabled(validate(...));

Categories