Converting jLabel to a jTextField - netbeans

I'm working on a JFrame interface to interact easily with a large amount of data. The data is saved in a .txt file, and when a name is selected from the JList, my program reads the appropriate lines of data, converts them into an Object I've defined (CounterParty), and displays the appropriate fields of the objects in JLabels. This all works well. I've also written code to launch a new JPanel that edits the selected Object. The JPanel opens, already populated with the data, and when a button is clicked the existing information on the .txt file is deleted and replaced with the new, edited data. This also works well.
However, I would like to make this a bit more user-friendly. I want the JLabels where the information is initially displayed to convert into JTextFields populated with the data from the jLabels when the Edit button is clicked. This would remove needing to launch the new JPanel window altogether. I assume is would change the visibility to false of the JLabels and create new JTextField objects. I'm having trouble with this. Can JLabel objects be converted to JTextFields? Can I maybe have both objects in the exact same spot, but alternate visibility? I'm not sure how to go about this.
I'm using NetBeans.
Thank you for your help! Let me know if any additional information is needed.

This is one way to do that:
Assuming that JLabel is your label and textfield your JTextField
textfield = new JTextField(label.getText());
This will create a with the text of the JLabel.
You should place your JLabel in a dedicated JPanel, so you remove the JLabel from it and replace it with the JTextField, then repaint()/revalidate()

I created a small example which I think demonstrates what you want. It uses a button which when pressed will either remove the JTextField and add the JLabel and vice versa and then it will call revalidate() and repaint() to show changes to the frame after each button click:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JLabelToJTextField extends JFrame {
JLabel jLabel;
JTextField jTextField;
JButton jButton;
JPanel mainPanel;
public JLabelToJTextField() {
jLabel = new JLabel("Name");
jTextField = new JTextField(15);
jButton = new JButton("Edit");
mainPanel = new JPanel(new BorderLayout());
createUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JLabelToJTextField().setVisible(true);
}
});
}
private void createUI() {
setTitle("JLabel to JtextField");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPanel();
setLocationRelativeTo(null);
pack();
}
private void addComponentsToPanel() {
mainPanel.add(jLabel, BorderLayout.CENTER);
mainPanel.add(jButton, BorderLayout.SOUTH);
addActionListeners();
getContentPane().add(mainPanel);
}
private void addActionListeners() {
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
switch (jButton.getText()) {
case "Edit":
mainPanel.remove(jLabel);//remove component
mainPanel.add(jTextField, BorderLayout.CENTER);//add new component
jButton.setText("Done");
//refresh JFrame
revalidate();
repaint();
break;
case "Done":
mainPanel.remove(jTextField);//remove component
mainPanel.add(jLabel, BorderLayout.CENTER);//add new component
jButton.setText("Edit");//set button text to original
//refresh JFrame
revalidate();
repaint();
break;
}
}
});
}
}

Related

Multiple RadioButtons Simulator

I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Put the ActionListener into the sim class.
public void actionPerformed(ActionEvent e)
{
JButton clicked = (JButton)e.getSource();
if(clicked == button)
{
JOptionPane.showMessageDialog(null, "this team will win");
}
}
You need to decrees the amount of code to just amount needed you dont need to show us all the raidio

JScrollPane in Eclipse by using palette

I am trying to make a JFrame scrollable by using Palette. In Netbeans if I make a panel with dimensions (300, 500) and a ScrollPane with dimensions (200,200) then if I drag and drop the panel into the ScrollPane it creates automatically the bars.
In eclipse I tried it with the same way and I cannot make it. Moreover the final code in eclipse after the attempt is the following:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
public class InsertWaterRawData extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InsertWaterRawData frame = new InsertWaterRawData();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public InsertWaterRawData() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 577, 383);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(236, 87, 200, 200);
contentPane.add(scrollPane);
JPanel panel = new JPanel();
scrollPane.setViewportView(panel);
panel.setLayout(null);
}
}
Is there any way to make it with the palette ??
Thanks in advance
panel.setLayout(null);
Don't use a null layout!!!
The scrollbars will appear automatically when the preferred size of the panel is greater than the size of the scrollpane.
When you use a layout manager the preferred size of the panel will be calculated automatically as you add components to the panel.
If you are doing custom painting on your panel, then you need to override the getPreferredSize() method of your panel to return an appropriate size.
Based on the code you posted there is no need for scrollbars because no components have been added to the panel.

How do I add a button and label to my frame?

Ok basically my problem is I don't know how to get my buttons and my labels to appear in the frame that I just created. I tried using frame.add(new JButton("VOTE1")); but that doesn't work and it says it's missing an identifier. Here is my code so far, your help is much appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class VotingMachine extends JFrame implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame("Voting Machine");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JLabel Candidate1 = new JLabel("My Name");
private JLabel Candidate2 = new JLabel("Jennifer Lawrence");
private JLabel Candidate3 = new JLabel("Cristiano Ronaldo");
private JButton VOTE1 = new JButton("VOTE FOR Bishoy Morcos");
private JButton VOTE2 = new JButton("VOTE FOR Jennifer Lawrence");
private JButton VOTE3 = new JButton("VOTE FOR Cristiano Ronaldo");
int countcandidate1;
int countcandidate2;
int countcandidate3;
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == VOTE1)
countcandidate1++;
else if(o == VOTE2)
countcandidate2++;
else if(o == VOTE3)
countcandidate3++;
}
}
First you need to create a JPanel
JPanel welcomePanel = new JPanel();
Then add the buttons and labels to that panel
welcomePanel.add(Candidate1);
welcomePanel.add(VOTE1);
ETC.... for all of your buttons and labels
Lastly, add that JPanel to your JFrame
frame.add(welcomePanel);
If this answers your question, please mark it as answered so other viewers will be informed.

