My image was displaying properly before I had a JButton on top of it. Now that I have added a JButton to my code, my image does not display. In the ActionPerformed method I am telling the button to setVisbible(false). When I click the button, it disapears and all that is behind it is the background.
public class Main extends JFrame implements ActionListener {
public static void main(String[] args) {
Main main = new Main();
}
ImageIcon GIF = new ImageIcon("src/Zombie Steve gif.gif");
JButton button = new JButton("Click me!");
JLabel Label = new JLabel(GIF);
public Main() {
button.addActionListener(this);
Label.setHorizontalAlignment(0);
JFrame Frame = new JFrame("zombieSteveGIF");
Frame.setSize(650, 650);
Frame.setVisible(true);
Frame.add(Label);
Frame.add(button);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
while (true) {
Frame.getContentPane().setBackground(Color.BLUE);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Frame.getContentPane().setBackground(Color.GREEN);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Frame.getContentPane().setBackground(Color.RED);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
button.setVisible(false);
}
}
Your problem is that you have a BorderLayout (the default for JFrames), and you are adding two components in the same position. The default is BorderLayout.CENTER, and by adding two components with just the default constraints, the first one is removed and the second put in its place.
As for fixing your problem, what do you want to achieve? If you want the components to show on top of one another, you can use the OverlayLayout. If you don't want this, try some other layout manager.
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 have managed to serialize my very basic GUI-object containing a JTextArea and a few buttons to a file 'test.ser'.
Now, I would like to completely restore the previously saved state from 'test.ser', but seem to have a misconception of how to properly deserialize an objects state.
The class MyFrame creates the JFrame and serializes it.
public class MyFrame extends JFrame implements ActionListener {
// Fields
JTextArea textArea;
String title;
static MyFrame gui = new MyFrame();
private static final long serialVersionUID = 1125762532137824262L;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
gui.run();
}
// parameterless default contructor
public MyFrame() {
}
// constructor with title
public MyFrame(String title) {
}
// creates Frame and its Layout
public void run() {
JFrame frame = new JFrame(title);
JPanel panel_01 = new JPanel();
JPanel panel_02 = new JPanel();
JTextArea textArea = new JTextArea(20, 22);
textArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel_01.add(scrollPane);
// Buttons
JButton saveButton = new JButton("Save");
saveButton.addActionListener(this);
JButton loadButton = new JButton("Load");
loadButton.addActionListener(this);
panel_02.add(loadButton);
panel_02.add(saveButton);
// Layout
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER, panel_01);
frame.getContentPane().add(BorderLayout.SOUTH, panel_02);
frame.setSize(300, 400);
frame.setVisible(true);
}
/*
*
*/
public void serialize() {
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser"));
oos.writeObject(gui);
oos.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ev) {
System.out.println("Action received!");
gui.serialize();
}
}
Here I try to do the deserialization:
public class Deserialize {
static Deserialize ds;
static MyFrame frame;
public static void main(String[] args) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));
frame = (MyFrame) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Maybe somebody could point me into the direction where my misconception is?
How would you guys write a class, which deserializes and restores the previously serialized gui-elements to their previously serialized state?
The way I am doing it right now seems to have more than one flaw in its concept, right?
What happens? Are you getting an exception? From the looks of the code ds is never initialised. I believe, once deserialised, you will need to show the frame with frame.setVisible(true);. As always, Swing (and in fact AWT) should be used only on the AWT Event Dispatch Thread (EDT) - use java.awt.EventQueue.invokeLater.
Generally using statics is not a good idea. Nor is serialising GUI components. final is good, and will, for the most part, make sure instance and static fields are initialised.
As says in every javadoc swing component, the preferred way to serialize JFrame, and others JFoo is the XMLEncoder.
The classic serialization works in some little GUI applications, but not with long life GUI components applications.