In Java, I want to set the Look and Feel of the program (specifically to the 'get system look and feel').
Is it necessary to set the look and feel inside each component (aka, each JPanel, each JFrame)?
Or is setting the look and feel once, enough to affect the whole application?
If once is enough, then where should I place the code to do so (in what class?)
You define it in the main method and it will be used everywhere.
This is the main screen's main method:
Example:
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainScreen mainWindow = new MainScreen();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
mainWindow.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Or is setting the look and feel once, enough to affect the whole application?
Correct
If once is enough, then where should I place the code to do so (in what class?)
Usually, in a class which creates the application frame (before it is created):
UIManager.setLookAndFeel(lookAndFeelName);
...
JFrame frame = new JFrame(...);
Also, you can change LnF on the fly for the whole application, if you need:
UIManager.setLookAndFeel(lookAndFeelName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
Related
I've been trying to learn java for a few weeks now, and I'm working on a pretty simple autoclicker.
The clicker itself works, but my problem is that my GUI never shows up.
The GUI runs just fine when I run the GUI file itself, but when I'm trying to run it from my main program (different file) it never shows. The clicker works fine all the time though. I'm sure the problem is something really simple that I have simply missed, but this is now my 4th day without any clue on what might be wrong with it, so decided I'd ask here.
Beware - the code is really messy atm, because I've been trying pretty much everything possible to get it working.
This is the code in the main program trying to run the GUI.
package autoclicker;
import java.awt.AWTException;
/**
* The main program for the autoclicker.
*/
public class AutoClicker {
public static void main(String[] args) throws AWTException {
Click click = new Click(true);
click.clicker();
try {
Swingerinos sw = new Swingerinos();
sw.initialize();
}
catch (AWTException e) { e. printStackTrace(); System.exit(-1); }
}
}
And this is the whole GUI file.
package autoclicker;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class Swingerinos extends Click implements WindowListener,ActionListener {
private int numClicks = 0;
TextField text;
private JFrame frame;
/**
* #wbp.nonvisual location=181,19
*/
private final JLabel lblAutoclicker = new JLabel("AutoClicker");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Swingerinos window = new Swingerinos();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Swingerinos() throws AWTException {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 109);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.WEST);
JButton btnNewButton = new JButton("Toggle On / Off");
text = new TextField(20);
text.setLocation(100, 100);
btnNewButton.addActionListener( this);
btnNewButton.setToolTipText("Toggles the autoclicker on / off.");
panel.add(btnNewButton);
panel.add(text);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
toggle();
numClicks++;
text.setText(""+numClicks);
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
}
I know the GUI file is really messy (there's 2x initialize(), one in the main program and one in the GUI file, and lots of other stuff, but I'm just too confused as for what to do now.
EDIT: I added the whole main program code, also this is the code for the autoclicker.
package autoclicker;
import java.awt.*;
import java.awt.event.InputEvent;
public class Click {
private boolean active;
private Robot robot;
public Click(boolean active, Robot robot) {
this.active = active;
this.robot = robot;
}
public Click() throws AWTException {
this(false, new Robot());
}
public Click(boolean active) throws AWTException {
this(active, new Robot());
}
//TODO: add click.toggle() to somewhere and control da clicker
public void toggle() {
active = !active;
}
public void clicker() {
while (active) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.setAutoDelay(10000);
}
}
}
Expanding JB Nizet's comment(s) into an answer.
The immediate cause:
When the JVM calls your code, it is run on the main thread. It calls main(String[]), as you know. You posted two main methods, only one of which is relevant to your nothing-is-happening problem: AutoClick#main(String[]). Let's go through it:
Click click = new Click(true);
click.clicker();
This first of the above two lines obviously calls the constructor of Click, which sets the active variable to true. So far so good. The second line is much more interesting. It calls Click#clicker(). Let's look at that method:
public void clicker() {
while (active) {
// <snip>
}
}
This method is the problem. Since you haven't started any other threads, the main thread is the only one you have at that moment, the only thread on which you can execute code. When this loop is executed it only finishes when the active variable is set to false. As long as it is true, it will keep looping. This means that Click#clicker() only returns if active is set to false. But, you never do that in the loop itself, meaning you need a thread different from the thread executing the loop to change active. So, how many threads do we have? 1, the main thread. See the problem? Because the loop never ends, the main thread never reaches the statements in the main method after click.clicker().
Simple solution
You could just set a fixed number of iterations:
public void clicker() {
int i = 0;
while (i < 100) { // iterate 100 times
// <snip>
++i;
}
}
Or using a for-loop (recommended):
public void clicker() {
for (int i = 0; i < 100; ++i) {
// <snip>
}
}
This eliminates the need for the active variable and hence the need for another thread.
A somewhat more complicated solution
If you really want the active variable, you'll need to have multiple threads. This is conveniently known as "multithreading"1, a very complicated topic. Luckily, we only need a bit of it, so it is only a bit complicated.
Don't just call the method Click#clicker() like you would normally. This creates your current problem. You'll need a worker thread, which can call the method. The easiest way to create a new thread is to call the constructor of the class Thread which takes a single argument of type Runnable. Like this:
Thread worker = new Thread(new Runnable() {
public void run() {
click.clicker();
}
});
This returns relatively quickly and leaves the Click#clicker() method running on another thread. Your main thread is now free to execute the other statements and even call click.toggle() after a while.
As JB Nizet pointed out, there are some other problems with your code. For example, Swingerinos shouldn't extend Click, but have an instance variable of type Click (http://en.wikipedia.org/wiki/Composition_over_inheritance) (as JB Nizet pointed out). Also, you shouldn't need to implement WindowListener to just call System.exit() when the window closes if you already call frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);. To get all kinds of feedback (not limited to but including this kind of issues, style and design) on working code2 I highly recommend the StackExchange website codereview.stackexchange.com
1: I by no means consider myself even remotely an expert on threading, so I won't go into it. If you want to know more about it, google it - there's lots of texts on multithreading - or ask another question - if you have a specific problem.
2: this is important: broken code is off-topic on Code Review.
I changed my IDE from Eclipse to IntelliJ IDEA. The new one started complaining about my code.
public class Controller {
private OknoGlowne frame;
private MenuListener menuListen = new MenuListener(this);
private TabListener tabListener = new TabListener(this);
public OknoGlowne getFrame() {
return frame;
}
public Controller(){
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new OknoGlowne();
frame.setVisible(true); //error
frame.addMenuListener(menuListen);
frame.addTabListener(tabListener);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
So I commented this line. And add new line to constructor of UI frame.
public OknoGlowne() {
jPanel.setVisible(true);
}
App start but UI doesn't show any more. IDEA create frame in different way than Eclispe. I have to switch.
Main
public class Runner {
public static void main(String[] args) {
new Controller();
}
}
This doesn't really have anything to do with your IDEs. I bet if you ran it 100 times in eclipse, or from the command line, you'd get different results depending on how busy your system is.
The reason you aren't seeing the JFrame pop up is because you're using invokeLater() instead of invokeAndWait().
The invokeLater() method immediately returns, at which point you're in a race condition: will the event thread display the EDT first, or will the main thread exit first? If the main thread exits first, then your program will exit before any windows are shown.
To prevent this, you have to use invokeAndWait() instead of invokeLater().
I want to use the Substance L&F library in my Java application, so I downloaded the .jar files and added them to the project classpath. Then I want to set the L&F in the application's main() function like this:
SwingUtilities.invokeAndWait(new Runnable()
{
#Override
public void run()
{
try
{
// Substance
String skin = "org.pushingpixels.substance.api.skin.SubstanceGraphiteAquaLookAndFeel";
SubstanceLookAndFeel.setSkin(skin);
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
}
catch(Exception e)
{
System.err.println("Can't initialize specified look&feel");
e.printStackTrace();
}
}
});
That is done before the JFrame is being created. However, even though no exception is thrown, nothing happens, the GUI is rendered in default Swing L&F.
Any ideas what I am missing here?
EDIT
Instead of the SubstanceLookAndFeel.setSkin(skin); call I tried it with UIManager.setLookAndFeel(skin); instead. This still doesn't work, but at least I get an exception now:
org.pushingpixels.substance.api.UiThreadingViolationException:
State tracking must be done on Event Dispatch Thread
Isn't that solved by calling this via invokeAndWait()?
EDIT-2
Ok, so the problem was something different. The exception was thrown while creating a JTable, not when setting the L&F. I was able to solve the issue - the L&F is now correctly rendered - by calling the JFrame constructor (which then basically runs the whole application) via EventQueue.invokeLater(). But I never did that before, is it "save" (valid in Java terms) to do it that way?
There is a small trick when setting Substance LaF. You have to call UIManager.setLookAndFeel(new SubstanceGraphiteAquaLookAndFeel()); before you call UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceGraphiteAquaLookAndFeel");. So, set it like this:
public class App {
public static void main(String [] args) {
try {
UIManager.setLookAndFeel(new SubstanceGraphiteAquaLookAndFeel());
UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceGraphiteAquaLookAndFeel");
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException | UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable(){
public void run() {
//Your GUI code goes here..
}
});
}
}
The issue is when I close my GUI windows I wanna run a last method ( for example printList() ) but I couldn't manage to do it. This is my main method
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
patientTest2 screen = new patientTest2();
screen.setVisible(true);
screen.setResizable(false);
} catch (FileNotFoundException ex) {
Logger.getLogger(patientTest2.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
patientTest2 is my JFrame class. I assume that if I put printList() before } catch (FileNotFoundException ex) { it should work and finally print my list to a file but it doesn't. I will be glad if you can help me and explain why of course_?
You should add a listener that extends WindowAdapter to your frame, and override the method windowClosing(WindowEvent e). In this method, you will be able to call any methods you want to call before the window is closed.
You need to
change the default close operation to JFrame.DO_NOTHING_ON_CLOSE (if the window is a JFrame)
add a WindowListener to your top-level window
listen for window closing events, calling your method
and then finally exit the JVM with the appropriate exit code (usually 0 if no errors).
If you want to have something that runs when you Java VM gets shut down, then you should have a look at
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
//The stuff you want to do at shutdown.
}
}));
Please read the here for further information.
You also should set the DefaultCloseOperation of your Window if you want to close your Programm (and shutdown your Java VM) when the JFrame is closed.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This is I think what you were asking for. Hope this helps.
In JGame, the method setBGImage() is supposed to change the background image. This works when I'm setting the background image for the first time at the start of the initialization. However, when I call the same method later to change the background image, it seems to do nothing. What am I doing wrong?
Here's some example code to show you what I mean:
import jgame.*;
import jgame.platform.*;
public class Test extends JGEngine{
public static void main(String[] args) {
new Test();
}
public Test(){
super();
initEngine(640,480);
}
public void initCanvas(){
setCanvasSettings(10,6,64,80,null,JGColor.white,null);
}
public void initGame(){
setFrameRate(35,2);
defineMedia("media.tbl");
doTestBackground();
}
/* Demonstrates the bug */
void doTestBackground(){
new Thread(new Runnable(){
public void run(){
setBGImage("bg1");
/* If it's put here, then it works perfectly:
setBGImage("bg2"); */
try{
Thread.sleep(2000);
}
catch(Exception e){}
/* If it's put here it doesn't work!
The background SHOULD change here but it doesn't */
setBGImage("bg2");
}
}).start();
}
}
If you still want some answer. Here it is:
http://installsteps.blogspot.com/2010/10/jgame-java-game-engine.html
FYI, this setBGImage behaviour is a bug that was fixed in version 3.4. Since 3.4, setBGImage correctly updates the screen.
Perhaps you are running into problems with using the wrong thread? Generally, the AWT thread is used to change components (in the Swing framework).
Try using SwingUtilities.invokeLater(new Runnable() { public void run() { setBGImage("things");} } );