Use wait() in Java - java

I need to create a new JFrame in a new Thread.. When I close the JFrame I need to return a String.
The problem is that the wait() method "doesn't wait" the "notify()" of new Thread.
Thank's for your answer.
import java.awt.Button;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FinestraTesto extends Thread {
JLabel jdescr;
JTextArea testo;
JPanel pannelloTasti;
JButton bottoneInvio;
JButton bottoneAnnulla;
JFrame finestraTestuale;
JPanel panAll;
static Boolean pause = true;
String titolo;
String descrizione;
private static String testoScritto = "";
public String mostra() {
// Create a new thread
Thread th = new Thread(new FinestraTesto(titolo, descrizione));
th.start();
synchronized (th) {
try {
// Waiting the end of th.
th.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return testoScritto;
}
public void run() {
synchronized (this) {
System.out.println("Fatto 1 thread");
finestraTestuale = new JFrame(titolo);
finestraTestuale.setPreferredSize(new Dimension(600, 200));
finestraTestuale.setSize(600, 200);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
finestraTestuale.setLocation(
dim.width / 2 - finestraTestuale.getSize().width / 2,
dim.height / 2 - finestraTestuale.getSize().height / 2);
panAll = new JPanel();
panAll.setLayout(new BoxLayout(panAll, BoxLayout.Y_AXIS));
bottoneInvio = new JButton("Conferma");
bottoneAnnulla = new JButton("Annulla");
pannelloTasti = new JPanel();
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
jdescr = new JLabel(descrizione);
jdescr.setPreferredSize(new Dimension(550, 50));
jdescr.setSize(550, 50);
pannelloTasti.setLayout(new BoxLayout(pannelloTasti,
BoxLayout.X_AXIS));
pannelloTasti.add(bottoneInvio);
pannelloTasti.add(bottoneAnnulla);
panAll.add(jdescr);
panAll.add(scrollPane);
panAll.add(pannelloTasti);
finestraTestuale.add(panAll);
bottoneInvio.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
testoScritto = testo.getText();
pause = false;
finestraTestuale.show(false);
// send notify
notify();
}
});
bottoneAnnulla.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
pause = false;
testoScritto = "";
finestraTestuale.show(false);
// send notify
notify();
}
});
finestraTestuale.show();
}
}
public FinestraTesto(String titolo, String descrizione) {
this.titolo = titolo;
this.descrizione = descrizione;
}
}

You would better to use Synchronizers instead of wait and notify. They're more preferable because of simplicity and safety.
Given the difficulty of using wait and notify correctly, you should
use the higher-level concurrency utilities instead.
Effective Java (2nd Edition), Item 69

