Java JFrame frame.dispose() not working as expected [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to dispose of my frame and create a new one. The new one gets created but the old one persists. I end up having two frames on my desktop. What am I missing? Thanks.
package org.rockislandschools;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DisplayStatus extends JFrame {
public void buildFrame(String ipAdd, String status){
JFrame frame = new JFrame("Host Status");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
JPanel panel = new JPanel();
JLabel ipLabel = new JLabel(ipAdd);
ipLabel.setOpaque(true);
ipLabel.setBackground(Color.white);
ipLabel.setPreferredSize(new Dimension(20, 25));
JLabel stateLabel = new JLabel(status);
stateLabel.setOpaque(true);
if (status.equals("Up")){
stateLabel.setBackground(Color.GREEN);
}
if (status.equals("Down")){
stateLabel.setBackground(Color.red);
}
stateLabel.setPreferredSize(new Dimension(20, 25));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400,400));
frame.getContentPane().add(panel);
frame.getContentPane().add(ipLabel, BorderLayout.CENTER);
frame.getContentPane().add(stateLabel, BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setVisible(true);
}
}
package org.rockislandschools;
import java.io.IOException;
import java.net.InetAddress;
public class HostStatus {
public String IsReachableReturnString(String ip){
String canBeReachedReturnString = "Down";
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReachedReturnString = "Up";
} catch (IOException e) {
e.printStackTrace();
}
return canBeReachedReturnString;
}
public boolean IsReachable(String ip){
boolean canBeReached = false;
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReached = true;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(canBeReached);
return canBeReached;
}
}
package org.rockislandschools;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
if(args.length == 0)
{
System.out.println("Please specify IP Address.");
System.exit(0);
}
String address = args[0];
HostStatus status = new HostStatus();
String currentState = status.IsReachableReturnString(address);
DisplayStatus statusFrame = new DisplayStatus();
statusFrame.buildFrame(address, currentState);
//String newState = status.IsReachableReturnString(address);
while (true){
String newState = status.IsReachableReturnString(address);
if (newState.equals(currentState)){
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE,null, ex);
}
System.out.println("Nothing has changed");
}
else {
statusFrame.setVisible(false);
statusFrame.dispose();
System.out.println("Building a new frame");
currentState = newState;
statusFrame.buildFrame(address, currentState);
}
}
}
}
I am not sure what I need in regards to more details. I can tell you that I am just starting with attempting to learn Java. I live in Iowa and like to spend my free time not being hassled by red arrow boxes that criticize my posts.

