Refresh a jframe from another class - java

I want to refresh(repaint) a jframe if an event in other class occurred, I use some thing like code below but somethimes this code didn't work:
static Container container;
public FrameConstractor()
{
...
container = getContentPane();
...
}
public static void refreshMethod()
{
container.repaint();
}
and I call refresh method when my event occurred; but this code repaint the frame for me some times and some times didn't do any thing!

I think your problem can be solved by changing refreshMethod to:
public static void refreshMethod()
{
container.invalidate();
container.validate();
}

Related

Changing size of Swing JPanel inside of an Eclipse plugin's ViewPart (despite SwingUtilities.invokeLater(Runnable()))

Today, I am working on an Eclipse plugin project, where I am using the standard SWT_AWT bridge in order to plug my Swing components in:
public class MyView extends ViewPart {
public static final String ID = "HelloRCP.view";
Frame frame;
public void createPartControl(Composite parent) {
Composite composite = new Composite(parent, SWT.EMBEDDED | SWT.NO_BACKGROUND);
this.frame = SWT_AWT.new_Frame(composite);
SwingUtilities.invokeLater(new Runnable() {
private MainPanel swingPanel;
public void run() {
this.swingPanel = new MainPanel();
frame.add(swingPanel);
}
});
this.setResizeListener();
}
public void setFocus() {}
private void setResizeListener() {
this.frame.addComponentListener(new frameResizeListener(this));
}
public Frame getFrame() { return this.frame; }
}
I would like to get the "frameResizeListener" to somehow trigger an update of all subsequent Swing components (e.g. JPanels) constructed by the Swing Runnable instance, this upon the ViewPart's size-change, in order to achieve some kind of responsive design.
Somehow then, the underlying JPanels need to get to know about the ViewPart's Frame size...
I have read my fair share of SO Q&As, and only found the answer that "you need to pass a parameter at construction time". But my problem with this is that my usecase happes once the Components in question are already created and living...
The only solution that I see, so far, seems to break Thread-safety, by writing a shared file or property, and then signalling the Runnable to read it once done.
Can anyone else think of a better option please?
Thank you very much in advance for your support ! :) :)
Regards,
Peter

How to call a GUI (Swing) from a Class to the Main Class?

I've seen similar questions answered but could not find an answer to my question. I have a Main Class, which has it's own JFrame. However, I've created a different Class where I've created another JFrame that prompts the user for some data. The Main Class is the main app. The secondary class is supposed to pop up before the main class GUI runs. I've created 2 different packages for each one of the Classes.
So, I'm trying to call an Object of the secondary Class from Main Class but the interface does not appear. I do not get any errors in the code and the App runs as if the Object of secondary Class is not being called at all. I am new to Java and would appreciate some lights on this.
My code is as follows:
Main Class
public class TempConverter extends javax.swing.JFrame {
public TempConverter() {
initComponents();
}
// More code
public static void main(String args[]) {
DemoUserData test = new DemoUserData();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test.setVisible(true);
new TempConverter().setVisible(true);
}
});
}
Secondary Class
public class DemoUserData extends javax.swing.JPanel {
public DemoUserData() {
initComponents();
}
}
Your JFrame is the main window. Before it is shown at the very early start a splash screen maybe shown, normally a small rectange with a logo.
It however seems, you want some input dialog, like say a login. That cannot be a JPanel, but must be a top-level window: JFrame or JDialog. Or one of the JOptionPane dialogs (asking string input, or whatevever).
Maybe you should make a JFrame for your current JPanel, run that.
.
DemoUserDataFrame test = new DemoUserDataFrame(this);
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test.setVisible(true);
}
});
public class DemoUserDataFrame extends JFrame {
//private final JFrame tempConverter;
public DemoUserDataFrame(final JFrame tempConverter) {
//this.tempConverter = tempConverter;
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
tempConverter.setVisible(true);
}
});
}
...
}
In the above, closing test, will make the main JFrame visible.
In order to have a better overview, have the classes not refer one to another, you might look into the Model-View-Controller concept. Then there is one global "Controller" class as intermediator for all business logic. It holds the data (Model), and so on.

How to set the previous jframe visible when current jframe is disposed

I am making a Java gui project and it consists of two frames.
The problem is that when I call the secondframe from the firstframe, I have set it such that the firstframe visibility is set to false. The problem is how do I make the firstframe visible again by using a button from the second frame.
should i ditch this method and create a new jpanel instead??? Does jpanel have similar capabilities as jframe?
Consider using CardLayout. This way you can switch via multiple UIs without needing another frame. Here's how to use it.
Edit: As Guillaume posted in his comment, this answer from Andrew also covers how to use the layout.
Edit2:
As you requested a little more information about my latest post, here's how such a class may look like:
import javax.swing.JFrame;
public abstract class MyFrameManager {
static private JFrame startFrame,
anotherFrame,
justAnotherFrame;
static public synchronized JFrame getStartFrame()
{
if(startFrame == null)
{
//frame isnt initialized, lets do it
startFrame = new JFrame();
startFrame.setSize(42, 42);
//...
}
return startFrame;
}
static public synchronized JFrame getAnotherFrame()
{
if(anotherFrame == null)
{
//same as above, init it
}
return anotherFrame;
}
static public synchronized JFrame getJustAnotherFrame()
{
//same again
return justAnotherFrame;
}
public static void main(String[] args) {
//let's test!
JFrame start = MyFrameManager.getStartFrame();
start.setVisible(true);
//want another window
JFrame another = MyFrameManager.getAnotherFrame();
another.setVisible(true);
//oh, doenst want start anymore
start.setVisible(false);
}
}
This way you would only instantiate every JFrame once, but you could always access them via your manager class. What you do with them after that is your decision.
I also just made it thread-safe, which is crucial for singletons.