I solved with this class:
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
private JTextArea testo;
public CustomDialog(String title,String descrizione)
{
components = new ArrayList<>();
setTitle(title);
setMessageType(JOptionPane.PLAIN_MESSAGE);
addMessageText(descrizione);
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
addComponent(scrollPane);
setRootPane(null);
setOptions(new String[] { "Send", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
components.add(new JLabel(messageText));
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public String show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
if(selection == 0)
return testo.getText();
else
return null;
}
}

Related

What else can be optimized how to use JTextField default text prompt function

What else can be optimized how to use JTextField default text prompt function
Thank you all for your answers
=============================================================================
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;[enter image description here][1]
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
class WindowActionEvent extends JFrame {
JTextField text;
JTextArea textShow;
JButton button;
ReaderListen listener;
public WindowActionEvent() throws HeadlessException {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout());
text = new JTextField(10);
button = new JButton("读取");
textShow = new JTextArea(25,50);
textShow.setEditable(false);
listener = new ReaderListen();
listener.setJTextField(text);
listener.setJTextArea(textShow);
text.addActionListener(listener);
button.addActionListener(listener);
add(text);
add(button);
add(new JScrollPane(textShow));
}
}
class ReaderListen implements ActionListener {
JTextField text;
JTextArea textShow;
public void setJTextField(JTextField text) {
this.text = text;
}
public void setJTextArea(JTextArea textShow) {
this.textShow = textShow;
}
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File(text.getText()); //getDocument()
FileReader inOne = new FileReader(file);
BufferedReader inTwo = new BufferedReader(inOne);
String s = null;
while ((s = inTwo.readLine()) != null) {
textShow.append(s+"\n");
}
inOne.close();
inTwo.close();
} catch (Throwable e2) {
e2.printStackTrace();
}
}
}
public class Matematiktest extends WindowActionEvent {
public static void main(String[] args) {
WindowActionEvent win = new WindowActionEvent();
win.setBounds(100,100,1000,500);
win.setTitle("处理ActionEvent事件");
}
}
This is the code I checked about the default text prompt function of JTextField but I don’t know where it should be placed or used
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class JTextFieldHintListener implements FocusListener {
private String hintText;
private JTextField textField;
public JTextFieldHintListener(JTextField jTextField,String hintText) {
this.textField = jTextField;
this.hintText = hintText;
jTextField.setText(hintText); //默认直接显示
jTextField.setForeground(Color.GRAY);
}
#Override
public void focusGained(FocusEvent e) {
//获取焦点时,清空提示内容
String temp = textField.getText();
if(temp.equals(hintText)) {
textField.setText("");
textField.setForeground(Color.BLACK);
}
}
#Override
public void focusLost(FocusEvent e) {
//失去焦点时,没有输入内容,显示提示内容
String temp = textField.getText();
if(temp.equals("")) {
textField.setForeground(Color.GRAY);
textField.setText(hintText);
}
}
}

jbutton does not work