When you were calling statusFrame.dispose(); you were calling that on a JFrame that did not exist. I fixed the code and here are each of the files:
EDIT: I have a version of this with system tray and GUI for selecting the IP on my github: https://github.com/ArgonBird18/HostStatus
Main.java
package org.rockislandschools;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
if(args.length == 0)
{
System.out.println("Please specify IP Address.");
System.exit(0);
}
String address = args[0];
HostStatus status = new HostStatus();
String currentState = status.IsReachableReturnString(address);
JFrame statusFrame = new JFrame();
statusFrame = DisplayStatus.buildFrame(address, currentState);
//String newState = status.IsReachableReturnString(address);
while (true){
String newState = status.IsReachableReturnString(address);
if (newState.equals(currentState)){
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println("Nothing has changed, Time is " + timeStamp );
} else {
//statusFrame.setVisible(false);
statusFrame.dispose();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
System.out.println("Building a new frame, Time is " + timeStamp);
currentState = newState;
statusFrame = DisplayStatus.buildFrame(address, currentState);
}
}
}
}
HostStatus.java
package org.rockislandschools;
import java.io.IOException;
import java.net.InetAddress;
public class HostStatus {
public String IsReachableReturnString(String ip){
String canBeReachedReturnString = "Down";
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReachedReturnString = "Up";
} catch (IOException e) {
e.printStackTrace();
}
return canBeReachedReturnString;
}
public boolean IsReachable(String ip){
boolean canBeReached = false;
int timeout = 10000;
try {
if (InetAddress.getByName(ip).isReachable(timeout)) canBeReached = true;
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println(canBeReached);
return canBeReached;
}
}
DisplayStatus.java
package org.rockislandschools;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DisplayStatus {
public static JFrame buildFrame(String ipAdd, String status){
JFrame frame = new JFrame("Host Status");
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
JPanel panel = new JPanel();
JLabel ipLabel = new JLabel(ipAdd);
ipLabel.setOpaque(true);
ipLabel.setBackground(Color.white);
ipLabel.setPreferredSize(new Dimension(20, 25));
JLabel stateLabel = new JLabel(status);
stateLabel.setOpaque(true);
if (status.equals("Up")){
stateLabel.setBackground(Color.GREEN);
}
if (status.equals("Down")){
stateLabel.setBackground(Color.red);
}
stateLabel.setPreferredSize(new Dimension(20, 25));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400,400));
frame.getContentPane().add(panel);
frame.getContentPane().add(ipLabel, BorderLayout.CENTER);
frame.getContentPane().add(stateLabel, BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setVisible(true);
return frame;
}
public static void editFrame(JFrame frame,String status,String ipAdd){
frame.setContentPane(new JPanel());
JPanel panel = new JPanel();
JLabel ipLabel = new JLabel(ipAdd);
ipLabel.setOpaque(true);
ipLabel.setBackground(Color.white);
ipLabel.setPreferredSize(new Dimension(20, 25));
JLabel stateLabel = new JLabel(status);
stateLabel.setOpaque(true);
if (status.equals("Up")){
stateLabel.setBackground(Color.GREEN);
}
if (status.equals("Down")){
stateLabel.setBackground(Color.red);
}
stateLabel.setPreferredSize(new Dimension(20, 25));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(400,400));
frame.getContentPane().add(panel);
frame.getContentPane().add(ipLabel, BorderLayout.CENTER);
frame.getContentPane().add(stateLabel, BorderLayout.AFTER_LAST_LINE);
}
}
Good luck with your host status program!

Related

How can I fill the Jtable with a complex json

