Correct way to serialize a JPanel? - serialization

I am sending my class which extends JPanel through an ObjectOutputStream to the client, so that their GUI will 'load'.
public class ClickOptionPanel extends JPanel implements Serializable {
private Font font = new Font("Arial", Font.BOLD, 13);
private JLabel clickerTitle;
private JSlider clickerMaxSlider, clickerMinSlider;
private JTextField clickerMinField, clickerMaxField;
private JCheckBox clickInsideMinecraft, autoBlock;
public ClickOptionPanel() {
setLayout(new BorderLayout());
add(getClickerTitlePanel(), BorderLayout.NORTH);
add(getClickerSliderPanel(), BorderLayout.CENTER);
add(getCheckBoxPanel(), BorderLayout.SOUTH);
}
private JPanel getClickerTitlePanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEtchedBorder());
clickerTitle = new JLabel("Clicker Options");
clickerTitle.setFont(font);
panel.add(clickerTitle);
return panel;
}
private JPanel getClickerSliderPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
clickerMaxSlider = new JSlider(0, 200, 125);
clickerMaxSlider.setPreferredSize(new Dimension(300, 45));
clickerMinSlider = new JSlider(0, 200, 75);
clickerMinSlider.setPreferredSize(new Dimension(300, 45));
panel.add(clickerMaxSlider, BorderLayout.NORTH);
panel.add(clickerMinSlider, BorderLayout.CENTER);
panel.add(getClickFieldPanel(), BorderLayout.SOUTH);
return panel;
}
private JPanel getClickFieldPanel() {
JPanel panel = new JPanel();
clickerMaxField = new JTextField(10);
clickerMaxField.setFont(font);
clickerMaxField.setHorizontalAlignment(SwingConstants.CENTER);
clickerMinField = new JTextField(10);
clickerMinField.setFont(font);
clickerMinField.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(clickerMinField);
panel.add(clickerMaxField);
return panel;
}
private JPanel getCheckBoxPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(BorderFactory.createEtchedBorder());
clickInsideMinecraft = new JCheckBox("Only click inside of Minecraft: ");
clickInsideMinecraft.setHorizontalTextPosition(SwingConstants.LEFT);
autoBlock = new JCheckBox("Enable auto-block: ");
autoBlock.setHorizontalTextPosition(SwingConstants.LEFT);
panel.add(clickInsideMinecraft, BorderLayout.NORTH);
panel.add(autoBlock, BorderLayout.SOUTH);
return panel;
}
There is the JPanel which I am sending. I create a new instance of it before it is sent.
The JPanel is turning up blank - why is this?

I was doing everything right - it was just that on the client side I forgot to set the ois.readObject object to the panel!

Related

Implementing a Launcher Framework - disabled Apply button on dialog