Trouble Adding text to JTextArea (append or settext)

So the program I am making uses 2 threads: One for the GUI and one to do the work.
I want updates from the work thread/class to print out on JTextArea in GUI class.
Everything I tried didn't seem to work. I added lines to print out text on the console right after lines to add text to the JTextArea to make sure it had got to the line but everytime console got text but no changes happened to JTextArea in the GUI.
public static void consoleText(String consoleUpdate){
GUI.console.append(consoleUpdate);
}
I tried this in the work class but nothing happened.
Anyone know how to fix my problem?
Edit:
MAIN.JAVA
public class main {
public static void main(String[] args) {
Thread t1 = new Thread(new GUI());
t1.start();
}
GUI.JAVA
public class GUI extends JFrame implements Runnable{
public static JTextArea console;
private final static String newline = "\n";
public void run(){
GUI go = new GUI();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(350, 340);
go.setVisible(true);
}
public GUI(){
setLayout(new FlowLayout());
console = new JTextArea(ConsoleContents, 15, 30);
add(console);
}
WORK.JAVA
...{
consoleText("\nI want this text on the JText Area");
}
public static void consoleText(String consoleUpdate){
GUI.console.append(consoleUpdate);
}
First, as has been said, your GUI should only run on the Event dispatch thread.
As it is written, your GUI class does two things : it's a frame, and a runnable, and both
are used completely independently. As a matter of fact, calling "run" on a your GUI object creates another, unrelated GUI object. That's probably the reason why you see nothing.
So I suggest making your main the following:
... main(...) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUI gui= new GUI();
gui.setVisible(true); // and other stuff
}
});
}
(I would also suggest getting rid of all "static" fields BTW. It's probably the source
of your problems, along with the weird place of the "run" method).
Now, your "consoleText" method, which I assume you call from another thread, should not
modify the text directly, but call SwingUtilities.invokeLater() to do so :
public void consoleText(final String consoleUpdate){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.append(consoleUpdate);
}
});
}
(the "final" declaration is important, as it allows the Runnable to use the consoleUpdate variable).

Disposing and closing windows in Java

Okay, so this might be a stupid question, but I'm new to Java and trying to teach myself things the right way before I develop any bad habits.
Anyway, I was writing a program last night that consisted of a custom class extending Frame and a custom class extending Canvas. The main() method is in the canvas class and I create an instance of the frame class there. The problem is that when the program detects a window close event, I can't dispose the frame because I seemingly have no way to access it from outside the main method. And if I try to define it outside of main(), then I can't use it within. So I ended up skipping dispose() and just using System.exit(0). Is this alright? Is it basically doing the same thing anyway? Or is this a problem I need to fix, and if so, any idea how?
Thanks so much for reading,
Cody
You can get a reference to the frame, from the source property of the event:
class MyWindowListener extends WindowAdapter {
public void windowClosing(WindowEvent e){
Frame frame = (Frame) e.getSource();
frame.dispose();
}
}
Alternatively, since this is an anonymous class (presumably) declared within the constructor, you also have access to the enclosing instance, so you can also write it as:
class MyFrameClass extends Frame {
public MyFrameClass() {
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MyFrameClass.this.dispose();
}
});
}
}
Or you can make it simpler still (as your WindowListener does not have a method of its own called "dispose"):
public void windowClosing(WindowEvent e){
dispose();
}
Not a stupid question. Because of the garbage collector its not such a big issue, however, there are some times when you will want to execute some cleanup when a window closes. So some suggestions:
The Window Closing event should be handled from the Frame itself. For instance:
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
//code here to perform as the window is about to close.
}
});
And I would suggest that you create a separate class for your main method that will invoke the Frame etc.
This is used to close Jframe with an event handler.
current Jframe
public class LoginForm extends JFrame
{
LoginForm()
{
//Some code for Jframe and its components.
if(Condition)
disposewindow();
}
private void disposewindow()
{
WindowEvent closingEvent = new WindowEvent(LoginForm.this,
WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(closingEvent);
}
//you can can use for alternate of dispose()event and it post some event handler **Closing event** ,
// if we can use this closing event to open new window with conditions.
//It means closing child window with closing event, get this flag in main window to make main window as Disable or Enable state
}
//In parent window
#Override
public void windowClosing(WindowEvent arg0) {
// TODO Auto-generated method stub
this.frame.disable();
}

Categories