I have this api:
https://api.openweathermap.org/data/2.5/weather?q=paris&appid=460b3f2acf469e5a496d8c019a2b364a&units=metric
I need to fill the JTable with the data in this API.
So I created the class (one of the classes im json in my api on the link:
package dataWeather;
public class Main {
private float temp;
private float pressure;
private float humidity;
private float temp_min;
private float temp_max;
// Getter Methods
public float getTemp() {
return temp;
}
public float getPressure() {
return pressure;
}
public float getHumidity() {
return humidity;
}
public float getTemp_min() {
return temp_min;
}
public float getTemp_max() {
return temp_max;
}
// Setter Methods
public void setTemp(float temp) {
this.temp = temp;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
public void setHumidity(float humidity) {
this.humidity = humidity;
}
public void setTemp_min(float temp_min) {
this.temp_min = temp_min;
}
public void setTemp_max(float temp_max) {
this.temp_max = temp_max;
}
}
And a table model:
package dataWeather;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class MainWeatherTableModel extends AbstractTableModel{
private List<Main> mainWeatherData = new ArrayList<Main>();
private String[] columnNames = {"temp", "pressure", "humidiry", "temp_min", "temp_max"};
public MainWeatherTableModel(List<Main> mainWeatherData)
{
this.mainWeatherData = mainWeatherData;
}
#Override
public String getColumnName(int column)
{
return columnNames[column];
}
#Override
public int getRowCount() {
return mainWeatherData.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object mainElementAttribute = null;
Main mainObject = mainWeatherData.get(rowIndex);
switch(columnIndex)
{
case 0: mainElementAttribute = mainObject.getTemp();break;
case 1: mainElementAttribute = mainObject.getPressure(); break;
case 2: mainElementAttribute = mainObject.getHumidity(); break;
case 3: mainElementAttribute = mainObject.getTemp_min(); break;
case 5: mainElementAttribute = mainObject.getTemp_max(); break;
default: break;
}
return mainElementAttribute;
}
}
And this is my MainFrame code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.border.Border;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import dataWeather.Main;
import dataWeather.MainWeatherTableModel;
public class MainFrame extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel leftPanel = new JPanel();
private JPanel rightPanel = new JPanel();
private JPanel downPanel = new JPanel();
private JPanel centralPanel = new JPanel();
private JPanel weatherPanel = new JPanel();
private JMenuBar menuBar;
private JFileChooser fileChooser;
JScrollPane scrollPane = new JScrollPane();
private JTabbedPane tabbedPane = new JTabbedPane();
private JLabel imageBox = new JLabel();
private JLabel imageBox2 = new JLabel();
private JList<AppImage> imageList;
private MainWeatherTableModel mainModel;
private ObjectMapper objectMapper = new ObjectMapper();
private JTable mainTable;
private JButton buttonGo = new JButton("GO!");
private JTextArea downTextArea = new JTextArea();
public MainFrame () {
super("AppTask");
setLayout(new BorderLayout());
setMinimumSize(new Dimension(500, 400));
setSize(600, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
addLeftPanel();
addRightPanel();
addDownPanel();
addCentralPanel();
addWeatherPanel();
menuBar = createMenuBar();
setJMenuBar(menuBar);
tabbedPane.addTab("Image", centralPanel);
tabbedPane.addTab("Weather", weatherPanel);
add(tabbedPane);
buttonGo.setAction(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
OnGoButtonClick(e);
}
});
buttonGo.setText("GOO");
downPanel.add(buttonGo);
downPanel.add(downTextArea);
}
void OnGoButtonClick(ActionEvent e) {
try
{
URL chosenUrl = new URL(imageList.getSelectedValue().getUrl());
HttpURLConnection connection = (HttpURLConnection)chosenUrl.openConnection();
connection.setRequestMethod("GET");
Integer responseCode = connection.getResponseCode();
downTextArea.append("Response: " + responseCode.toString());
String chosenUrlString = imageList.getSelectedValue().getUrl();
setImageUrl(chosenUrlString, imageBox);
}
catch (MalformedURLException ex) {
System.out.println("Malformed URL");
} catch (IOException iox) {
System.out.println("Can not load file");
}
}
public void addLeftPanel()
{
Dimension dim = getPreferredSize();
dim.width = 300;
leftPanel.setPreferredSize(dim);
Border innerBorder = BorderFactory.createTitledBorder("Choose an Image");
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
leftPanel.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
add(leftPanel, BorderLayout.WEST);
imageList = new JList<>();
ArrayList<AppImage> images = new DataModel().getImages();
DefaultListModel<AppImage> imageListModel = new DefaultListModel<>();
for( AppImage item: images) {
imageListModel.addElement(item);
}
imageList.setModel(imageListModel);
imageList.setPreferredSize(new Dimension(110, 74));
imageList.setBorder(BorderFactory.createEtchedBorder());
imageList.setSelectedIndex(0);
leftPanel.setLayout(new BorderLayout());
leftPanel.add(imageList, BorderLayout.CENTER);
}
public void addRightPanel()
{
Dimension dim = getPreferredSize();
dim.width = 300;
rightPanel.setPreferredSize(dim);
Border innerBorder = BorderFactory.createTitledBorder("");
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
rightPanel.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
add(rightPanel, BorderLayout.EAST);
}
public void addDownPanel() {
Dimension dim = getPreferredSize();
dim.height = 100;
downPanel.setPreferredSize(dim);
Border innerBorder = BorderFactory.createEtchedBorder();
Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
downPanel.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
downPanel.setLayout(new GridLayout(1, 4, 40, 0));
add(downPanel, BorderLayout.SOUTH);
}
public void addMainTable() {
URL url = null;
Main mainWeather = null;
try {
url = new URL("https://api.openweathermap.org/data/2.5/weather?q=paris&appid=460b3f2acf469e5a496d8c019a2b364a&units=metric");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mainWeather = objectMapper.readValue(url, Main.class);
System.out.println(mainWeather.getHumidity());
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<Main> listMainWeather = new ArrayList<>();
listMainWeather.add(mainWeather);
mainModel = new MainWeatherTableModel(listMainWeather);
mainTable = new JTable(mainModel);
weatherPanel.add(mainTable);
}
public void addWeatherPanel()
{
weatherPanel.setLayout(new FlowLayout());
addMainTable();
}
public void addCentralPanel()
{
String imageUrl = "https://thumbs.dreamstime.com/z/welcome-to-summer-concept-written-sand-47585464.jpg";
setImageUrl(imageUrl, imageBox);
centralPanel.add(imageBox, BorderLayout.CENTER);
getContentPane().add(centralPanel, BorderLayout.CENTER);
pack();
}
private void setImageUrl(String imageUrl, JLabel imageBox) {
BufferedImage image = null;
URL url = null;
try {
url = new URL(imageUrl);
image = ImageIO.read(url);
} catch (MalformedURLException ex) {
System.out.println("Malformed URL");
} catch (IOException iox) {
System.out.println("Can not load file");
}
imageBox.setIcon(new ImageIcon(image));
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu windowMenu = new JMenu("Window");
JMenu fileMenu = new JMenu("File");
JMenuItem exportDataItem = new JMenuItem("Export Data...");
JMenuItem importDataItem = new JMenuItem("Import Data...");
JMenuItem exitItem = new JMenuItem("Exit");
menuBar.add(fileMenu);
menuBar.add(windowMenu);
fileMenu.add(importDataItem);
fileMenu.add(exportDataItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
JMenu showMenu = new JMenu("Show");
fileMenu.setMnemonic(KeyEvent.VK_F); //Alt+F opens the fileMenu
exitItem.setMnemonic(KeyEvent.VK_X);
exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));
exitItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int action = JOptionPane.showConfirmDialog(MainFrame.this, "Do you really want to exit from application?",
"Confirm Exit", JOptionPane.OK_CANCEL_OPTION);
if (action == JOptionPane.OK_OPTION)
{
System.exit(0);
}
}
});
exportDataItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(fileChooser.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) //MainFrame.this its a parent component
{
System.out.println(fileChooser.getSelectedFile());
}
}
});
importDataItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(fileChooser.showOpenDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) //MainFrame.this its a parent component
{
System.out.println(fileChooser.getSelectedFile());
}
}
});
return menuBar;
}
}
I cant see what I'm doing wrong... Please help, dealing with it hours and can't make it work...
I'm very newbie in swing java, trying to understand what I have to do.
By default Swing components don't have a size/location.
It is the job of the layout manger to give components a size/location based on the rules of the layout manager.
The layout manager is invoked whenever you pack() a frame of use setVisible(true) on the frame.
You are making your frame visible BEFORE you add components to the frame, so I'm guessing your components still have a size of (0, 0) so there is nothing to paint.
Typically your would use:
panel.revalidate();
panel.repaint();
after you add components to a visible panel.
But in your case you appear to be creating all the panels after you make the frame visible so I think you just need to add
revalidate();
repaint();
at the end of your constructor.
weatherPanel.add(mainTable);
Also you need to display a JTable in a JScrollPane in order to see the table headers so the code should be:
//weatherPanel.add(mainTable);
JScrollPane scrollPane = new JScrollPane(mainTable);
weatherPanel.add( scrollPane );
I also question why you need the panel. You can add any component directly to a tabbed pane.