I am working on a eclipse plugin and implementing a custom launcher as per the link https://eclipse.org/articles/Article-Launch-Framework/launch.html .
I have implemented a class BrowsersTab which extends AbstractLaunchConfigurationTab and implemented all the methods. The problem is that when I call the updateLaunchConfigurationDialog(); on the selection event , the 'Apply' Button remains disabled.
Code :
public class BrowsersTab extends AbstractLaunchConfigurationTab {
private Button chrome;
private Button firefox;
private Button safari;
private Button ie;
private Button opera;
private Button android;
private Button ios;
#Override
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
GridLayout topLayout = new GridLayout();
comp.setLayout(topLayout);
Group fGroup = new Group(comp, SWT.NONE);
fGroup.setFont(parent.getFont());
fGroup.setLayout(new GridLayout(2, true));
fGroup.setText(DialogMessages.browserSelection);
chrome = new Button(fGroup, SWT.CHECK);
chrome.setText("Google Chrome");
chrome.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
System.out.println("chrome selected");
updateLaunchConfigurationDialog();
}
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
Image chromeIcon= getBrowserIcon("chrome-browser-24X24.png");
if(null!=chromeIcon)
chrome.setImage(chromeIcon);
Combo comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
firefox = new Button(fGroup, SWT.CHECK);
firefox.setText("Mozilla Firefox");
Image firefoxIcon= getBrowserIcon("Firefox-icon.png");
if(null!=firefoxIcon)
firefox.setImage(firefoxIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
safari = new Button(fGroup, SWT.CHECK);
safari.setText("Apple Safari");
Image safariIcon= getBrowserIcon("Safari-icon.png");
if(null!=safariIcon)
safari.setImage(safariIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ie = new Button(fGroup, SWT.CHECK);
ie.setText("Internet Explorer");
Image ieIcon= getBrowserIcon("Internet-Explorer-icon.png");
if(null!=ieIcon)
ie.setImage(ieIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
opera= new Button(fGroup, SWT.CHECK);
opera.setText("Opera");
Image operaIcon= getBrowserIcon("browser-opera-icon.png");
if(null!=operaIcon)
opera.setImage(operaIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
android= new Button(fGroup, SWT.CHECK);
android.setText("Android");
Image androidIcon= getBrowserIcon("android-platform-icon.png");
if(null!=androidIcon)
android.setImage(androidIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
ios= new Button(fGroup, SWT.CHECK);
ios.setText("Mobile Safari");
Image iosIcon= getBrowserIcon("Apple-grey-icon.png");
if(null!=iosIcon)
ios.setImage(iosIcon);
comboDropDown = new Combo(fGroup, SWT.DROP_DOWN | SWT.BORDER);
comboDropDown.setText("Version");
}
#Override
public String getName() {
return "Browsers";
}
public Image getBrowserIcon(String name){
Image icon=null;
try {
icon = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/"+name).createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return icon;
}
public Image getImage() {
Image tab=null;
try {
tab = AbstractUIPlugin.imageDescriptorFromPlugin("SuitACore","icons/browser.png").createImage();
} catch (Exception e) {
// Swallow it; we'll do without images
}
return tab;
}
public void initializeFrom(ILaunchConfiguration configuration) {
try {
List<String> browsersDefaults = new ArrayList<String>();
browsersDefaults.add("chrome");
List<String> browsers =configuration.getAttribute("browsers", browsersDefaults);
} catch (CoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
chrome.setSelection(true);
}
public void performApply(ILaunchConfigurationWorkingCopy configuration) {
List<String> browsers = new ArrayList<String>();
browsers.add("chrome");
configuration.setAttribute("browser",browsers );
}
public void setDefaults(ILaunchConfigurationWorkingCopy arg0) {
}
}
You must call updateLaunchConfigurationDialog() whenever anything changes that might update the Apply button - so all checkboxes and combos.
You must also save everything that changes in the ILaunchConfigurationWorkingCopy in the performApply method. The Apply button state is determined by checking that the working copy is different from the original configuration.

saving a text file using JFileChooser

I am writing a small program where are user enters some information into text fields and then has the option to save that information using JFileChooser. I have not been able to figure out how to get it to save. What am I doing wrong? Thank you in advance.
public class Program implements ActionListener{
JMenuItem loadMenuItem, saveMenuItem, quitMenuItem;
JFrame frame;
JPanel mainPanel, inputPanel, listPanel;
JLabel firstNameLabel, lastNameLabel, rentLabel, listLabel;
JTextField firstNameTextField, lastNameTextField, rentTextField;
JButton addButton;
JList list;
DefaultListModel<TenantInfo> listModel;
JScrollPane scrollPane;
public ArrayList<TenantInfo>tenantInfo;
private void saveFile() {
// TODO Auto-generated method stub
JFileChooser jfc = new JFileChooser();
int userSelected = jfc.showSaveDialog(null);
if(userSelected == JFileChooser.APPROVE_OPTION){
try{
FileOutputStream fos = new FileOutputStream(jfc.getSelectedFile());
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(TenantInfo t : tenantInfo){
oos.writeObject(t);
}
oos.writeObject(tenantInfo.get(0));
oos.close();
fos.close();
}catch(Exception ex){
ex.printStackTrace();
}
}

Null pointer Exception using a PrintWriter

I have that inner class shown under. This is for a client/server and I had nullpointer exception at the "println" from an PrintWriter. I have tried all I know to solve it but, unsuccessfully. Anyone can give me a tip or an idea for what I have to do. Thanks guys!
Here's the FULL CLASS code:
public class ChatClient extends JFrame{
private JTextField textToSend;
private Socket socket;
private PrintWriter writer
private String name;
private JTextArea receivedText;
private Scanner reader;
public ChatCliente(String name){
super("Chat: "+ name);
this.name = name;
Font font = new Font("Serif", Font.PLAIN, 20);
textToSend = new JTextField();
textToSend.setFont(font);
JButton btn = new JButton("Send");
btn.setFont(font);
btn.addActionListener(new Listener());
Container content = new JPanel();
content.setLayout(new BorderLayout());
content.add(BorderLayout.CENTER, textToSend);
content.add(BorderLayout.EAST, btn);
receivedText = new JTextArea();
receivedText.setFont(font);
JScrollPane scroll = new JScrollPane(receivedText);
getContentPane().add(BorderLayout.CENTER, scroll);
getContentPane().add(BorderLayout.SOUTH, content);
configureNetwork();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
}
private void configureNetwork(){
try{
socket = new Socket("127.0.0.1",5000);
writer = new PrintWriter(socket.getOutputStream());
reader = new Scanner(socket.getInputStream());
new Thread(new ServerThread()).start();
}catch (Exception e){}
}
private class Listener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
try{
String s = name;
String t = textToSend.getText();
System.out.println(name+" : "+ textToSend.getText());
writer.println(s+" : "+t);
writer.flush();
textToSend.setText("");
textToSend.requestFocus();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
private class ServerThread implements Runnable{
#Override
public void run() {
String text;
try{
while((text = reader.nextLine()) != null){
receivedText.append(text+"\n");
}
}catch(Exception e){}
}
}
}
'name' is not declared.
Maybe you meant:
String s = "name";
Just some stupid thing that happened to me: do not insert "/" in the name of your file, or it will of course look for an extra folder that probably isn't there.
int number = 1, total = 126;
String path = "some/path/found " + number + "/" + total;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));

How can I show JDialog generated with JFormDesigner

I generated a JDialog w/ JFormDesigner, but I don't know how to display it. Here is the code:
public class FinishPopup extends JDialog {
public FinishPopup(Frame owner) {
super(owner);
initComponents();
}
public FinishPopup(Dialog owner) {
super(owner);
initComponents();
}
public void initComponents() {
dialogPane = new JPanel();
contentPanel = new JPanel();
label1 = new JLabel();
label2 = new JLabel();
buttonBar = new JPanel();
okButton = new JButton();
label3 = new JLabel();
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
{
{
label1.setText("Money: ");
label1.setFont(new Font("Tahoma", Font.PLAIN, 12));
label2.setText("Time");
label2.setFont(new Font("Tahoma", Font.PLAIN, 12));
GroupLayout contentPanelLayout = new GroupLayout(contentPanel);
contentPanel.setLayout(contentPanelLayout);
contentPanelLayout.setHorizontalGroup(
contentPanelLayout.createParallelGroup()
.addGroup(contentPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(label2)
.addGap(90, 90, 90)
.addComponent(label1)
.addContainerGap(105, Short.MAX_VALUE))
);
contentPanelLayout.setVerticalGroup(
contentPanelLayout.createParallelGroup()
.addGroup(contentPanelLayout.createSequentialGroup()
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(contentPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(label2)
.addComponent(label1))
.addContainerGap())
);
}
dialogPane.add(contentPanel, BorderLayout.CENTER);
{
buttonBar.setBorder(new EmptyBorder(12, 0, 0, 0));
buttonBar.setLayout(new GridBagLayout());
((GridBagLayout)buttonBar.getLayout()).columnWidths = new int[] {0, 80};
((GridBagLayout)buttonBar.getLayout()).columnWeights = new double[] {1.0, 0.0};
okButton.setText("OK");
buttonBar.add(okButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
dialogPane.add(buttonBar, BorderLayout.SOUTH);
label3.setText("Finished");
label3.setFont(new Font("Tahoma", Font.BOLD, 14));
dialogPane.add(label3, BorderLayout.NORTH);
}
contentPane.add(dialogPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(getOwner());
}
private JPanel dialogPane;
private JPanel contentPanel;
private JLabel label1;
private JLabel label2;
private JPanel buttonBar;
private JButton okButton;
private JLabel label3;
}
How do I create and show it? thanks.
You need to first create an instance of the class and then call setVisible to make it visible
// owner is reference to the parent frame or dialog. May be null, but you'll
// need to cast it
FinishPopup popup = new FinishPopup(owner);
popup.setVisible(true);
You may also find setLocationRelativeTo helpful

Adding numbers to an arraylist from the Jtextfield

I am sure its very simple but this is my first java class. the user enters a number into the input Jtextfield. the Add button is supposed to add that number to the arraylist. I am having trouble figuring out how to do that exactly. Any help you can give me would be awesome
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ArrayExercise extends JFrame
{
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 300;
private JPanel panel1;
private JPanel panel2;
private JLabel messageLabel;
private JTextField input;
private JTextArea output;
private JButton addButton;
private JButton list;
private JButton rlist;
private JButton clear;
public ArrayExercise()
{
setTitle("Array Exercise");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1();
panel2();
add(panel1, BorderLayout.EAST);
add(panel2, BorderLayout.WEST);
setVisible(true);
input.requestFocus();
}
private void panel1()
{
messageLabel = new JLabel("Input");
input = new JTextField(5);
addButton = new JButton("Add");
list = new JButton("List");
rlist = new JButton("R-List");
clear = new JButton("Clear");
addButton.addActionListener(new ButtonListener());
list.addActionListener(new ButtonListener());
rlist.addActionListener(new ButtonListener());
clear.addActionListener(new ButtonListener());
panel1 = new JPanel();
panel1.setLayout(new GridLayout(6,1));
panel1.add(messageLabel);
panel1.add(input);
panel1.add(addButton);
panel1.add(list);
panel1.add(rlist);
panel1.add(clear);
}
private void panel2()
{
output = new JTextArea(12, 10);
panel2 = new JPanel();
panel2.add(output);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String in;
int number;
int index = 0;
ArrayList<String> list = new ArrayList<>();
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Add"))
{
index++;
in = addButton.getText();
list.add(addButton.getText());
if (index == 9)
{
input.setEditable(false);
addButton.setEnabled(false);
}
output.setText(in + " added.");
input.setText(null);
input.requestFocus();
}
if (actionCommand.equals("List"))
{
for(int x = 0; x <= list.size(); x++)
{
output.setText((x+1)+ ". " + list.get(x) + "\n");
}
}
}
}
public static void main(String[] args)
{
new ArrayExercise();
}
}
You have ArrayList list which is not adding any string value to that list and you are trying to run that over loop to get you values. If you are not adding anything to list then how can you extract anything out of it.
ArrayList<String> list = new ArrayList<String>();
For each button attach different actionlistener as all buttons are not supposed to act same way.
To add elements in ArrayList use this
list.add(input.getText()); // adding text entered into input textfield.
Make a list
List item
Make a TextField
Make Button Add Listener to button
Get the text from the text field or text area Add to array list
object
Here is all the work you need to do:
ArrayList<String> arrayObject= new ArrayList<String>();
JButton button = new JButton();
JtextField textBox = new JtextField ();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//inside your action listener:
String add_item_to_array = textBox.getText().trim();
arrayObject.add(add_item_to_array);
}
});