Hi I have the following code where I have a start and stop button . when start is pressed canvas starts painting but I cannot press stop button until the start operation is done . I need to stop and resume the paint on the button press . Once the start button is pressed the other buttons cannot be pressed till the canvas is painted.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;
public abstract class JUIApp extends JPanel implements ActionListener {
public static CACanvas cacanvas= null;
public ArrayList<int[]> genL;
public JFrame frame = null;
protected JPanel mainPanel = null;
private JButton btn0 = null;
private JButton btn1 = null;
private JButton btn2 = null;
#SuppressWarnings("rawtypes")
DefaultComboBoxModel rules = null;
#SuppressWarnings("rawtypes")
JComboBox rulesCombo =null;
JScrollPane ruleListScrollPane=null;
JLabel lable=null;
JTextField generation=null;
JLabel gLable=null;
public static String Rule;
public static String Generations;
public boolean isChanged =false;
public int gridCellSize=4;
private static final long serialVersionUID = 1L;
public int genCurrent=0;
public int posCurrent=0;
public int i;
public Color cellColor= null;
public Timer waitTimer;
public static boolean waitFlag;
public static boolean alert1Flag=false;
public boolean stopFlag=false;
public JLabel Alert1=new JLabel();
public int genCheck=0;
//private List<Point> fillCells;
public JUIApp() {
initGUI();
}
public void initGUI() {
//fillCells = new ArrayList<>(25);
frame = new JFrame();
frame.setTitle("Cellular Automata Demo");
frame.setSize(1050, 610);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(getMainPanel(),BorderLayout.NORTH);
frame.setVisible(true);
Toolkit.getDefaultToolkit().setDynamicLayout(false);
cacanvas=new CACanvas();
frame.add(cacanvas);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public JPanel getMainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
//cacanvas=new CACanvas();
btn0 = new JButton("Start");
btn0.addActionListener(this);
//waitTimer = new Timer(1000, this);
mainPanel.add(btn0);
JButton btn2 = new JButton("Stop");
btn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent s)
{
stopFlag=true;
//cacanvas.repaint();
}
});
mainPanel.add(btn2);
btn1 = new JButton("Clear");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
CACanvas.clearFlag=true;
generation.setText("");
alert1Flag=true;
rulesCombo.setSelectedIndex(0);
Alert1.setText("Please enter the number of generations");
Alert1.setBounds(30, 20, 5, 5);
Alert1.setVisible(alert1Flag);
mainPanel.add(Alert1);
cacanvas.repaint();
frame.setSize(1060, 610);
}
});
mainPanel.add(btn1);
lable=new JLabel();
lable.setText("Select Rule :");
mainPanel.add(lable);
rules=new DefaultComboBoxModel();
for (int i=0;i<=100;i++)
{
String p=String.valueOf(i);
rules.addElement(p);
}
rules.addElement("250");
rules.addElement("254");
rulesCombo = new JComboBox(rules);
rulesCombo.setSelectedIndex(0);
ruleListScrollPane = new JScrollPane(rulesCombo);
mainPanel.add(ruleListScrollPane);
//mainPanel.revalidate();
gLable=new JLabel();
gLable.setText("Enter the number of Generations (Max 64)");
generation=new JTextField(2);
mainPanel.add(gLable);
mainPanel.add(generation);
// mainPanel.add(cacanvas);
return mainPanel;
}
public abstract void run();
#Override
public void actionPerformed(ActionEvent arg0) {
Alert1.setVisible(false);
waitFlag=false;
System.out.println("We received an ActionEvent " + arg0);
Generations=generation.getText();
System.out.println(Generations);
Rule = "";
if (rulesCombo.getSelectedIndex() != -1) {
Rule =
(String) rulesCombo.getItemAt
(rulesCombo.getSelectedIndex());
}
System.out.println(Rule);
int rule=Integer.parseInt(Rule);
Hashtable<String,Integer> rules= new Hashtable<String,Integer>();
CARule ruleClass=new CARule();
rules=ruleClass.setRule(rule);
CAGenetationSet sa =new CAGenetationSet(100, false,rules);
genL=new ArrayList<int[]>();
genL=sa.runSteps(Integer.parseInt(Generations));
System.out.println("calling pattern set");
for(int i=0;i<=genL.size()-1;i++)
{
System.out.println("Painting generation :"+i);
if(stopFlag==false)
{
cacanvas.repaint();
}
//genPaint();
//sleep();
int[] newCell=genL.get(i);
for(int r=0;r<newCell.length;r++)
{
if(newCell[r]==1)
{
System.out.println("Generaton is"+i+"CellLife is"+r);
cacanvas.fillCell(i,r);
}
}
}
/*cacanvas.patternSet(genL);
waitFlag=true;
System.out.println("run completed");
// cacanvas.clearFlag=true;
*/
}
public void genPaint()
{
cacanvas.repaint();
}
public void sleep()
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) {
JUIApp app = new JUIApp() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Run method");
}
};
}
}
Seems like you are using the current Thread on that task, you should create another Thread and add one listeners code to the new Thread.

Populating a JList from a JButton ActionListener