Why can't I retrieve my buttons when I run my program?

So, my program is a user adding buttons during runtime. When he/she clicks on the 'save' button the program is saved to a file. But when I run it again, the buttons are gone. I tried to serialize my buttons using XMLEncoder and XMLDecoder, but when I ran my program, it didn't save anything, it started all over again. How would I serialize this correctly so that when I start my program, the buttons are there? Any help would be appreciated.
Here is a snippet of my code:
public class saveButton
{
//JFrame and JPanels have been declared earlier
class ClickListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
str = JOptionPane.showInputDialog("What is the name of the new button?");
JButton b = new JButton(str);
frame.add(b);
try
{
XMLEncoder encdr = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("file.ser")));
encdr.writeObject(new JButton(str));
encdr.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
ActionListener addButtonClicked = new ClickListener();
b.addActionListener(addButtonClicked);
class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent f)
{
try
{
XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("file.ser")));
Object result = d.readObject();
d.close();
}
catch (IOException decoder)
{
decoder.printStackTrace();
}
}
}
Once you decode the object, you need to cast the object appropriately and then add the component to the container.
This is pretty basic example which generates a random number of buttons on a panel each time you click the Random button. When you click Save, the panel is saved to disk and when you click Load, it loads the panel from disk and reapplies it the container
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private RandomButtonPane pane;
public TestPane() {
setLayout(new BorderLayout());
JPanel actions = new JPanel();
JButton random = new JButton("Random");
JButton save = new JButton("Save");
JButton load = new JButton("Load");
actions.add(random);
actions.add(save);
actions.add(load);
add(actions, BorderLayout.SOUTH);
random.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
}
pane = new RandomButtonPane();
pane.randomise();
add(pane);
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
try (OutputStream os = new FileOutputStream(new File("Save.dat"))) {
try (XMLEncoder encoder = new XMLEncoder(os)) {
encoder.writeObject(pane);
remove(pane);
pane = null;
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
});
load.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (pane != null) {
remove(pane);
pane = null;
}
try (InputStream is = new FileInputStream(new File("Save.dat"))) {
try (XMLDecoder decoder = new XMLDecoder(is)) {
Object value = decoder.readObject();
if (value instanceof RandomButtonPane) {
pane = (RandomButtonPane)value;
pane.revalidate();
add(pane);
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
Window window = SwingUtilities.windowForComponent(TestPane.this);
window.pack();
window.setLocationRelativeTo(null);
}
});
}
}
public static class RandomButtonPane extends JPanel {
public RandomButtonPane() {
setLayout(new GridBagLayout());
}
public void randomise() {
int count = ((int) (Math.random() * 100)) + 1;
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < count; index++) {
if (index % 10 == 0) {
gbc.gridx = 0;
gbc.gridy++;
}
add(new JButton(Integer.toString(index)), gbc);
gbc.gridx++;
}
}
}
}