displaying jpg to a jPanel

So i am trying to add an image to my program after a button is pressed with a certain value entered into a text field. I want the image to be blank until the button is pressed with the correct value. The only issue i seem to be having is making the photo appear, i know the output should be working. here is the code i have for adding the label.
photo = new JLabel();
photo.setBounds(425, 170, 400, 360);
contentPane.add(photo);
ImageIcon icon = new ImageIcon("AwsomeSauce.jpg");
here is the code for when the value is entered correctly
if (error) {
photo.setIcon(image);
}
now im still pretty new at this so go easy on me.
Here is simple example for you:
public class Frame extends JFrame {
private JLabel label;
public Frame() {
getContentPane().add(label = new JLabel(),BorderLayout.SOUTH);
JButton b = new JButton("show Icon");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
URL resource = getClass().getResource("/res/3_disc.png");
ImageIcon ico = new ImageIcon(resource);
label.setIcon(ico);
}
});
getContentPane().add(b,BorderLayout.NORTH);
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setTitle("This is a test");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
"/res/3_disc.png" - is my icon which is placed in my project in res folder.

Generating check boxes dynamically, Netbeans

I am developing a desktop application in which I want Admin have option to delete users, for which I planned that whenever Admin clicks on 'delete users' button a new tab will open in which check boxes with the name of all existing users in my database should appear(so that he can delete multiple users simultaneously); so basically I need to generate dynamic check boxes as per my database.
I am using Netbeans 7.0.1, jdk 1.6, sqlite3.
After searching on google I got two links which match to my problem:
http://www.coderanch.com/t/345949/GUI/java/create-dynamic-checkboxes#2805277
Creating dcheckbox dynamically in Java-NetBeans
I have tried to follow the code from above first link but it does not working for me properly. What I does is just created new JFrame in netbeans and called a method inside constructor which create checkboxes as per needed, method's code is as below:
public class Work extends javax.swing.JFrame {
/** Creates new form Work */
public Work() {
initComponents();
checks = new java.util.ArrayList<>();
createCheckboxes();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void createCheckboxes(){
panel = new javax.swing.JPanel();
this.add(panel);
for(int i = 0; i<4; i++){
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
panel.add(box);
checks.add(box);
panel.revalidate();
panel.repaint();
}
panel.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Work.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
private java.util.ArrayList <javax.swing.JCheckBox> checks;
private javax.swing.JPanel panel;
}
The output is just a blank frame. Please help me to know where I am wrong!!
And yes this code is not connected to database yet, once it will work then I can modify it to work with database.
Also is their any other betterway to accomplish my task or am on right path?`
I think it might help if u call the following function whenever to wanna create a new checkbox..
public class CheckBox extends JFrame{
//private static final long serialVersionUID = 1L;
public CheckBox() {
// set flow layout for the frame
this.getContentPane().setLayout(new FlowLayout(FlowLayout.TRAILING, 50, 20)); //(default) centered alignment and a default 5-unit horizontal and vertical gap.
JCheckBox checkBox1 = new JCheckBox("Checkbox 1");
checkBox1.setSelected(true);
JCheckBox checkBox2 = new JCheckBox("Checkbox 2", true);
JCheckBox checkBox3 = new JCheckBox("Checkbox 3");
// add checkboxes to frame
add(checkBox1);
add(checkBox2);
add(checkBox3);
}
private static void createAndShowGUI() {
//Create and set up the window.
//JFrame frame = new CreateCheckedUncheckedJCheckBox();
CheckBox cb = new CheckBox();
//Display the window.
cb.pack();
cb.setVisible(true);
cb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You add the new checkboxes as if your frame was using some simple layout such as FlowLayout, but it is not - it is using GroupLayout - see the generated initComponents() method.
If you want to handle ALL components in the frame dynamically, you can do this (it is better to create an empty class file and then paste the code below; do not ask NB to create a JFrame as it would again create a form to be designed in the visual designer; if you still do it then r-click it and change the layout to something simpler):
public class Work extends javax.swing.JFrame {
private java.util.List <javax.swing.JCheckBox> checks = new java.util.ArrayList<>();;
public Work() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new java.awt.FlowLayout()); // simply put the components next to each other
createCheckboxes();
}
private void createCheckboxes(){
for(int i=0; i<4; i++) {
javax.swing.JCheckBox box = new javax.swing.JCheckBox("check"+i);
add(box);
checks.add(box);
}
pack(); // this will tell the JFrame's panel to layout all the components
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Work().setVisible(true);
}
});
}
}
Or you can design part of your frame with the visual designer and then add the checkboxes. In that case add an empty panel in the designer, set the panel's layout to something like flow or grid layout and then add the checkboxes to that panel from your code in the same way as above.
You validate needs to be called only if the panel/frame is already visible. Calling pack works even then, but might change the size of the frame. Also validating can be done after all components were added not after adding each one.
To add check boxes or any other component dynamically in Netbeans JFrame one need to manage Layout Managers, by default netbeans frames use Free Design Layout, follow steps below:
Create blank JFrame -->Add Jpanel to it-->right click to the panel, select setLayout and change it to GridLayout.
Now we are free to add ant components on this panel.
Also don't forgate to add revalidate() and repaint() methods.
This worked for me.