Java Swing refresh JPanel - swing

I have a Applet class (extends JApplet). Inside the class I am instantiating a JPanel and initializing a JButton whit setEnabled(true). After the user clicks this button in the Panel and does some processing, I call a method inside of the JPanel to update the panel. I then do setEnabled(false) the button clicked on the JPanel.
However, the JPanel is not "refreshing" correctly after I call add(ScrollPane) on main panel. After the processing and setting the JButton to not enabled (and I confirmed that the right data is there etc), the JPanel still is in its initialized form.
In other words, what do I need to do so that calling add(JScrollPane) on a JPanel within a applet actually refreshes the Panel?
Basically i'm wondering: if you update the panel inside a swing component which is nested inside of a JApplet, should the update be visible? What needs to be done to refresh if not?
THIS IS THE CODE:
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (STAMPA_COMMAND.equals(command)) {
stampa.setEnabled(false);
JPanel areaPrint = new JPanel();
JLabel lab = new JLabel("Wait Printing...");
areaPrint.setBackground(Color.magenta);
areaPrint.add(lab);
scrollArea.getViewport().add(areaPrint); // THIS IS THE PROBLEM...THE CHANGE ARE NOT REFRESHED
try {
PrintPdf printPDFFile;
ArrayList assegniDaStampare = new ArrayList();
for (int i = 0; i < assegni.size(); i++) {
DatiAssegno datiAss = (DatiAssegno) assegni.get(i);
if (datiAss != null && datiAss.getStatoAssegno().equals(STATUS_OK)) {
printPDFFile = new PrintPdf("Stampa Assegni", datiAss);
printPDFFile.print();
String servletLocation = "http://localhost/Servlet";
// connect to the servlet
URL studentDBservlet = new URL(servletLocation);
URLConnection servletConnection = studentDBservlet.openConnection();
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
OutputStream outstream = servletConnection.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstream);
oos.writeObject(datiAss.idAssegno);
oos.flush();
oos.close();
ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
try {
String statusSave = (String) inputFromServlet.readObject();
} catch (ClassNotFoundException e4) {
e4.printStackTrace();
}
}
}
JPanel areaPrint2 = new JPanel();
JLabel lab2 = new JLabel("Print Complete");
areaPrint2.setBackground(Color.green);
areaPrint2.add(lab2);
scrollArea.getViewport().add(areaPrint2);
} catch (FileNotFoundException e1) {
//do something
} catch (IOException e2) {
//do something
} catch (PrinterException e3) {
//do something
}
}
if (EXIT_COMMAND.equals(command)) {
JSObject win = JSObject.getWindow(appletParent);
appletParent.stop();
appletParent.destroy();
win.eval("self.close()");
}
}

First off, you shouldn't be opening a connection within the action. Use a SwingWorker or some other executor to do this.
Secondly, try calling revalidate() on the panel after adding the scrollpane. These two fixes should solve the problem.

Related

add Listener to logger context in logback

I have the following code for adding a listener to my logger context:
private static void configureLoggerContext(String logbackConfigFileUrl) {
File file = new File(logbackConfigFileUrl);
LoggerListener loggerListener = new LoggerListener();
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
loggerContext.reset();
loggerContext.addListener(loggerListener);
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(loggerContext);
try {
configurator.doConfigure(file);
} catch (JoranException je) {
throw new RuntimeException(je.getMessage());
}
}
Is there anyway so that I won't have to doConfigure after adding listener?
My problem is that I have added a and because two times configuration, my header is printed twice.

Search Result in new Window (JavaFx)