Why JFrame Background Image is not Working?

I am trying to Show a background Image but it will not work, i have tried multiple things it comes back with this error ever time. Every time it says Duplicate field i don't know what that means I am a beginner in java
Here is the Error
Exception in thread "main" java.lang.ClassFormatError: Duplicate field name&signature in class file search/text/file/SearchTextFile$1
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at search.text.file.SearchTextFile.<init>(SearchTextFile.java:46)
at search.text.file.SearchTextFile.main(SearchTextFile.java:42)
Java Result: 1
And this try block causing background error :
try {
BufferedImage img = ImageIO.read(new File("bible.jpg"));
} catch(IOException e ) {
}
Thank You
Java Code:
package search.text.file;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class SearchTextFile {
public static void main(String[] args) {
new SearchTextFile();
}
public SearchTextFile() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Bible Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
try {
BufferedImage img = ImageIO.read(new File("bible.jpg"));
} catch(IOException e ) {
}
});
}
public class TestPane extends JPanel {
private JTextField findText;
private JButton search;
private DefaultListModel<String> model;
private JList list;
private String searchPhrase;
public TestPane() {
setLayout(new BorderLayout());
JPanel searchPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
searchPane.add(new JLabel("Find: "), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
findText = new JTextField(20);
searchPane.add(findText, gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search = new JButton("Search");
searchPane.add(search, gbc);
add(searchPane, BorderLayout.NORTH);
model = new DefaultListModel<>();
list = new JList(model);
list.setCellRenderer(new HighlightListCellRenderer());
add(new JScrollPane(list));
ActionHandler handler = new ActionHandler();
search.addActionListener(handler);
findText.addActionListener(handler);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("bible.txt")))) {
String text = null;
while ((text = reader.readLine()) != null) {
model.addElement(text);
}
} catch (IOException exp) {
exp.printStackTrace();
}
}
public class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
searchPhrase = findText.getText();
if (searchPhrase != null && searchPhrase.trim().length() == 0) {
searchPhrase = null;
}
list.repaint();
// model.removeAllElements();
//// BufferedReader reader = null;
//
// String searchText = findText.getText();
// try (BufferedReader reader = new BufferedReader(new FileReader(new File("bible.txt")))) {
//
// String text = null;
// while ((text = reader.readLine()) != null) {
//
// if (text.contains(searchText)) {
//
// model.addElement(text);
//
// }
//
// }
//
// } catch (IOException exp) {
//
// exp.printStackTrace();
// JOptionPane.showMessageDialog(TestPane.this, "Something Went Wrong", "Error", JOptionPane.ERROR_MESSAGE);
//
// }
}
}
public class HighlightListCellRenderer extends DefaultListCellRenderer {
public final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))";
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof String && searchPhrase != null) {
String text = (String) value;
if (text.contains(searchPhrase)) {
text = text.replace(" ", " ");
value = "<html>" + text.replace(searchPhrase, "<span STYLE='background-color: #ffff00'>" + searchPhrase + "</span>") + "</html>";
}
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
}
}
}
}
Your try block:
try {
BufferedImage img = ImageIO.read(new File("bible.jpg"));
} catch(IOException e ) {
}
});
is outside of any method or constructor, and this is not allowed. I suggest that you
move it to within a constructor or method.
Don't ignore the exceptions as you're doing as this is very dangerous coding. At least print out the exception's stack trace.
Also, why are you reading in an image but then doing nothing with it?
e.g.
public class SearchTextFile2 {
private static void createAndShowGui() {
BufferedImage img = null;
try {
// better to get as a resource and not as a File
img = ImageIO.read(new File("bible.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("SearchTextFile2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestPane(img)); // pass image into TestPane
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
// make TestPane a static inner class
// have TestPane display image within its paintComponent method
public static class TestPane extends JPanel {
private JTextField findText;
private JButton search;
private DefaultListModel<String> model;
private JList list;
private BufferedImage img;
private String searchPhrase;
public TestPane(BufferedImage img) {
setLayout(new BorderLayout());
this.img = img;
// etc.....
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
}
// .....
looks like all classes you placed in one file might be that would be messed in your case
please check java docs for error
Java Virtual Machine attempts to read a class file and determines that
the file is malformed or otherwise cannot be interpreted as a class
file
http://docs.oracle.com/javase/7/docs/api/java/lang/ClassFormatError.html

While searching directory, only first instance of specified file name is shown

I am attempting to search a directory chosen by the user for any and all files. There is an option to search for a specific string of characters and have only file names with instances of these characters appear on the screen. When I run this program, however, no text (except the default specified by using JTextArea constructor) appears on the screen. If possible, I would truly appreciate it if someone helps me debug.
package comp.search.direct;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
#SuppressWarnings("serial")
public class SearchInitializer extends JFrame implements ActionListener {
public static JButton button;
public static JTextArea ta;
public static JTextField tf;
public static JPanel pane, pane2, pane3;
public static JLabel label;
public static JCheckBox jcb;
#SuppressWarnings({ "unchecked", "rawtypes" })
public static ArrayList<String> filenames = new ArrayList();
#SuppressWarnings("unused")
public static void main(String[] args) {
SearchInitializer sci = new SearchInitializer();
}
public SearchInitializer() {
super("Search Directory");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
this.setLayout(new BorderLayout());
pane = new JPanel();
pane.setLayout(new BorderLayout());
button = new JButton("Search Directory");
ta = new JTextArea("File Names:");
ta.setEditable(false);
tf = new JTextField(10);
label = new JLabel("Find:");
jcb = new JCheckBox("Append Text");
pane2 = new JPanel();
pane2.add(label);
pane2.add(tf);
pane3 = new JPanel();
pane3.add(button);
pane3.add(jcb);
pane.add(pane3, BorderLayout.CENTER);
pane.add(pane2, BorderLayout.EAST);
addActionListeners();
getContentPane().add(pane, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(ta), BorderLayout.CENTER);
this.setResizable(true);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
}
public static void searchDirectory(File folder, JTextField find, JTextArea ta, ArrayList<String> arg) {
arg.clear();
for (File fileentry : folder.listFiles()) {
if (find.getText() == null) {
if (fileentry.isDirectory()) {
searchDirectory(fileentry, find, ta, arg);
} else {
if (!fileentry.getName().endsWith(".lnk"))
ta.append("\n" + fileentry.getName());
}
} else {
if (fileentry.isDirectory()) {
searchDirectory(fileentry, find, ta, arg);
} else {
if (!fileentry.getName().contains(find.getText()))
return;
else {
if (arg.contains(fileentry.getName())) {
ta.append("\n" + fileentry.getName());
arg.add(fileentry.getName());
searchDirectory(folder, find, ta, arg);
System.out.println(fileentry.getName()); // Testing purposes only
} else {
return;
}
}
}
}
}
}
public void addActionListeners() {
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fc.showDialog(SearchInitializer.this, "Select") == JFileChooser.APPROVE_OPTION) {
searchDirectory(new File(fc.getSelectedFile().getAbsolutePath()), tf, ta, filenames);
}
}
}
}
The error is probably here:
if (arg.contains(fileentry.getName())) {
ta.append("\n" + fileentry.getName());
arg.add(fileentry.getName());
searchDirectory(folder, find, ta, arg);
System.out.println(fileentry.getName()); // Testing purposes only
} else {
return;
}
You're telling it to add an entry to the ArrayList only if it's already there. Because of this logic, there's no way your ArrayList will ever be anything other than empty.

Java JCheckBox ActionListener

I have a program that is a list of notes that can be added by the user. Every note is loaded through a for loop and given a JCheckBox on runtime from the notes.txt. How do I add an actionlistener for my JCheckBoxes when they are only instance based and not permanent code?
(e.g. they don't have their own variable names?)
I need to update notes.txt with a 0 or a 1 based on if the JCheckBox is checked or not. Here is my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SideNotes {
public static JPanel panel = new JPanel();
private static JButton add = new JButton("Add note");
JCheckBox[] notes;
public SideNotes() {
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
loadNotes();
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
addNote();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
public void addNote() throws IOException {
String note = JOptionPane.showInputDialog("Enter note: ", null);
JCheckBox jcb = new JCheckBox(note, false);
panel.add(jcb);
panel.revalidate();
panel.repaint();
File file = new File("notes.txt");
FileWriter writer = new FileWriter(file, true);
BufferedWriter brw = new BufferedWriter(writer);
brw.write(note);
brw.newLine();
brw.close();
}
private void loadNotes() {
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
BufferedReader reader = new BufferedReader(new FileReader(
"notes.txt"));
int lines = 0;
while (reader.readLine() != null)
lines++;
reader.close();
notes = new JCheckBox[lines];
for (int i = 0; i < notes.length; i++) {
String note = br.readLine();
int checked = note.charAt(note.length() - 1);
System.out.println(checked);
if (checked == 49) {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, true);
} else {
note = note.substring(0, note.length() - 1);
notes[i] = new JCheckBox(note, false);
}
panel.add(notes[i]);
panel.revalidate();
panel.repaint();
}
br.close();
} catch (Exception e1) {
}
} else {
System.out.println("File does not exist");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200, 400);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(add);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new SideNotes();
}
}
Create a generic ActionListener outside the loop where you create the checkboxes:
ActionListener al = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JCheckBox checkbox = (JCheckBox)e.getSource();
// do something with the checkbox
}
}
Then after you create the checkbox you add the ActionListener to the checkbox
notes[i].addActionListener(al);
panel.add(notes[i]);

Categories

Resources