I am new to java, I facing a problem while trying to change the look and feel of a java file when invoked from another class. I have two classes, main.java and auth.java. I have set the look and feel as nimbus in the auth.java file. When I try to invoke auth class from main.java(i have attached the code snippet below) the UI doesn't change. But when i use
public static void main(String[] args) in auth.java and try to run that file individually the UI of the jFrame changes. Kindly let me know if there is a way to change the UI of a jFrame when called from another class. And is there any problem invoking the jFrame from another class, is that a good practice? because we are onto doing a big project and will require calling authentication frame once in a while, so any suggestion guys?
Thank you all in advance! :)
main.java:
package com.package.name;
public class main {
public static void main(String[] args) {
new auth();
}
}
This is a section of my auth.java code:
package com.package.name;
import javax.swing.*;
import java.awt.*;
public class auth extends JFrame {
public auth() {
initComponents();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel ( "javax.swing.plaf.nimbus.NimbusLookAndFeel" );
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
});
}
You've already called initComponents before changing the look at feel. This will install what ever is the currently installed look and feel into those components.
Without having to go and instruct each component to update its UI, you could simply swap the installation of the look and feel with the initComponents method, for example...
try {
UIManager.setLookAndFeel ( "javax.swing.plaf.nimbus.NimbusLookAndFeel" );
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
initComponents();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
Now, having said that. You really should have been within the context of the EDT before you called the auth constructor and auth shouldn't really be making decisions about the Look and Feel. What happens if you want to use this frame again with a different look and feel?
Instead could do something more like
public class main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel ( "javax.swing.plaf.nimbus.NimbusLookAndFeel" );
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
new auth();
}
});
}
}
public class auth extends JFrame {
public auth() {
initComponents();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
You should also consider taking a look through Code Conventions for the Java Programming Language, it will make your code much easier to read ;)
Related
So I'm working on a project with JFrames. When the programm starts it creates a JFrame in a Method called "initialThread" and then it sets the bounds, Default Close Operation and the visibility in a Method called "initialize".
When debugging the Method "initialThread", the frame automaticaly becomes visible without me excecuting the "initialize" Method.
The Code where I run the Methods:
public void loadPanels(){
initialThread();
initialize();
}
Here's the code with the two Methods i was talking about:
public void initialThread(){
try {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
try {
frame = new JFrame();
frame.setAlwaysOnTop (true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* set the basic functions and configurations of the frame.
*/
private void initialize() {
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
I'm trying to implement a JEditorPane with hyperlinks. I'm using a HyperLinkListener but it seems to never trigger.
Code:
JEditorPane editorPane = new JEditorPane("text/html", programInfo);
editorPane.addHyperlinkListener(e -> {
System.out.println("CLICK");
if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED))
try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
});
JOptionPane.showMessageDialog(contentPane, editorPane);
Sample HTML:
<body>
<p><b>Author:</b> James - sample</p>
</body>
This leads to this:
But when I click on the links nothing happens.
Additional Info:
I'm testing this on Ubuntu 14.04.
I have set Look and Feel to system.
EDIT: thanks to #AndrewThompson for finding the real issue.
The reason why it does not trigger events is because the editor pane will only fire events when it is not editable. So, to make your code work you should add this line after the construction of the editorPane:
editorPane.setEditable(false);
Below you can find a self contained example:
public class TestFrame extends JFrame {
public static void main(String[] args) {
JEditorPane editorPane = new JEditorPane("text/html", "test link to example.com");
editorPane.addHyperlinkListener(new HyperlinkListener() {
#Override
public void hyperlinkUpdate(HyperlinkEvent e) {
System.out.println("CLICK");
if (e.getEventType().equals(HyperlinkEvent.EventType.ENTERED)) try {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(e.getURL().toURI());
}
}
catch (IOException e1) {
e1.printStackTrace();
}
catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
});
editorPane.setEditable(false); // otherwise ignores hyperlink events!
JFrame frame = new JFrame("EditorPane Example");
frame.add(editorPane);
frame.setSize(300,200);
frame.setVisible(true);
} }
(sorry, I removed the lambda because I don't have a jdk8 on this PC)
So I am making this code to write to a file based on user clicks. The only problem I have, is that I get an error on "public class prog". The prog name is where I get the error: It says: The type prog must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent). When I do the quickfix of adding the uninherited methods, it adds the action listener method to the end of my code but with nothing in it. If I already have action listeners in the program, why does it tell me I need to implement them? And why when I add it at the end, does it work fine even though nothing is in it?
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.*;
public class prog extends JFrame implements ActionListener {
//create newLine
final String newLine = System.getProperty("line.separator");
//create buttons
JPanel row1 = new JPanel();
JButton oneLeft = new JButton("oneLeft");
JButton oneRight = new JButton("oneRight");
JPanel row2 = new JPanel();
JButton twoLeft = new JButton("twoLeft");
JButton twoRight = new JButton("twoRight");
JPanel row3 = new JPanel();
JButton threeLeft = new JButton("threeLeft");
JButton threeRight = new JButton("threeRight");
public prog() {
super("Prog");
setLookAndFeel();
setSize(400, 800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout = new GridLayout(3, 2);
setLayout(layout);
//create outStream for writing to file
try {
final File numClicks = new File("numClicks.properties");
final FileOutputStream outStream = new FileOutputStream(numClicks);
//add Listeners
oneLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "oneLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
oneRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "oneRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
twoLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "twoLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
twoRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "twoRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
threeLeft.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "threeLeft has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
threeRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
write(outStream, "threeRight has been clicked.");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
} catch (IOException ioe) {
System.out.println("The file could not be written.");
}
row1.add(oneLeft);
row1.add(oneRight);
row2.add(twoLeft);
row2.add(twoRight);
row3.add(threeLeft);
row3.add(threeRight);
add(row1);
add(row2);
add(row3);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
//ignore error
}
}
void write(FileOutputStream stream, String output) throws IOException {
output = output + newLine;
byte[] data = output.getBytes();
stream.write(data, 0, data.length);
}
public static void main(String[] args) {
prog progApp = new prog();
}
}
Your class shouldn't implement ActionListener. Instead of writing a top-level class that implements the interface, you're writing a bunch of little inline classes (called anonymous inner classes) that do this work for you when you say new ActionListener().
You implement ActionListener it, but you don't actually implement the required methods (i.e., actionPerformed()). Therefore your class is invalid to the compiler.
You need a method like:
#Override
public void actionPerformed(ActionEvent e) {
// ...
}
The way an interface works is that it defines what the classes that implements it have to... well... implement. That way any other process can treat it as an ActionListener and know that certain methods have been defined.
Just another way Java tries to make polymorphism your friend.
To address something from the comment below, it's actually not that uncommon to see a class implement an interface (like KeyListener) and define the method without even using it.
For example, KeyListener requires you to implement three different methods:
public void keyPressed(KeyEvent e);
public void keyReleased(KeyEvent e);
public void keyTyped(KeyEvent e);
Let's say I only really care about keyPressed. Then my class might look something like this:
public class MyKeyListener implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
// do stuff
}
#Override
public void keyReleased(KeyEvent e){}
#Override
public void keyTyped(KeyEvent e){}
}
I have a JDesktopPane with this code.
public class Menu extends JFrame implements ActionListener{
/**
* Creates new form Portada
*/
public static JDesktopPane desktop;
public JDesktopPane getDesktop() {
return desktop;
}
public Menu() {
desktop = new JDesktopPane();
setContentPane(desktop);
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
initComponents();
}
}
then i add the new components like this
desktop.add(orden);
and when i want to call them i use
if(e.getSource()==jMenuItem1_1){
orden.setVisible(true);
desktop.setSelectedFrame(orden);
desktop.moveToFront(orden);
try {
orden.setSelected(true);
} catch (PropertyVetoException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
The problem i get is that when "orden" wants to pop out another JInternalFrame i use the next code.
searchSupplier.setVisible(true);
Main.getInstance().getPortada().getDesktop().add(searchSupplier);
Main.getInstance().getPortada().getDesktop()
.moveToFront(searchSupplier);
try {
searchSupplier.setSelected(true);
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
When I execute the event more than 2 times i get the next error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: illegal component position
Where should i add the new JInternalFrame to the DesktopPane? or to Orden?, or What can i do to fix this error?
If the searchSupplier frame is already on the desktop, it is unlikely that you will able to add it again. Try using getParent to determine if the frame needs to be added
if (searchSupplier.getParent() == null) {
Main.getInstance().getPortada().getDesktop().add(searchSupplier);
}
searchSupplier.setVisible(true);
Main.getInstance().getPortada().getDesktop().moveToFront(searchSupplier);
try {
searchSupplier.setSelected(true);
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I use Google Wave, and I want to emulate the ability to send messages before you actually hit the enter key.
Is there a Java equivalent to the C function _getch()?
You could use the JLine library's ConsoleReader.readVirtualKey() method. See http://jline.sourceforge.net/apidocs/jline/ConsoleReader.html#readVirtualKey().
If you don't want to use a 3rd party library, and if you are on Mac OS X or UNIX, you can just take advantage of the same trick that JLine uses to be able to read individual characters: just execute the command "stty -icanon min 1" before running your program, and then System.in will no longer be line buffered and you can get an individual character using System.in.read(). Unfortunately, this trick doesn't work on Windows, so you would need to use a native library to help (or just use JLine).
I found a code, Equivalent function to C's “_getch()
public static void getCh() {
final JFrame frame = new JFrame();
synchronized (frame) {
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e) {
synchronized (frame) {
frame.setVisible(false);
frame.dispose();
frame.notify();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
});
frame.setVisible(true);
try {
frame.wait();
} catch (InterruptedException e1) {
}
}
}
Initially I thought of System.in.read(), but you need to get input without pressing Enter. That requires native console interaction (and console is different under every system).
So answer is "no, there is no direct analogue".
There's no getch equivalent in java. You might as well create a GUI component and bind the keyEvent Listener.
Custom-made method in Java for getch() function of C
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
class getch
{
public static void getCh()
{
final JFrame frame = new JFrame();
synchronized(frame)
{
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.addKeyListener(new KeyListener()
{
public void keyPressed(KeyEvent e)
{
synchronized(frame)
{
frame.setVisible(false);
frame.dispose();
frame.notify();
}
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
});
frame.setVisible(true);
try
{
frame.wait();
}
catch(InterruptedException e1)
{
}
}
}
}
This will Do the trick but i works only from command line . Not from IDE
Console c =System.console();
Reader r = c.reader();
try {
num= r.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
why don't you just create a variable Scanner that don't use it, the program, in anywhere.
pause0 = pause1.nextInt();
:l it seems a lot more easy... Plus you can put a message saying "Press to continue.";