I am currently working on a software module consisting of searching in a database using JavaFx.
Everything is working as expected.
But the only problem is that in my result table I am showing only few details of search (from UX issues: I have too much details and long texts).
What I would like to do is to show a new window with all details of a clicked row in TextFields and TextArea.
I looked at several tutorials and answers, but unfortunately nothing is working.
Any help would be appreciated!
Thank you.
SearchResult.setOnMouseClicked(new EventHandler<MouseEvent>() {
Gemo temp;
#Override
public void handle(MouseEvent event) {
Gemo row = SearchResult.getSelectionModel().getSelectedItem();
if(row == null) {
System.out.print("I am not in");
return ;
}
else {
temp = row;
String id = String.format(temp.getRef());
System.out.println(id);
FXMLLoader loader=new FXMLLoader();
loader.setLocation(getClass().getResource("DetailsWindow.fxml"));
ControllerDetails gemodetails=loader.getController();
ControllerDetails gd=new ControllerDetails();
gd.SearchById(id);
try{
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
Parent p= loader.getRoot();
Stage stage=new Stage();
stage.setTitle("More Details");
stage.setScene(new Scene(p));
stage.show();
}
}
});
public class ControllerDetails {
#FXML
private TextField fn_patient;
#FXML
private TextField ln_patient;
#FXML
private TextField db_patient;
#FXML
private TextField id_patient;
#FXML
private TextField id_visit;
#FXML
private TextField date_visit;
#FXML
private TextField fn_user;
#FXML
private TextField ln_user;
#FXML
private TextField status;
#FXML
private TextArea com;
#FXML
public void initialize(){
}
public void SearchById(String id) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
connection = ConnectionConfiguration.getConnection();
statement = connection.prepareStatement("my_sql_query");
rs = statement.executeQuery();
while (rs.next()) {
id_visit.setText(rs.getString(1));
id_patient.setText(rs.getString(2));
date_visit.setText(rs.getString(3));
com.setText(rs.getString(4));
fn_patient.setText(rs.getString(5));
ln_patient.setText(rs.getString(6));
db_patient.setText(rs.getString(7));
fn_user.setText(rs.getString(8));
ln_user.setText(rs.getString(9));
status.setText(rs.getString(10));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try to create a simple fxml file with a listView. Place the data you are interested in into this listView. If you prefer something else than listView, that's ok too.
To open such fxml in a new window try something like that:
Stage s = new Stage();
try {
s.setScene(new Scene(new FXMLLoader(getClass().getResource("your_fxml_name")).load()));
s.show();
} catch (IOException e) {
e.printStackTrace();
}
You have two action options: either extract all the data and paste it into a table, or extract a small part that you put in a table, and extract the extra on demand (display details).
The example I give is not addicted to the approach - it simply tells how to transfer table data (a selected row) to a dialog (its controller)
public class Controller {
#FXML
private TableView<MySearchResult> tableView;
#FXML
private void initialize() {
tableView.setItems(new Database().serach("query", "query"));
tableView.setOnMouseClicked(event -> {
if(event.getClickCount() == 2) {
showDetailsDialog();
}
});
}
private void showDetailsDialog() {
MySearchResult result = tableView.getSelectionModel().getSelectedItem();
if(result == null) {
return;
}
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("details_dilaog.fxml"));
Dialog dlg = new Dialog();
dlg.initOwner(tableView.getScene().getWindow());
dlg.initModality(Modality.APPLICATION_MODAL);
dlg.getDialogPane().setContent((Parent) loader.load());
dlg.getDialogPane().getButtonTypes().setAll(ButtonType.OK);
DetailsDialogControler ddc = loader.getController();
ddc.showDetailsFor(result);
dlg.showAndWait();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
My goal is to show the logic in the showDetailsDialog() function.

Display images in observable collection one after the other as user scrolls in windows phone 8

I have a json array of image URLs added into an observable collection and I want to display the first image on the page such that when a user scrolls horizontally, next or previous images in the array shall display on the screen. Help me achieve this.
Here's how I download the image URLs via json and add them to the observable collection
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<readPageModel> readPages = new ObservableCollection<readPageModel>();
public ObservableCollection<readPageModel> Read_Pages
{
get
{
return readPages;
}
set
{
readPages = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Read_Pages"));
}
}
}
public void DownloadData()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://########/mob/ranges/id/3/limit/10/offset/0/r_id/6", UriKind.Absolute));
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (!string.IsNullOrEmpty(e.Result))
{
string data = e.Result;
var items = JsonConvert.DeserializeObject<readModel[]>(data);
foreach (var x in items)
{
Read_Pages.Add(x);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You can take scrollviwer in the xaml after this within this scrollviewer take stack panel with horizontal orientation. and then from c# code add image control to this stack panel.
You can have one image control in content panel and implement below code :
public Page()
{
InitializeComponent();
GestureListener gestureListener = GestureService.GetGestureListener(ContentPanel);
gestureListener.DragCompleted += gestureListener_DragCompleted;
//set the initial image to Image control
}
void gestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
{
// User flicked towards left
if (e.HorizontalVelocity < 0)
{
// Load the next image if Downloaded
}
// User flicked towards right
if (e.HorizontalVelocity > 0)
{
// Load the previous image
}
}
you would also needed to have one variable for tracking the index of image to be loaded

Infinite wait loading remote image into BitmapImage() in Background Agent

I have a valid URL for a remote JPEG which I'm trying to load in the background. But I find I never get control back after invoking the BitmapImage() constructor. My question is, should this approach work, or should I pitch it all, load up BcpAsync project from NuGet and start working with WebClient asynch methods?
A sample URL for which it fails is
http://image.weather.com/images/maps/current/garden_june_720x486.jpg
It is valid. .UpdateAsync() references it from AppViewModel.Instance, it's not explicitly referenced here.
Here's the background agent:
protected override async void OnInvoke(ScheduledTask task)
{
AppViewModel.LoadData();
await AppViewModel.Instance.RemoteImageProxy.UpdateAsync();
AppViewModel.Instance.ImageUrl = AppViewModel.Instance.RemoteImageProxy.LocalFileUri;
AppViewModel.Instance.UpdateCount++;
PinnedTile.Update();
}
AppViewModel.SaveData();
#if DEBUG
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(AppViewModel.Instance.BgAgentInterval));
#endif
NotifyComplete();
}
Here's the invoked method:
public Task<double> UpdateAsync() {
LastCheckedTime = DateTime.UtcNow;
CompletionTask = new TaskCompletionSource<double>();
// Not usually called on UI thread, not worth optimizing for that case here.
Deployment.Current.Dispatcher.BeginInvoke(() => { //todo determine whether System.Windows.Deployment.Dispatcher can be called from main app, or just bgAgent.
HelperImageControl = new Image();
HelperImageControl.Loaded += im_Loaded;
HelperImageControl.ImageFailed += im_ImageFailed;
HelperImageControl.ImageOpened += im_ImageOpened;
// breakpoint here
HelperImageControl.Source = new BitmapImage(SourceUri);
// stepping over the function, control does not return here. Nor are any of the above events fired.
});
return CompletionTask.Task; // this will be completed in one of the subsequent control events...
}
You need to call CompletionTask.SetResult(); to return control back to the caller method.
This works (I'm returning 100 in case of successful download because you set the task to return double).
TaskCompletionSource<double> CompletionTask;
public Task<double> UpdateAsync()
{
CompletionTask = new TaskCompletionSource<double>();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var HelperImageControl = new Image();
var bmp = new BitmapImage();
bmp.ImageOpened += bmp_ImageOpened;
bmp.ImageFailed += bmp_ImageFailed;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = new Uri("http://image.weather.com/images/maps/current/garden_june_720x486.jpg", UriKind.Absolute);
HelperImageControl.Source = bmp;
});
return CompletionTask.Task;
}
void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
CompletionTask.SetException(e.ErrorException);
}
void bmp_ImageOpened(object sender, RoutedEventArgs e)
{
CompletionTask.SetResult(100);
}

writing output to textarea in another class

hi i am new to java and am stuck here, been quite a while now that i can move forward; i have created a GUI interface for a chat system(although very rough because i have used the java help file and alot i have never done before). but i have another code which is standing on its own, no GUI at all, all out put are on command prompt. now i want to append all the output to the GUI that i have created. please help take a look at the codes below and suggest ways and stepps to help figure it out... please this is not an assignment from college, i am a graduate and working so i do this when i have time, because i believe knowing java is a great knowledge. thank you for your time.
this is the chat GUI Class that i created
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainView extends JFrame {
protected JLabel msgLabel, bannerLabel;
protected JButton sendBtn;
protected JTextArea genMsg, frndLst;
protected JTextField msgF;
protected JMenuBar menubar;
protected JMenu loginmenu, aboutmenu;
protected JMenuItem loginitem, disconnectitem, seperatoritem, quititem, aboutitem;
protected Toolkit toolkit;
MultiThreadChatClient chatClient;
public MainView() {
toolkit = Toolkit.getDefaultToolkit();
if(toolkit.getScreenSize().getWidth() > 600)
setSize(600, 575);
else
setSize((int)toolkit.getScreenSize().getWidth(),(int toolkit.getScreenSize().getHeight() - 20);
setResizable(false);
Dimension dimension = getSize();
setLayout(new FlowLayout());
setTitle("FRESHER MARKETING COMPANY");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) { System.exit(0);}});
menubar = new JMenuBar();
loginmenu = new JMenu("Login");
loginitem = new JMenuItem("Login");
disconnectitem = new JMenuItem("Disconnect");
seperatoritem = new JMenuItem("---------------");
quititem = new JMenuItem("Quit");
loginmenu.add(loginitem);
loginmenu.add(disconnectitem);
loginmenu.add(seperatoritem);
loginmenu.add(quititem);
aboutmenu = new JMenu("Help ");
aboutitem = new JMenuItem("About ");
aboutmenu.add(aboutitem);
menubar.add(loginmenu);
menubar.add(aboutmenu);
setJMenuBar(menubar);
Container container = getContentPane();
container.setLayout(new FlowLayout());
// create an ImageIcon
ImageIcon banner =new ImageIcon("images\\defaultbanner.gif");
bannerLabel = new JLabel(banner);
container.add(bannerLabel);
// create General Message Screen
genMsg = new JTextArea(30,45);
genMsg.setEditable(false);
genMsg.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
genMsg.setLineWrap(true);
container.add( new JScrollPane( genMsg ));
// create Friend List View
frndLst = new JTextArea(30, 15);
frndLst.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
container.add( new JScrollPane( frndLst));
frndLst.setEditable(false);
frndLst.setLineWrap(true);
msgLabel = new JLabel ("Message:");
container.add(msgLabel);
// create Message Field
msgF = new JTextField(38);
msgF.setEnabled( true );
msgF.setText("");
msgF.requestFocus();
msgF.addActionListener(
new ActionListener()
{
// send message to client
public void actionPerformed( ActionEvent event )
{
// sendData( event.getActionCommand() );
}
} // end anonymous inner class
); // end call to addActionListener
container.add(msgF);
// create Send Button
sendBtn = new JButton ("Send");
container.add(sendBtn);
setVisible( true );
}
public static void main(String[] args)
{
MainView application = new MainView();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
and this is the Chat multithread system that i want to append.
import java.io.*;
import java.net.*;
public class MultiThreadChatServer{
// Declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
static Socket clientSocket = null;
static ServerSocket serverSocket = null;
// This chat server can accept up to 10 clients' connections
static clientThread t[] = new clientThread[10];
public static void main(String args[]) {
// The default port
int port_number=2222;
if (args.length < 1)
{
System.out.println("Usage: java MultiThreadChatServer \n"+
"Now using port number="+port_number);
} else {
port_number=Integer.valueOf(args[0]).intValue();
}
// Initialization section:
// Try to open a server socket on port port_number (default 2222)
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
serverSocket = new ServerSocket(port_number);
}
catch (IOException e)
{System.out.println(e);}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams for this socket will be created in
// client's thread since every client is served by the server in
// an individual thread
while(true){
try {
clientSocket = serverSocket.accept();
for(int i=0; i<=9; i++){
if(t[i]==null)
{
(t[i] = new clientThread(clientSocket,t)).start();
break;
}
}
}
catch (IOException e) {
System.out.println(e);}
}
}
}
// This client thread opens the input and the output streams for a particular client,
// ask the client's name, informs all the clients currently connected to the
//server about the fact that a new client has joined the chat room,
// and as long as it receive data, echos that data back to all other clients.
// When the client leaves the chat room this thread informs also all the
// clients about that and terminates.
class clientThread extends Thread{
DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
clientThread t[];
public clientThread(Socket clientSocket, clientThread[] t){
this.clientSocket=clientSocket;
this.t=t;
}
public void run()
{
String line;
String name;
try{
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
os.println("Enter your name.");
name = is.readLine();
os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line");
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" );
while (true) {
line = is.readLine();
if(line.startsWith("/quit")) break;
for(int i=0; i<=9; i++)
if (t[i]!=null) t[i].os.println("<"+name+"> "+line);
}
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
os.println("*** Bye "+name+" ***");
// Clean up:
// Set to null the current thread variable such that other client could
// be accepted by the server
for(int i=0; i<=9; i++)
if (t[i]==this) t[i]=null;
// close the output stream
// close the input stream
// close the socket
is.close();
os.close();
clientSocket.close();
}
catch(IOException e){};
}
}
any suggestions would do really. be it steps to achieve this, links to make things easier, a code snippet... thank you..
i would like an example on how to append the ouputs from MultiThreadChatServer class to the textarea in MainView class
EDIT: re-read the code and noticed that the gui code actually holds an instance of the chat client. Have you considered making the chat client observable for chat client events and then setting the gui as a listener for those events?