I want to make an GUI program which write in a file x numbers from y.
E.g: if y=103 and x=100, the output is "103 104 105 106...202"(100 numbers).
I tried this code, but when I run it and submit some numbers, the file still remain empty.
Probably the problem is at the void filein().
package me;
import java.io.FileInputStream;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class program {
static PrintStream OUT = System.out;
public static void main(String args[]) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
startGUI();
}
});
}
private static void startGUI() {
JFrame window = new JFrame();
window.setTitle("Text Writer");
{
setupWindowContent(window);
}
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
private static void setupWindowContent(JFrame window) {
JPanel content = new JPanel();
final JLabel lblEnterSmthng = new JLabel("Enter the first number and the iterate limit:");
final JTextField txtField1 = new JTextField(30);
final JTextField txtField2 = new JTextField(30);
JButton btnOk = new JButton("Ok");
final JLabel labelLastText = new JLabel();
content.add(lblEnterSmthng);
content.add(txtField1);
content.add(txtField2);
content.add(btnOk);
content.add(labelLastText);
window.setContentPane(content);
ActionListener submitAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String txt = txtField1.getText();
String txt2 = txtField2.getText();
int i = Integer.parseInt(txt);
int serii = Integer.parseInt(txt2);
if(!txt.isEmpty()){
labelLastText.setText(txt);
}
}
void filein(int i, int serii) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
out = new FileOutputStream("C:/Users/mihai/OneDrive/Desktop/Text.txt");
System.out.print(i + serii);
for(i=i;i<i+serii-1;i++) {
out.write(i);
}
}finally {
if (out != null) {
out.close();
}
}
}
};
btnOk.addActionListener(submitAction);
txtField1.addActionListener(submitAction);
txtField2.addActionListener(submitAction);
}
}
I do not know what details to give you.
Related
I need to make a slot machine that implements thread in java and jframe
this is what iv'e done so far kindly tell me what i need to do in order make the images change per .5 seconds when i press the the play and stop when i press stop. If all the three images are the same it'll say you won. This is what iv'e got so far how will i change this numbers or text to images in jlabel.
public class MySlotNumber extends JFrame{
private MyJLabel x;
private MyJLabel y;
private MyJLabel z;
private JButton btn;
public MySlotNumber(){
super("ABC");
setLayout(new FlowLayout());
Font font = new Font("arial",Font.ITALIC,50);
x = new MyJLabel();
x.setFont(font);
y = new MyJLabel();
y.setFont(font);
z = new MyJLabel();
z.setFont(font);
btn = new JButton("PLAY");
btn.setFont(font);
add(x);
add(y);
add(z);
add(btn);
final Thread thx = new Thread(x);
final Thread thy = new Thread(y);
final Thread thz = new Thread(z);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("PLAY")){
if(thx.isAlive()){
thx.resume();
thy.resume();
thz.resume();
} else {
thx.start();
thy.start();
thz.start();
}
btn.setText("STOP");
} else {
thx.suspend();
thy.suspend();
thz.suspend();
btn.setText("PLAY");
System.out.println(x.getText());
}
}
});
}
- - - - - - --
public class MyJLabel extends JLabel implements Runnable{
private Random r;
private int ctr;
private final int T = 500;
public MyJLabel(){
setText("0");
ctr = 0;
r= new Random();
}
#Override
public void run() {
while(true){
try {
Thread.sleep(T);
} catch (InterruptedException ex) {
Logger.getLogger(MyJLabel.class.getName()).log(Level.SEVERE, null, ex);
}
//ctr++;
ctr = r.nextInt(9)+1;
setText(String.valueOf(ctr));
}
}
}
Here is one way to put a picture on a JLabel and change it when you click a button. (I am using window builder for eclipse, so it may look a little odd.) It is not recommended you use absolute paths because when you move your project or the file, it breaks (I did this just for proof of concept).
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 1379, 643);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\Andrew\\Pictures\\Random Pictures\\Capture.JPG"));
frame.getContentPane().add(lblNewLabel, BorderLayout.CENTER);
JButton btnClickMe = new JButton("click me");
btnClickMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\Andrew\\Pictures\\Random Pictures\\I'm pretty sure he did.JPG"));
}
});
frame.getContentPane().add(btnClickMe, BorderLayout.EAST);
}
}
Im woking on some code to do some computations on different types of beer. I have a main class which uses a GUI and has a JTextArea to print output. Calling append within the main class works just fine, but as soon as I try to call append from an outside class to write to the text area..no cigar..i've worked at this for awhile and simply have no clue. Quite a bit of code, but I think the fix is simple
and I guess while im at it, does it make sense to extend NewFileOpener into LagerChooser? Or should it extend jpanel?
thanks for the help!!
public class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public CustomTextArea customTextArea = new CustomTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList<String> namesForGeneration;
private boolean namesRead = false;
void displayGUI() {
JFrame frame = new JFrame("Binary Brewing! " + "Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
// customTextArea = new CustomTextArea();
customTextArea
.append(" Program progress and/or errors will display below:");
customTextArea
.append("\n"
+ "----------------------------------------------------------------------------------------------------");
customTextArea.append("\n" + "\n"
+ "To Enable Beer recipe Generation please read in Name file!" + "\n");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new NewFinalOpener().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if(namesRead == false){
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if(namesRead == false){
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if(namesRead == false){
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
public Dimension getPreferredSize() {
return (new Dimension(200, 100));
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(
fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList<String>();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
customTextArea.append("\n"
+ "Successfully read all names!" + " "
+ file + "\n");
customTextArea.append("\n" + "Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
customTextArea
.append("\n"
+ "---------------------------------------------------------");
br.close();
}
} catch (Exception f) {
JOptionPane.showMessageDialog(null, e);
}
} else {
customTextArea.append("Open command cancelled by user."
+ "\n");
}
}
if(action.equalsIgnoreCase("lager")){
customTextArea.append("\n" + "\n "+ "Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame(){
LagerChooser l1 = new LagerChooser();
}
}
class CustomTextArea extends JTextArea {
private static final int GAP = 5;
public CustomTextArea() {
setEditable(false);
setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
}
public Dimension getPreferredSize() {
return (new Dimension(800, 800));
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
public void setCustomText(String text){
customTextArea.append(text);
}
}
and the class that needs to append to the JTextarea
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class LagerChooser extends NewFinalOpener{
public LagerChooser() {
}
public void tellCustom(String line){
setCustomText(line);
}
}
You can use:
public static final PrintStream OUT = System.out;
public CustomPanel() throws Throwable
{
...
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
customTextArea.append(str);
}
}));
And write to System.out. it will print to console and to textarea.
PS. Why you create custom textarea class? You should use JTextArea:
customTextArea=new JTextArea();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPrefferedSize(...);
Your code uses lot of memory, size of exported JAR isn't small for "simple program".
Optimized code:
import java.io.*;
import java.util.*;
class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public JTextArea customTextArea = new JTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList < String > namesForGeneration;
private boolean namesRead = false;
private static final PrintStream SYSOUT = System.out;
public NewFinalOpener() {
JFrame frame = new JFrame("Binary Brewing! Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPreferredSize(new Dimension(800, 800));
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
SYSOUT.write(b,offset,length);
customTextArea.append(str);
}
}));
System.setErr(System.out);
System.out.println(" Program progress and/or errors will display below:");
System.out.println("----------------------------------------------------------------------------------------------------\n");
System.out.println("To Enable Beer recipe Generation please read in Name file!");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NewFinalOpener();
}
});
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
setPreferredSize(new Dimension(200, 100));
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if (namesRead == false) {
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if (namesRead == false) {
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if (namesRead == false) {
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList < String > ();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
System.out.println("Successfully read all names!" + " " + file + "\n");
System.out.println("Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
System.out.println("\n---------------------------------------------------------");
br.close();
}
} catch (Throwable f) {
f.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
} else {
System.out.println("Open command cancelled by user.");
}
}
if (action.equalsIgnoreCase("lager")) {
System.out.println("Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame() {
LagerChooser l1 = new LagerChooser();
}
}
}
class LagerChooser extends NewFinalOpener {
public LagerChooser() {}
public void tellCustom(String line) {
setCustomText(line);
}
}
I have a JTextArea and a JComboBox to allow me to cycle through various open files - the contents of the JTextArea change as I select a different file. I am trying to maintain a different Undo buffer per file and have defined a separate UndoManager per file.
I have created a simpler SSCCE to demonstrate my problem using two buffers, which I call "One" and "Two" - with a simple button to switch between them. Once an UndoableEdit happens, it checks the active buffer and performs an addEdit() on the respective UndoManager. When the "Undo" button is pressed, then it checks canUndo() and performs an undo() on the respective UndoManager. I have a flag called ignoreEdit, which is used when switching between buffers to ignore those edits from being recorded.
If I never switch between the buffers, then I don't have a problem, Undo works as expected. It is only when I switch between the buffers and appear to "break" the Document, does it fail. The following steps can be used to recreate the problem:
In buffer "One", type:
THIS
IS ONE
EXAMPLE
Switch to buffer "Two", type:
THIS
IS ANOTHER
EXAMPLE
Switch to buffer "One" and press the "Undo" button multiple times. After a few Undo operations, the buffer looks like this (with no way for the cursor to select the first two lines). However, the contents of textArea.getText() are correct as per the System.out.println() - so, it looks like a rendering issue?
THIS
THISIS ONE
This can't be the first time that someone has tried to implement independent Undo buffers per file? I am obviously doing something wrong with the Document model and inherently breaking it, but I looking for some advice on how best to fix this?
The code for the SSCCE is included below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
public class SSCCE extends JFrame implements ActionListener, UndoableEditListener {
private final JLabel labTextArea;
private final JTextArea textArea;
private final JScrollPane scrollTextArea;
private final Document docTextArea;
private final JButton bOne, bTwo, bUndo;
private final UndoManager uOne, uTwo;
private String sOne, sTwo;
private boolean ignoreEdit = false;
public SSCCE(String[] args) {
setTitle("SSCCE - Short, Self Contained, Correct Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
labTextArea = new JLabel("One");
getContentPane().add(labTextArea, BorderLayout.PAGE_START);
uOne = new UndoManager();
uTwo = new UndoManager();
sOne = new String();
sTwo = new String();
textArea = new JTextArea();
docTextArea = textArea.getDocument();
docTextArea.addUndoableEditListener(this);
scrollTextArea = new JScrollPane(textArea);
getContentPane().add(scrollTextArea, BorderLayout.CENTER);
JPanel pButtons = new JPanel();
bOne = new JButton("One");
bOne.addActionListener(this);
bOne.setFocusable(false);
pButtons.add(bOne, BorderLayout.LINE_START);
bTwo = new JButton("Two");
bTwo.addActionListener(this);
bTwo.setFocusable(false);
pButtons.add(bTwo, BorderLayout.LINE_END);
bUndo = new JButton("Undo");
bUndo.addActionListener(this);
bUndo.setFocusable(false);
pButtons.add(bUndo, BorderLayout.LINE_END);
getContentPane().add(pButtons, BorderLayout.PAGE_END);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(bOne)) {
if (!labTextArea.getText().equals("One")) {
sTwo = textArea.getText();
ignoreEdit = true;
textArea.setText(sOne);
ignoreEdit = false;
labTextArea.setText("One");
}
}
else if (e.getSource().equals(bTwo)) {
if (!labTextArea.getText().equals("Two")) {
sOne = textArea.getText();
ignoreEdit = true;
textArea.setText(sTwo);
ignoreEdit = false;
labTextArea.setText("Two");
}
}
else if (e.getSource().equals(bUndo)) {
if (labTextArea.getText().equals("One")) {
try {
if (uOne.canUndo()) {
System.out.println("Performing Undo for One");
uOne.undo();
System.out.println("Buffer One is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for One");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
else if (labTextArea.getText().equals("Two")) {
try {
if (uTwo.canUndo()) {
System.out.println("Performing Undo for Two");
uTwo.undo();
System.out.println("Buffer Two is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for Two");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
}
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
if (!ignoreEdit) {
if (labTextArea.getText().equals("One")) {
System.out.println("Adding Edit for One");
uOne.addEdit(e.getEdit());
}
else if (labTextArea.getText().equals("Two")) {
System.out.println("Adding Edit for Two");
uTwo.addEdit(e.getEdit());
}
}
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SSCCE(args);
}
});
}
}
Previously I had attempted to create a new instance of the Document class (each referencing the same Undo listener) and was going to use JTextArea.setDocument() instead of JTextArea.setText(). However, Document is an interface and can't be instantiated, but after reading the reference that mKorbel posted, I tried this using the PlainDocument class instead, which worked.
I have decided to maintain a HashMap<String, Document> to contain my Document classes and switch between them. When I switch the Document, I don't see the Undo/Redo issue - I suppose as I am no longer breaking the Document.
Updated SSCCE below which now uses JTextArea.setDocument() instead of JTextArea.setText(). This also has the advantage of not requiring the ignoreEdit boolean as setDocument() doesn't trigger an UndoableEditEvent, whereas setText() does. Each Document then references the local classes UndoableEditListener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
public class SSCCE extends JFrame implements ActionListener, UndoableEditListener {
private final JLabel labTextArea;
private final JTextArea textArea;
private final JScrollPane scrollTextArea;
private final Document docTextArea;
private final JButton bOne, bTwo, bUndo;
private final UndoManager uOne, uTwo;
private Document dOne, dTwo;
public SSCCE(String[] args) {
setTitle("SSCCE - Short, Self Contained, Correct Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
labTextArea = new JLabel("One");
getContentPane().add(labTextArea, BorderLayout.PAGE_START);
uOne = new UndoManager();
uTwo = new UndoManager();
dOne = new PlainDocument();
dTwo = new PlainDocument();
dOne.addUndoableEditListener(this);
dTwo.addUndoableEditListener(this);
textArea = new JTextArea();
docTextArea = textArea.getDocument();
docTextArea.addUndoableEditListener(this);
textArea.setDocument(dOne);
scrollTextArea = new JScrollPane(textArea);
getContentPane().add(scrollTextArea, BorderLayout.CENTER);
JPanel pButtons = new JPanel();
bOne = new JButton("One");
bOne.addActionListener(this);
bOne.setFocusable(false);
pButtons.add(bOne, BorderLayout.LINE_START);
bTwo = new JButton("Two");
bTwo.addActionListener(this);
bTwo.setFocusable(false);
pButtons.add(bTwo, BorderLayout.LINE_END);
bUndo = new JButton("Undo");
bUndo.addActionListener(this);
bUndo.setFocusable(false);
pButtons.add(bUndo, BorderLayout.LINE_END);
getContentPane().add(pButtons, BorderLayout.PAGE_END);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(bOne)) {
if (!labTextArea.getText().equals("One")) {
textArea.setDocument(dOne);
labTextArea.setText("One");
}
}
else if (e.getSource().equals(bTwo)) {
if (!labTextArea.getText().equals("Two")) {
textArea.setDocument(dTwo);
labTextArea.setText("Two");
}
}
else if (e.getSource().equals(bUndo)) {
if (labTextArea.getText().equals("One")) {
try {
if (uOne.canUndo()) {
System.out.println("Performing Undo for One");
uOne.undo();
System.out.println("Buffer One is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for One");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
else if (labTextArea.getText().equals("Two")) {
try {
if (uTwo.canUndo()) {
System.out.println("Performing Undo for Two");
uTwo.undo();
System.out.println("Buffer Two is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for Two");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
}
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
if (labTextArea.getText().equals("One")) {
System.out.println("Adding Edit for One");
uOne.addEdit(e.getEdit());
}
else if (labTextArea.getText().equals("Two")) {
System.out.println("Adding Edit for Two");
uTwo.addEdit(e.getEdit());
}
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SSCCE(args);
}
});
}
}
This is not an answer per se, but a demonstration of a different way of approaching the same problem.
What this does is wraps the UndoableEditListener in a self managed proxy, which has it's own UndoManager and Document.
Tested this with Java 7 and Java 8:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import javax.swing.undo.UndoManager;
public class UndoExample {
public static void main(String[] args) {
new UndoExample();
}
private int index = 0;
private Map<String, Undoer> mapUndoers;
private JTextArea ta;
private Undoer current;
public UndoExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
mapUndoers = new HashMap<>(2);
mapUndoers.put("One", new Undoer());
mapUndoers.put("Two", new Undoer());
ta = new JTextArea(4, 20);
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
JButton btnOne = new JButton("One");
JButton btnTwo = new JButton("Two");
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
install(e.getActionCommand());
}
};
btnOne.addActionListener(al);
btnTwo.addActionListener(al);
JButton undo = new JButton("Undo");
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (current != null) {
current.undo();
}
}
});
JPanel panel = new JPanel(new GridBagLayout());
panel.add(btnOne);
panel.add(btnTwo);
panel.add(undo);
install("One");
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(ta));
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected void install(String name) {
Undoer undoer = mapUndoers.get(name);
if (undoer != null) {
current = undoer;
undoer.install(ta);
}
}
public class Undoer implements UndoableEditListener {
private UndoManager undoManager;
private Document doc;
public Undoer() {
undoManager = new UndoManager();
doc = createDocument();
doc.addUndoableEditListener(this);
}
public void undo() {
undoManager.undo();
}
public void undoOrRedo() {
undoManager.undoOrRedo();
}
protected Document createDocument() {
return new PlainDocument();
}
public void install(JTextComponent comp) {
comp.setDocument(doc);
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
undoManager.addEdit(e.getEdit());
}
}
}
I have a Gridlayout filled with images loaded from File and I want to add a different, for example, popup, on mouseEvent mouseClicked for each image. How do I determine which image I'm clicking? I've tried adding GetComponentAt(Point), but Eclipse keeps showing that as an unidentified method for the mouseAdapter, and how do I determine the fields for the if statement?
This is what I have:
public class testclass implements ItemListener {
JPanel template;
final static String title = "Title";
public void testclass (Container window){
JPanel index = new JPanel();
String index2[] = {title};
JComboBox index3 = new JComboBox(index2);
index3.setEditable(false);
index3.addItemListener(this);
index.add(index3);
File folder = new File("images/");
File[] listOfFiles = folder.listFiles();
String nr;
final JPanel panel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < listOfFiles.length; i++) {
nr = "images/" + listOfFiles[i].getName();
final ImageIcon images = new ImageIcon(nr);
final JLabel display[] = new JLabel[1];
for (int n = 0; n < 1; n++){
display[n] = new JLabel(images);
panel.add(display[n]);
} }
panel.addMouseListener(new MouseAdapter()
{ public void mouseClicked (MouseEvent e)
{ //JPanel panel = (JPanel) getComponentAt(e.getPoint());
JOptionPane.showMessageDialog(null, "Message");
}});
template = new JPanel(new CardLayout());
template.add(panel, title);
window.add(index, BorderLayout.PAGE_START);
window.add(template, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent event){
CardLayout change = (CardLayout)(template.getLayout());
change.show(template, (String)event.getItem());
}
private static void userinterface() {
JFrame showwindow = new JFrame("Window");
showwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testclass show = new testclass();
show.testclass(showwindow.getContentPane());
showwindow.pack();
showwindow.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e){
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
userinterface();
}
});
}
}
Edit: Proper Answer
Thankyou for providing code. I have adjusted some things so hopefully you can understand them.
Firstly I have added a new object, ImageButton. From when I added the actionListener the functionality you wanted was already done (minus the good looks, you will have to play around with that, or ask another question)
Added a 'dir' string so that you don't have to keep copy and pasting the directory address.
I had to adjust the size of the window through the userInterface() method, you should look at being able to shorten the sequence of being able to adjust the parameters, maybe another GUI object to keep all that information together.
A couple of things:
The code you wrote was good but it would need for you to adjust alot of (getting the size of windows and repeatedly check for different sizes if you adjusted the window size where a mouse click could click on other image that you don't want!) in order for a mouseListener to work, I am guessing with a wide range of images you would be providing.
Putting comments in your code can help both you and someone trying to help you.
Anyways, please upvote/accept answer if this helps out, which I'm sure it does.
Good Luck!
Put these files into your eclipse and run them it should work if you adjust the dir string to follow your original directory path.
testclass.java
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class testclass implements ItemListener {
JPanel template;
final static String title = "Title";
final String dir = "images/";
public void testclass(Container window) {
JPanel index = new JPanel();
String[] index2 = { title };
JComboBox index3 = new JComboBox(index2);
index3.setEditable(false);
index3.addItemListener(this);
index.add(index3);
index.setSize(500, 500);
File folder = new File(dir);
File[] listOfFiles = folder.listFiles();
String nr;
final JPanel panel = new JPanel(new GridLayout(4, 4, 4, 4));
for (int i = 0; i < listOfFiles.length; i++) {
nr = dir + listOfFiles[i].getName();
panel.add(new ImageButton(nr));
}
template = new JPanel(new CardLayout());
template.add(panel, title);
window.add(template, BorderLayout.CENTER);
window.add(index, BorderLayout.NORTH);
window.setVisible(true);
}
public void itemStateChanged(ItemEvent event) {
CardLayout change = (CardLayout) (template.getLayout());
change.show(template, (String) event.getItem());
}
private static void userinterface() {
JFrame showwindow = new JFrame("Window");
showwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testclass show = new testclass();
show.testclass(showwindow.getContentPane());
showwindow.pack();
showwindow.setVisible(true);
showwindow.setSize(500, 500);
}
public static void main(String[] args) {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
}
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
userinterface();
}
});
}
}
ImageButton.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class ImageButton extends JButton {
private String fileName;
private ImageIcon image;
private JButton button;
public ImageButton(String fileName) {
setFileName(fileName);
setImage(new ImageIcon(fileName));
setButton(new JButton(getImage()));
this.setIcon(getImage());
this.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, ae.getSource());
}
});
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public ImageIcon getImage() {
return image;
}
public void setImage(ImageIcon image) {
this.image = image;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
}
I have two Java(.java) files. One has a JButton and JTextField and the other has a Thread. In first Java file, I have added an ActionListener to the JButton so that, when the button is pressed, a thread (object for 2nd .java file in created and thread is initiated) runs which modifies an integer variable continuously. How to display the value of that integer variable (of 2nd .java file) in the JTextField (of 1st .java file) ?
Detection.java
package sample;
public class Detection implements Runnable
{
public String viewers;
public int count;
public void run()
{
try
{
while (true)
{
// i have written code for displaying video.
// and it say how many no. of people in the video
// the no of people is stored in a variable "count"
viewers=""+count; //storing count as string so as to display in the JTextField
}
}
catch (Exception e)
{
System.out.println("Exception: "+e);
}
}
}
UsrInterfac.java
//build using WindowBuilder eclipse juno
package sample;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UsrInterfac
{
private JFrame frame;
private JTextField textField;
Detection dd = new Detection();
Thread th = new Thread(dd);
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
UsrInterfac window = new UsrInterfac();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UsrInterfac()
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnStartThread = new JButton("Start Thread");
btnStartThread.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
th.start();
}
});
btnStartThread.setBounds(59, 133, 117, 23);
frame.getContentPane().add(btnStartThread);
textField = new JTextField();
textField.setBounds(270, 134, 104, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
}
}
Starting from the basics, while using Swing, it is always best to use LayoutManagers, which can make your work much more easier, in comparison to using Absolute Positioning.
Whenever one needs to change something in the View from some another thread, it is always advisable to do that using EventQueue.invokeLater(...)/EventQueue.invokeAndWait(...).
This small sample program, might be able to help you get an idea, how to accomplish what you so desire :-)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThreadCounter
{
private CustomThread cThread;
private JTextField tField;
private JButton button;
private int counter;
public ThreadCounter()
{
counter = 0;
}
private void displayGUI()
{
JFrame frame = new JFrame("Thread Counter Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
tField = new JTextField(10);
tField.setText("0");
button = new JButton("Start");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (counter == 0)
{
cThread = new CustomThread(tField);
cThread.setFlagValue(true);
cThread.start();
counter = 1;
button.setText("Stop");
}
else
{
try
{
cThread.setFlagValue(false);
cThread.join();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
counter = 0;
button.setText("Start");
}
}
});
contentPane.add(tField);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ThreadCounter().displayGUI();
}
});
}
}
class CustomThread extends Thread
{
private int changingVariable;
private JTextField tField;
private boolean flag = true;
public CustomThread(JTextField tf)
{
changingVariable = 0;
tField = tf;
}
public void setFlagValue(boolean flag)
{
this.flag = flag;
}
#Override
public void run()
{
while (flag)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
tField.setText(
Integer.toString(
++changingVariable));
}
});
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
System.out.println("I am OUT of WHILE");
}
}
Ideally you should post your code. Anyway, when you are calling the thread code, either pass the instance of the first class (object) or an instance of JTextField, so that the thread can set the new value in the text field.