Running into a lot of problems trying to populate a JList after a button press. The code below utilizes a technique that I have employed successfully before, but I have been unable to get this working. The goal is to run a test after pressing a button and display the urls that passed and the urls that failed in separate JLists.
The Action Listener:
//Start button--starts tests when pressed.
JButton start = new JButton("Start");
start.setPreferredSize(new Dimension(400, 40));
start.setAlignmentX(Component.CENTER_ALIGNMENT);
start.addActionListener(new Web(urlA, codeA, cb, passJ, failJ));
panel2.add(start);
The Action Listener Method:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
public class Web implements ActionListener {
private ArrayList<String> urls;
private ArrayList<Integer> statusCodes;
private JComboBox cb;
private JList passJ = new JList();
private JList failJ = new JList();
//constructor--allows other values to be used
public Web(ArrayList<String> urls, ArrayList<Integer> statusCodes, JComboBox cb, JList passList, JList failList ){
this.urls = urls;
this.statusCodes = statusCodes;
this.cb = cb;
this.passJ = passJ;
this.failJ = failJ;
}
#Override
public void actionPerformed(ActionEvent event){
ArrayList<String> resultsP = new ArrayList<String>();
ArrayList<String> resultsF = new ArrayList<String>();
//get source
JButton start = (JButton) event.getSource();
//get value from combobox
String selected = cb.getSelectedItem().toString();
if(selected.equals("ALL")){
}
if(selected.equals("STATUS CODE")){
for(int i = 0; i < urls.size(); i++){
try {
URL u = new URL(urls.get(i));
HttpURLConnection connection = (HttpURLConnection)u.openConnection(); //open connection and cast to HttpURLConnection
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == statusCodes.get(i)){
System.out.println(i + "."+ urls.get(i)+" \t\t\t PASS");
resultsP.add(urls.get(i));
}
else{
System.out.println(i + "." +urls.get(i)+ "\t\t\t FAIL");
resultsF.add(urls.get(i));
}
} catch (MalformedURLException | ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (String str: resultsP){
System.out.println(str);
}
System.out.println("/////////////////////////////////////////////////////////////////////////////////");
for (String str: resultsF){
System.out.println(str);
}
passJ.removeAll();
failJ.removeAll();
passJ.setListData(resultsP.toArray());
failJ.setListData(resultsF.toArray()) ;
passJ.repaint();
failJ.repaint();
}//StatusCodeTest
}
}
How the lists are added to the GUI:
JList passJ = new JList(urlA.toArray());
JScrollPane scroll1 = new JScrollPane(passJ);
scroll1.setPreferredSize(new Dimension (700, 150));
scroll1.setMaximumSize( scroll1.getPreferredSize() );
scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll1);
panel2.add(Box.createRigidArea(new Dimension(0,50)));
JList failJ = new JList(urlA.toArray());
JScrollPane scroll2 = new JScrollPane(failJ);
scroll2.setPreferredSize(new Dimension(700, 150));
scroll2.setMaximumSize(scroll1.getPreferredSize());
scroll2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll2);
//spacer
panel2.add(Box.createRigidArea(new Dimension(0,25)));
Any GUIdance would be greatly appreciated.
Seems you have different instances of passJ/failJ in your Web class and GUI class.
passJ.removeAll(); failJ.removeAll(); doesn't clear items of JList, that method from Container.
Here is simple example of adding/clearing items to JList:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestFrame extends JFrame {
private JList<Integer> normal;
private JList<Integer> fail;
private Integer[] vals;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
normal = new JList<Integer>(new DefaultListModel<Integer>());
fail = new JList<Integer>(new DefaultListModel<Integer>());
vals = new Integer[]{1,2,3,4,5,6,7,8,9,33};
JButton add = new JButton("collect data");
add.addActionListener(getCollectListener());
JButton clear = new JButton("clear data");
clear.addActionListener(getClearListener());
JPanel p = new JPanel();
p.add(new JScrollPane(normal));
p.add(new JScrollPane(fail));
JPanel btnPanel = new JPanel();
btnPanel.add(add);
btnPanel.add(clear);
add(p);
add(btnPanel,BorderLayout.SOUTH);
}
private ActionListener getClearListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((DefaultListModel<Integer>)normal.getModel()).removeAllElements();
((DefaultListModel<Integer>)fail.getModel()).removeAllElements();
}
};
}
private ActionListener getCollectListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Integer i : vals){
if(i%3==0){
((DefaultListModel<Integer>)normal.getModel()).addElement(i);
} else {
((DefaultListModel<Integer>)fail.getModel()).addElement(i);
}
}
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}

java drop and drag label to join correct image

