Why JFrame Background Image is not Working? - java

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

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++;
}
}
}
}

JScrollPane shrink/collapse on window minimize

I have a JScrollPane which contains a JTextArea. When the window is minimized and then restored, the JScrollPane will then collapse on itself. Note that this squish only happens if the text in the JTextArea exceeds the given width and/or height of the JTextArea (i.e., the horizontal or vertical scrollbars appear).
This question here: JScrollpane loses size after minimize poses the same problem, but the issue is never addressed, other than to add weightx, weighty, and fill constraints to the JScrollPane, which I already had to begin with.
Below is a simplified example that demonstrates the problem. How can I get the JScrollPane to sustain its size after the window is minimized and restored?
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.border.EtchedBorder;
public class GUITest implements ActionListener {
JButton button = new JButton("Button");
JTextArea textArea = new JTextArea();
SwingWorker<String, String> mySwingWorker = null;
public static void main(String[] args) throws IOException {
GUITest tracer = new GUITest();
}
public GUITest() throws IOException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGUI();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public void createAndShowGUI() throws IOException {
JFrame frame = new JFrame("GUI Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints mainPanelConstraints = new GridBagConstraints();
mainPanelConstraints.gridx = 0;
mainPanelConstraints.gridy = 0;
mainPanelConstraints.fill = GridBagConstraints.BOTH;
button.addActionListener(this);
mainPanel.add(button, mainPanelConstraints);
mainPanelConstraints.gridx = 0;
mainPanelConstraints.gridy = 1;
mainPanelConstraints.fill = GridBagConstraints.BOTH;
mainPanel.add(buildTextAreaPanel(), mainPanelConstraints);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
private JPanel buildTextAreaPanel() {
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new GridBagLayout());
GridBagConstraints textAreaPanelConstraints = new GridBagConstraints();
textAreaPanel.setBorder(BorderFactory.createTitledBorder(new EtchedBorder(EtchedBorder.RAISED), "TextArea"));
textArea.setColumns(30);
textArea.setRows(15);
textArea.setEditable(false);
JScrollPane textAreaScrollPane = new JScrollPane(textArea);
textAreaScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textAreaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
textAreaPanelConstraints.gridx = 0;
textAreaPanelConstraints.gridy = 0;
textAreaPanelConstraints.weightx = 1.0;
textAreaPanelConstraints.weighty = 1.0;
textAreaPanelConstraints.fill = GridBagConstraints.BOTH;
textAreaPanel.add(textAreaScrollPane, textAreaPanelConstraints);
return textAreaPanel;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
mySwingWorker = new MySwingWorker();
mySwingWorker.execute();
}
}
private class MySwingWorker extends SwingWorker<String, String> {
public String doInBackground() throws Exception {
for (int i = 0; i < textArea.getRows(); i++) {
publish("text\n");
}
publish("more text\n");
return "Done.";
}
public void process(List<String> chunks) {
for (String msg : chunks) {
textArea.append(msg);
}
}
public void done() {
try {
String msg = get();
textArea.append("\n" + msg);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
You need to set the weightx and weighty in both layouts. In createAndShowGui, set mainPanelConstraints.weightx and mainPanelConstraints.weighty to 1 before adding the text area panel.
Set the layout of the parent Container (the content pane) to FlowLayout
...
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(mainPanel);
...
I solved the shrinkage problem in this particular code example by removing all GridBagLayouts and replacing them with BorderLayouts. I have no idea why a JScrollPane reacts the way you discovered when using a GridBagLayout.
I felt real uncomfortable starting the Event Dispatch thread from the class constructor. I moved the SwingUtilities invokeLater into the main method.
Anyway, here's the code.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.border.EtchedBorder;
public class JScrollPaneTest implements ActionListener {
JButton button = new JButton("Button");
JTextArea textArea = new JTextArea();
SwingWorker<String, String> mySwingWorker = null;
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new JScrollPaneTest().createAndShowGUI();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public JScrollPaneTest() throws IOException {
}
public void createAndShowGUI() throws IOException {
JFrame frame = new JFrame("JScrollPane Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(button, BorderLayout.NORTH);
mainPanel.add(buildTextAreaPanel(), BorderLayout.CENTER);
button.addActionListener(this);
frame.add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private JPanel buildTextAreaPanel() {
JPanel textAreaPanel = new JPanel();
textAreaPanel.setLayout(new BorderLayout());
textAreaPanel.setBorder(BorderFactory.createTitledBorder(
new EtchedBorder(EtchedBorder.RAISED), "TextArea"));
textArea.setColumns(30);
textArea.setRows(15);
textArea.setEditable(false);
JScrollPane textAreaScrollPane = new JScrollPane(textArea);
textAreaPanel.add(textAreaScrollPane, BorderLayout.CENTER);
return textAreaPanel;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
mySwingWorker = new MySwingWorker();
mySwingWorker.execute();
}
}
private class MySwingWorker extends SwingWorker<String, String> {
public String doInBackground() throws Exception {
for (int i = 0; i < textArea.getRows(); i++) {
publish("text\n");
}
publish("more text\n");
return "Done.";
}
public void process(List<String> chunks) {
for (String msg : chunks) {
textArea.append(msg);
}
}
public void done() {
try {
String msg = get();
textArea.append("\n" + msg);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}

Drag and Drop from JButton to JComponent in Java

I searched on the internet for examples how to Drag and Drop JButtons to an Object but I could not make it work.
What my program does, is that when I click on a button, the object updated a field (with a selectedobject.setField()). I want to be able to do this not by clicking, but by dragging the JButton.
How can I do this ?
I found this, and I tried to put in my code:
btn.setTransferHandler(new ImageHandler());
btn.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent)e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
});
I took the ImageHandler class from here.
Drag'n'drop is a fun bag of crunchy, munchy carrots...not helped by the fact that there is a "core" API and the newer "transfer" API, so it's really easy to get confused
The following example uses the "transfer" API and basically transfers a String value from a button to a JLabel.
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
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 {
public TestPane() {
setLayout(new GridLayout(1, 2));
add(createLeftPanel());
add(createRightPanel());
}
protected JPanel createLeftPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
for (int index = 0; index < 10; index++) {
JButton btn = new JButton(Integer.toString(index + 1));
panel.add(btn, gbc);
btn.setTransferHandler(new ValueExportTransferHandler(Integer.toString(index + 1)));
btn.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
JButton button = (JButton) e.getSource();
TransferHandler handle = button.getTransferHandler();
handle.exportAsDrag(button, e, TransferHandler.COPY);
}
});
}
return panel;
}
protected JPanel createRightPanel() {
JPanel panel = new JPanel(new GridBagLayout());
JLabel label = new JLabel("Drop in");
label.setBorder(new CompoundBorder(new LineBorder(Color.DARK_GRAY), new EmptyBorder(20, 20, 20, 20)));
label.setTransferHandler(new ValueImportTransferHandler());
panel.add(label);
return panel;
}
}
public static class ValueExportTransferHandler extends TransferHandler {
public static final DataFlavor SUPPORTED_DATE_FLAVOR = DataFlavor.stringFlavor;
private String value;
public ValueExportTransferHandler(String value) {
this.value = value;
}
public String getValue() {
return value;
}
#Override
public int getSourceActions(JComponent c) {
return DnDConstants.ACTION_COPY_OR_MOVE;
}
#Override
protected Transferable createTransferable(JComponent c) {
Transferable t = new StringSelection(getValue());
return t;
}
#Override
protected void exportDone(JComponent source, Transferable data, int action) {
super.exportDone(source, data, action);
// Decide what to do after the drop has been accepted
}
}
public static class ValueImportTransferHandler extends TransferHandler {
public static final DataFlavor SUPPORTED_DATE_FLAVOR = DataFlavor.stringFlavor;
public ValueImportTransferHandler() {
}
#Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(SUPPORTED_DATE_FLAVOR);
}
#Override
public boolean importData(TransferHandler.TransferSupport support) {
boolean accept = false;
if (canImport(support)) {
try {
Transferable t = support.getTransferable();
Object value = t.getTransferData(SUPPORTED_DATE_FLAVOR);
if (value instanceof String) {
Component component = support.getComponent();
if (component instanceof JLabel) {
((JLabel) component).setText(value.toString());
accept = true;
}
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
return accept;
}
}
}
I've gone out my way to separate the TransferHandlers allowing for a "drag" and "drop" version. You don't "have" to do this and you "could" use a single TransferHandler to perform both operations, that's up to you.
You will have to modify the ValueExportTransferHandler to accept different values and modify the SUPPORTED_DATE_FLAVOR accordingingly, but those are the basics
You could also have a look at Drag and Drop custom object from JList into JLabel as another example...

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.

Categories

Resources