this code is only allowing me to reject a string the second time to try to drop in a textArea where there is all ready a string.
public GridLayoutTest() {
JFrame frame = new JFrame("GridLayout test");
connection = getConnection();
try {
statement = (PreparedStatement) connection
result = statement.executeQuery();
while (result.next()) {
byte[] image = null;
image = result.getBytes("image");
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
}
}
catch (SQLException e) {
e.printStackTrace();}
}
So, two things, first...
public void DropTargetTextArea(String string1, String string2) {
Isn't a constructor, it's a method, note the void. This means that it is never getting called. It's also the reason why DropTargetTextArea textArea = new DropTargetTextArea(); works, when you think it shouldn't.
Second, you're not maintaining a reference to the values you pass in to the (want to be) constructor, so you have no means to references them later...
You could try using something like...
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this, true);
}
And then use something like...
if (values[0].equals(dragContents) || values[1].equals(dragContents)) {
In the drop method.
In your dragEnter, dragOver and dropActionChanged methods you have the oppurtunity to accept or reject the drag action using something like dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); or dtde.rejectDrag();
Updated with test code
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DragAndDropExample {
public static void main(String[] args) {
ImageIcon ii1 = new ImageIcon("C:\\Users\\Desktop\\home.jpg");
ImageIcon ii = new ImageIcon("C:\\Users\\Desktop\\images (2).jpg");
// Create a frame
JFrame frame = new JFrame("test");
JLabel label = new JLabel(ii);
JLabel label1 = new JLabel(ii1);
JPanel panel = new JPanel(new GridLayout(2, 4, 10, 10));
JLabel testLabel = new DraggableLabel("test");
JLabel testingLabel = new DraggableLabel("testing");
panel.add(testLabel);
panel.add(testingLabel);
panel.add(label);
panel.add(label1);
Component textArea = new DropTargetTextArea("test", "testing");
frame.add(textArea, BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static class DraggableLabel extends JLabel implements DragGestureListener, DragSourceListener {
DragSource dragSource1;
public DraggableLabel(String text) {
setText(text);
dragSource1 = new DragSource();
dragSource1.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
}
public void dragGestureRecognized(DragGestureEvent evt) {
Transferable transferable = new StringSelection(getText());
dragSource1.startDrag(evt, DragSource.DefaultCopyDrop, transferable, this);
}
public void dragEnter(DragSourceDragEvent evt) {
System.out.println("Drag enter");
}
public void dragOver(DragSourceDragEvent evt) {
System.out.println("Drag over");
}
public void dragExit(DragSourceEvent evt) {
System.out.println("Drag exit");
}
public void dropActionChanged(DragSourceDragEvent evt) {
System.out.println("Drag action changed");
}
public void dragDropEnd(DragSourceDropEvent evt) {
System.out.println("Drag action End");
}
}
public static class DropTargetTextArea extends JLabel implements DropTargetListener {
private String[] values;
public DropTargetTextArea(String string1, String string2) {
values = new String[]{string1, string2};
DropTarget dropTarget = new DropTarget(this, this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void dragEnter(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag enter");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragOver(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject drag over");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void dragExit(DropTargetEvent evt) {
System.out.println("Drop exit");
}
public void dropActionChanged(DropTargetDragEvent evt) {
if (!getText().isEmpty()) {
System.out.println("Reject dropActionChanged");
evt.rejectDrag();
} else {
evt.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
}
}
public void drop(DropTargetDropEvent evt) {
if (!getText().isEmpty()) {
evt.rejectDrop();
} else {
try {
Transferable transferable = evt.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String dragContents = (String) transferable.getTransferData(DataFlavor.stringFlavor);
evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
if (values[0].equals(dragContents) || (values[1]).equals(dragContents)) {
System.out.println("Accept Drop");
setText(getText() + " " + dragContents);
evt.getDropTargetContext().dropComplete(true);
} else {
System.out.println("Reject Drop");
}
}
} catch (IOException e) {
evt.rejectDrop();
evt.dropComplete(false);
} catch (UnsupportedFlavorException e) {
}
}
}
}
}

Display all deserialized Objects in JTable in JAVA

i want to show all objects in a table.
i have a folder named /menschen which contains files like this: "firstname.lastname.ser"
package adressverwaltung;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
// FILE
import java.io.*;
import java.util.*;
import java.util.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.HeadlessException;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
*
* #author
*/
public class Adressverwaltung {
JFrame mainWindow;
final File folder = new File("menschen");
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Adressverwaltung verweiss = new Adressverwaltung();
verweiss.main();
}
public void main() {
mainWindow = new JFrame();
mainWindow.setBounds(0, 0, 800, 400);
mainWindow.setLocationRelativeTo(null);
mainWindow.setLayout(null);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setResizable(false);
mainWindow.setVisible(true);
mainWindow.setLayout(new FlowLayout());
menu();
}
public String deserialize(String m, int field) {
try {
FileInputStream fin = new FileInputStream("menschen\\" + m);
ObjectInputStream ois = new ObjectInputStream(fin);
Person n = (Person) ois.readObject();
ois.close();
switch (field) {
case 1:
return n.vorname;
case 2:
return n.nachname;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void table(String[][] alle) {
String[] columnNames = {
"Vorname", "Nachname"
};
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(alle, columnNames);
f.add(new JScrollPane(table));
f.pack();
f.setVisible(true);
}
private static void serialize(Person m) {
try {
FileOutputStream fileOut =
new FileOutputStream("menschen\\" + m.vorname + "." + m.nachname + ".ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(m);
out.close();
fileOut.close();
} catch (IOException i) {
}
}
public void menu() {
JPanel list = new JPanel();
list.setBorder(BorderFactory.createLineBorder(Color.black));
list.setPreferredSize(new java.awt.Dimension(400, 360));
list.setBackground(Color.white);
mainWindow.add(list);
// Wir lassen unseren Dialog anzeigen
mainWindow.setVisible(true);
int ButtonWidth = 100;
int ButtonHeight = 30;
int ButtonTop = 10;
JButton Button1 = new JButton("List all");
JButton Button3 = new JButton("Search");
Button1.setBounds(10, ButtonTop, ButtonWidth, ButtonHeight);
Button3.setBounds(230, ButtonTop, ButtonWidth, ButtonHeight);
list.add(Button1);
list.add(Button3);
mainWindow.add(list);
createForm();
Button1.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
list(folder);
}
});
}
public void list(final File folder) {
String[][] rowData = new String[3][];
int r = 0;
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
} else {
String name = fileEntry.getName();
rowData[r][0] = deserialize(name, 1);
rowData[r][1] = deserialize(name, 2);
r++;
}
}
table(rowData);
}
private void createForm() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 2));
JButton b = new JButton("Neue Person!");
JLabel vornameLabel = new JLabel("Vorname:");
final JTextField vorname = new JTextField();
JLabel nachnameLabel = new JLabel("Nachname:");
final JTextField nachname = new JTextField();
p.add(vornameLabel);
p.add(vorname);
p.add(nachnameLabel);
p.add(nachname);
p.add(b);
p.setBorder(BorderFactory.createLineBorder(Color.black));
p.setPreferredSize(new java.awt.Dimension(300, 100));
p.setBackground(Color.white);
mainWindow.add(p);
// Wir lassen unseren Dialog anzeigen
mainWindow.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Person m = new Person(vorname.getText(), nachname.getText());
serialize(m);
JOptionPane.showMessageDialog(null, vorname.getText() + "." + nachname.getText() + ".ser abgespeichert.", "Tutorial 2", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
And this is my Person class:
package adressverwaltung;
/**
*
* #author Mahshid
*/
class Person implements java.io.Serializable {
// Allgemeine Kontaktinformationen:
public String vorname;
public String nachname;
// Adresse
public String strasse;
public int hausnummer;
public int postleitzahl;
public String ort;
public String land;
// Telefon
public int mobil;
public int festnetz;
// Email & Kommentar
public String mail;
public String kommentar;
Person(String vorname, String nachname) {
this.vorname = vorname;
this.nachname = nachname;
}
}
I think there is a problem in list() function. this is my first java code so please don't be surpriced if you see any big mistakes :)
By creating a 2D array like this:
String[][] rowData = new String[3][];
you are creating an array where where all the "column" data is not initialized. You can check this for yourself by doing:
for (String[] s: rowData) {
System.out.println(s);
}
Therefore attempting to assign any of the outer array elements to a single String is impossible:
rowData[r][0] = deserialize(name, 1);

Categories