How to create JCheckBox that changes the text in JLabel - java

How can I declare JCheckBox so that when it's checked it will change the JLabel text to uppercase?
I've been trying many things yet nothing works
public void itemStateChanged(ItemEvent e) {
Font f = null;
if(Bold.isSelected() && Italic.isSelected())
f = new Font("Serif", Font.BOLD + Font.ITALIC, 14);
else if(Bold.isSelected())
f = new Font("Serif", Font.BOLD, 14);
else if(Italic.isSelected())
f = new Font("Serif", Font.ITALIC, 14);
if(Capitalized.isSelected()){
}
label3.setFont(f);
}
What should put inside if(Capitalized.isSelected())?

Have you tried getting the text, then calling toUpperCase() on it:
label3.setText(label3.getText().toUpperCase());

Related

Text area exceeds the window area

I have wrote program in java the program is to convert from KM to miles and miles to KM the program works fine but the problem is in the result in text area exceeded the area so does not appear the full text below the code attached. so i want if it is reached at the end of line it goes to new line
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Converter extends JFrame implements ActionListener {
JLabel label = new JLabel("Distance : ");
JTextField input = new JTextField(10);
JButton button = new JButton("Convert");
JTextArea output = new JTextArea(10,15);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Convert MILES to KM", cbg, true);
Checkbox cb2 = new Checkbox("Convert KM to MILES", cbg, false);
public static void main(String args[]) {
Converter s = new Converter();
s.setVisible(true);
}
public Converter() {
setLayout(null);
setSize(300,400);
//left-down-width-hegiht
cb1.setBounds(60,30,150,30);
cb2.setBounds(60,60,150,30);
label.setBounds(30,90,120,30);
input.setBounds(90,95,170,20);
button.setBounds(100,130,90,30);
output.setBounds(45,168,200,165);
add(cb1);
add(cb2);
add(label);
add(input);
add(button);
add(output);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (cb1.getState() ) {
if (e.getSource() == button) {
double d = Double.parseDouble(input.getText());
double d2 = d / 0.62;
String str2 = String.valueOf(d2);
output.setText(d + "miles equals to " + str2 + " kilometers");
}
}
if (cb2.getState()) {
if (e.getSource() == button){
double d = Double.parseDouble(input.getText());
double d2 = d * 0.62;
String str2 = String.valueOf(d2);
output.setText(d + " kilometers equals to " + str2 + " miles ");
}
}
}
}
If your goal is purely to have line wrapping on in the text area then you can make use of JTextArea's built-in function named setLineWrap.
Passing a true boolean value as a parameter to setLineWrap such as setLineWrap(true) will turn on line wrapping for the JTextArea component. Passing a false boolean value as a parameter will turn off line wrapping
In your code, it would be used as follows.
output.setLineWrap(true);
The Converter constructor will then look as follows.
public Converter() {
// Turn on line wrapping.
output.setLineWrap(true);
setLayout(null);
setSize(300, 400);
// left-down-width-hegiht
cb1.setBounds(60, 30, 150, 30);
cb2.setBounds(60, 60, 150, 30);
label.setBounds(30, 90, 120, 30);
input.setBounds(90, 95, 170, 20);
button.setBounds(100, 130, 90, 30);
output.setBounds(45, 168, 200, 165);
add(cb1);
add(cb2);
add(label);
add(input);
add(button);
add(output);
button.addActionListener(this);
}

How to append a scrollbar for the window?

How to append a scroll pane for my window?
The program compiles properly, but the scroll pane for the window is not created. I really don't know why this is happening. I defined JScrollPane and even implemented it with scrollPane = new JScrollPane
Where is my mistake?
Below is my code:
import java.awt.*;
import java.awt.Font;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JScrollPane;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
public class RegForm extends JFrame implements ItemListener{
JLabel l0,li,l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,l13;
JButton b1,b2,b3,b4,b5;
JTextField t1,t2,t3,t4,t5,t6,t7,t8;
JTextArea a1,a2;
JComboBox<Integer> dd = new JComboBox<Integer>();
JComboBox<String> mm = new JComboBox<String>();
JComboBox<Integer> yyyy = new JComboBox<Integer>();
JComboBox<String> q = new JComboBox<String>();
JRadioButton rb1 = new JRadioButton( " Male ");
JRadioButton rb2 = new JRadioButton(" Female ");
JCheckBox cb1 = new JCheckBox (" C ");
JCheckBox cb2 = new JCheckBox (" C++ ");
JCheckBox cb3 = new JCheckBox (" Java ");
JCheckBox cb4 = new JCheckBox (" Oracle ");
JCheckBox cb5 = new JCheckBox (" Android ");
JCheckBox cb6 = new JCheckBox (" iOS ");
JCheckBox cb7 = new JCheckBox (" Web Designing ");
JCheckBox cb8 = new JCheckBox (" .Net ");
JCheckBox cb9 = new JCheckBox (" Same as Contact Address ");
JScrollPane scrollPane = new JScrollPane();
RegForm()
{
l0 = new JLabel("REGISTRATION FORM");
Font f0 = new Font("Algerian",Font.ITALIC,20);
l0.setFont(f0);
l0.setBounds(600,10,250,50);
scrollPane.add(l0);
li = new JLabel(" * Fields are mandatory");
Font fi = new Font("Arabic TypeSetting",Font.PLAIN,17);
li.setFont(fi);
li.setForeground(Color.RED);
li.setBounds(10,50,150,30);
scrollPane.add(li);
l1 = new JLabel(" * FirstName: ");
Font f1 = new Font("Bookman Old Style",Font.PLAIN,12);
l1.setFont(f1);
l1.setBounds(10,70,100,50);
scrollPane.add(l1);
t1 = new JTextField(20);
t1.setBounds(165,85,140,20);
scrollPane.add(t1);
l2 = new JLabel("* Confirm FirstName: ");
l2.setFont(f1);
l2.setBounds(10,100,150,50);
scrollPane.add(l2);
t2 = new JTextField(20);
t2.setBounds(165,115,140,20);
scrollPane.add(t2);
l3 = new JLabel(" Middle Name: ");
l3.setFont(f1);
l3.setBounds(15,130,120,50);
scrollPane.add(l3);
t3 = new JTextField(20);
t3.setBounds(165,145,140,20);
scrollPane.add(t3);
l4 = new JLabel(" Confirm Middle Name: ");
l4.setFont(f1);
l4.setBounds(15,160,150,50);
scrollPane.add(l4);
t4 = new JTextField(20);
t4.setBounds(165,175,140,20);
scrollPane.add(t4);
l5 = new JLabel(" * Sur Name: ");
l5.setFont(f1);
l5.setBounds(10,190,100,50);
scrollPane.add(l5);
t5 = new JTextField(20);
t5.setBounds(165,205,140,20);
scrollPane.add(t5);
l6 = new JLabel(" * Confirm Sur Name: ");
l6.setFont(f1);
l6.setBounds(10,220,150,50);
scrollPane.add(l6);
t6 = new JTextField(20);
t6.setBounds(165,235,140,20);
scrollPane.add(t6);
l7 = new JLabel(" * DD / MM / YYYY" );
Font f2 = new Font(" Comic Sans MS ",Font.ITALIC,12);
l7.setFont(f2);
l7.setBounds(10,260,150,50);
scrollPane.add(l7);
for(int j=1;j<=31;j++)
dd.addItem(new Integer(j));
dd.setBounds(165,275,47,20);
scrollPane.add(dd);
dd.addItemListener(this);
mm.addItem("January");
mm.addItem("February");
mm.addItem("March");
mm.addItem("April");
mm.addItem("May");
mm.addItem("June");
mm.addItem("July");
mm.addItem("August");
mm.addItem("September");
mm.addItem("October");
mm.addItem("November");
mm.addItem("December");
mm.setBounds(212,275,90,20);
scrollPane.add(mm);
mm.addItemListener(this);
for(int i=1990;i<=2016;i++)
yyyy.addItem(new Integer(i));
yyyy.setBounds(302,275,70,20);
scrollPane.add(yyyy);
yyyy.addItemListener(this);
l8 = new JLabel(" Age: ");
l8.setFont(f1);
l8.setBounds(15,290,50,50);
scrollPane.add(l8);
t8 = new JTextField(10);
t8.setBounds(165,305,50,20);
scrollPane.add(t8);
l9 = new JLabel(" Qualification ");
l9.setFont(f1);
l9.setBounds(15,320,120,50);
scrollPane.add(l9);
q.addItem(" B.Tech ");
q.addItem(" M.Tech ");
q.addItem(" MBA ");
q.addItem(" MCA ");
q.addItem(" Intermediate ");
q.addItem(" SSC ");
q.addItem(" Others ");
q.setBounds(165,335,100,20);
scrollPane.add(q);
q.addItemListener(this);
l10 = new JLabel(" Gender ");
l10.setFont(f1);
l10.setBounds(15,360,80,50);
scrollPane.add(l10);
rb1.setBounds(165,365,80,39);
rb2.setBounds(250,365,80,39);
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
scrollPane.add(rb1);
scrollPane.add(rb2);
l11 = new JLabel(" Courses Intrested: ");
l11.setFont(f1);
l11.setBounds(15,450,150,50);
scrollPane.add(l11);
cb1.setBounds(165,390,100,50);
scrollPane.add(cb1);
cb2.setBounds(285,390,100,50);
scrollPane.add(cb2);
cb3.setBounds(165,425,100,50);
scrollPane.add(cb3);
cb4.setBounds(285,425,100,50);
scrollPane.add(cb4);
cb5.setBounds(165,460,100,50);
scrollPane.add(cb5);
cb6.setBounds(285,460,100,50);
scrollPane.add(cb6);
cb7.setBounds(165,495,100,50);
scrollPane.add(cb7);
cb8.setBounds(285,495,100,50);
scrollPane.add(cb8);
cb9.setBounds(15,630,200,50);
scrollPane.add(cb9);
l12 = new JLabel(" Contact Address: ");
l12.setFont(f1);
l12.setBounds(15,550,150,50);
scrollPane.add(l12);
a1 = new JTextArea (5,20);
a1.setBounds(165,545,250,80);
scrollPane.add(a1);
l13 = new JLabel(" Permenant Address: ");
l13.setFont(f1);
l13.setBounds(15,675,150,50);
scrollPane.add(l13);
a2 = new JTextArea (5,20);
a2.setBounds(165,680,250,80);
scrollPane.add(a2);
cb9.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource() == yyyy){
int y = (Integer) ie.getItem();
t8.setText(Integer.toString(2016-y));
t8.setEditable(false);
}
if(cb9.isSelected()){
a2.setText(a1.getText());
a2.setEditable(false);
}
}
public void actionPerformed(ActionEvent ae)
{
}
public static void main(String[] args)
{
RegForm rf = new RegForm();
rf.setTitle("Hai Hello");
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(10,10,100,100);
JPanel contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(1500, 800));
contentPane.add(scrollPane);
rf.setContentPane(contentPane);
rf.pack();
rf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
rf.setVisible(true);
}
}
scrollPane.add(l11);
Never add components directly to a scroll pane.
l1.setBounds(10,70,100,50);
Don't use setBounds(...). It is the job of the layout manager to set the size/location of the component.
The basic logic would be:
JPanel panel = new JPanel(); // set your layout manager for the panel.
panel.add( someComponent );
panel.add( anotherComponent );
JScrollPane scrollPane = new JScrollPane( panel );
frame.add( scrollPane );
Read the Swing Tutorial for Swing basics. Every section in the tutorial has working examples. Maybe start with the section on How to Use Scroll Panes.
This works, but you'll need to layout the components better..
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RegForm extends JFrame implements ItemListener {
JLabel l0, li, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12, l13;
JButton b1, b2, b3, b4, b5;
JTextField t1, t2, t3, t4, t5, t6, t7, t8;
JTextArea a1, a2;
JComboBox<Integer> dd = new JComboBox<Integer>();
JComboBox<String> mm = new JComboBox<String>();
JComboBox<Integer> yyyy = new JComboBox<Integer>();
JComboBox<String> q = new JComboBox<String>();
JRadioButton rb1 = new JRadioButton(" Male ");
JRadioButton rb2 = new JRadioButton(" Female ");
JCheckBox cb1 = new JCheckBox(" C ");
JCheckBox cb2 = new JCheckBox(" C++ ");
JCheckBox cb3 = new JCheckBox(" Java ");
JCheckBox cb4 = new JCheckBox(" Oracle ");
JCheckBox cb5 = new JCheckBox(" Android ");
JCheckBox cb6 = new JCheckBox(" iOS ");
JCheckBox cb7 = new JCheckBox(" Web Designing ");
JCheckBox cb8 = new JCheckBox(" .Net ");
JCheckBox cb9 = new JCheckBox(" Same as Contact Address ");
JScrollPane scrollPane;
JPanel panel = new JPanel(new GridLayout(0,1));
RegForm() {
l0 = new JLabel("REGISTRATION FORM");
Font f0 = new Font("Algerian", Font.ITALIC, 20);
l0.setFont(f0);
l0.setBounds(600, 10, 250, 50);
panel.add(l0);
li = new JLabel(" * Fields are mandatory");
Font fi = new Font("Arabic TypeSetting", Font.PLAIN, 17);
li.setFont(fi);
li.setForeground(Color.RED);
li.setBounds(10, 50, 150, 30);
panel.add(li);
l1 = new JLabel(" * FirstName: ");
Font f1 = new Font("Bookman Old Style", Font.PLAIN, 12);
l1.setFont(f1);
l1.setBounds(10, 70, 100, 50);
panel.add(l1);
t1 = new JTextField(20);
t1.setBounds(165, 85, 140, 20);
panel.add(t1);
l2 = new JLabel("* Confirm FirstName: ");
l2.setFont(f1);
l2.setBounds(10, 100, 150, 50);
panel.add(l2);
t2 = new JTextField(20);
t2.setBounds(165, 115, 140, 20);
panel.add(t2);
l3 = new JLabel(" Middle Name: ");
l3.setFont(f1);
l3.setBounds(15, 130, 120, 50);
panel.add(l3);
t3 = new JTextField(20);
t3.setBounds(165, 145, 140, 20);
panel.add(t3);
l4 = new JLabel(" Confirm Middle Name: ");
l4.setFont(f1);
l4.setBounds(15, 160, 150, 50);
panel.add(l4);
t4 = new JTextField(20);
t4.setBounds(165, 175, 140, 20);
panel.add(t4);
l5 = new JLabel(" * Sur Name: ");
l5.setFont(f1);
l5.setBounds(10, 190, 100, 50);
panel.add(l5);
t5 = new JTextField(20);
t5.setBounds(165, 205, 140, 20);
panel.add(t5);
l6 = new JLabel(" * Confirm Sur Name: ");
l6.setFont(f1);
l6.setBounds(10, 220, 150, 50);
panel.add(l6);
t6 = new JTextField(20);
t6.setBounds(165, 235, 140, 20);
panel.add(t6);
l7 = new JLabel(" * DD / MM / YYYY");
Font f2 = new Font(" Comic Sans MS ", Font.ITALIC, 12);
l7.setFont(f2);
l7.setBounds(10, 260, 150, 50);
panel.add(l7);
for (int j = 1; j <= 31; j++) {
dd.addItem(new Integer(j));
}
dd.setBounds(165, 275, 47, 20);
panel.add(dd);
dd.addItemListener(this);
mm.addItem("January");
mm.addItem("February");
mm.addItem("March");
mm.addItem("April");
mm.addItem("May");
mm.addItem("June");
mm.addItem("July");
mm.addItem("August");
mm.addItem("September");
mm.addItem("October");
mm.addItem("November");
mm.addItem("December");
mm.setBounds(212, 275, 90, 20);
panel.add(mm);
mm.addItemListener(this);
for (int i = 1990; i <= 2016; i++) {
yyyy.addItem(new Integer(i));
}
yyyy.setBounds(302, 275, 70, 20);
panel.add(yyyy);
yyyy.addItemListener(this);
l8 = new JLabel(" Age: ");
l8.setFont(f1);
l8.setBounds(15, 290, 50, 50);
panel.add(l8);
t8 = new JTextField(10);
t8.setBounds(165, 305, 50, 20);
panel.add(t8);
l9 = new JLabel(" Qualification ");
l9.setFont(f1);
l9.setBounds(15, 320, 120, 50);
panel.add(l9);
q.addItem(" B.Tech ");
q.addItem(" M.Tech ");
q.addItem(" MBA ");
q.addItem(" MCA ");
q.addItem(" Intermediate ");
q.addItem(" SSC ");
q.addItem(" Others ");
q.setBounds(165, 335, 100, 20);
panel.add(q);
q.addItemListener(this);
l10 = new JLabel(" Gender ");
l10.setFont(f1);
l10.setBounds(15, 360, 80, 50);
panel.add(l10);
rb1.setBounds(165, 365, 80, 39);
rb2.setBounds(250, 365, 80, 39);
ButtonGroup bg = new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
panel.add(rb1);
panel.add(rb2);
l11 = new JLabel(" Courses Intrested: ");
l11.setFont(f1);
l11.setBounds(15, 450, 150, 50);
panel.add(l11);
cb1.setBounds(165, 390, 100, 50);
panel.add(cb1);
cb2.setBounds(285, 390, 100, 50);
panel.add(cb2);
cb3.setBounds(165, 425, 100, 50);
panel.add(cb3);
cb4.setBounds(285, 425, 100, 50);
panel.add(cb4);
cb5.setBounds(165, 460, 100, 50);
panel.add(cb5);
cb6.setBounds(285, 460, 100, 50);
panel.add(cb6);
cb7.setBounds(165, 495, 100, 50);
panel.add(cb7);
cb8.setBounds(285, 495, 100, 50);
panel.add(cb8);
cb9.setBounds(15, 630, 200, 50);
panel.add(cb9);
l12 = new JLabel(" Contact Address: ");
l12.setFont(f1);
l12.setBounds(15, 550, 150, 50);
panel.add(l12);
a1 = new JTextArea(5, 20);
a1.setBounds(165, 545, 250, 80);
panel.add(a1);
l13 = new JLabel(" Permenant Address: ");
l13.setFont(f1);
l13.setBounds(15, 675, 150, 50);
panel.add(l13);
a2 = new JTextArea(5, 20);
a2.setBounds(165, 680, 250, 80);
panel.add(a2);
cb9.addItemListener(this);
scrollPane = new JScrollPane(panel);
add(scrollPane);
//add(panel);
}
public void itemStateChanged(ItemEvent ie) {
if (ie.getSource() == yyyy) {
int y = (Integer) ie.getItem();
t8.setText(Integer.toString(2016 - y));
t8.setEditable(false);
}
if (cb9.isSelected()) {
a2.setText(a1.getText());
a2.setEditable(false);
}
}
public void actionPerformed(ActionEvent ae) {
}
public static void main(String[] args) {
RegForm rf = new RegForm();
rf.setTitle("Hai Hello");
/*JScrollPane panel = new JScrollPane();
panel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
panel.setBounds(10, 10, 100, 100);
JPanel contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(1500, 800));
contentPane.add(panel);
rf.setContentPane(contentPane);*/
rf.pack();
rf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
rf.setVisible(true);
}
}
Notes:
As mentioned by #camickr, setting the bounds of the components won't work reliably. Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Please try to solve programming errors before you've got to dozens of components! For simple testing of layouts with many components, just add dummy components in a loop. To put that another way: For better help sooner, post a Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
Safer to use logical font names that specific one, e.g. Algerian will only work on systems with that font installed!

Can you add an image to a GUI using the picture's URL?

I am currently creating a database that uses information from IMDB and Rotten Tomatoes. In the printout of the data (in a GUI Frame), I have to list the URL to the poster image of the movie.
My question is this: Instead of printing the image URL, is there a way to use the URL to show the image WITHOUT having the image stored locally?
Here's the code I have to display the data retrieved from mySQL (It works, I just want the URL to show as an image instead of the link):
public void mouseClicked(MouseEvent e) {
JFrame frame3 = new JFrame("Query 1: Top Movies");
frame3.setBackground(Color.BLACK);
frame3.setSize(new Dimension(1500,1500));
frame3.setVisible(true);
frame3.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
System.out.println("frame created");
try {
loadConnection();
//create query
System.out.println("Connection loaded...");
String sql = "SELECT M.TITLE,M.YEAR,M.RTAUDIENCESCORE,M.IMDBPICTUREURL FROM MOVIES AS M ORDER BY RTAUDIENCESCORE DESC,TITLE LIMIT 10";
//prepares statement for execution
java.sql.PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
System.out.println("Query Successful!");
//create labels for output
JLabel l1, l2, l3, l4;
JTextField title, year, RTscore, IMDBURL;
//labels
l1 = new JLabel("Title");
l2 = new JLabel("Year");
l3 = new JLabel("RT Audience Score");
l4 = new JLabel("IMDB Picture URL");
l1.setBounds(20, 20, 150, 20);
l2.setBounds(200, 20, 150, 20);
l3.setBounds(380, 20, 150, 20);
l4.setBounds(560, 20, 150, 20);
frame3.add(l1);
frame3.add(l2);
frame3.add(l3);
frame3.add(l4);
System.out.println("Frames added...");
int y = 50;
while (rs.next()) {
//Text fields
title = new JTextField();
year = new JTextField();
RTscore = new JTextField();
IMDBURL = new JTextField();
title.setText(rs.getString(1));
year.setText(rs.getString(2));
RTscore.setText(rs.getString(3));
IMDBURL.setText(rs.getString(4));
title.setBounds(20, y, 150, 20);
year.setBounds(200, y, 150, 20);
RTscore.setBounds(380, y, 150, 20);
IMDBURL.setBounds(560, y, 150, 20);
y+=30;
frame3.add(title);
frame3.add(year);
frame3.add(RTscore);
frame3.add(IMDBURL);
}
JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(IMDBURL))
In your case you will have edit your while loop and add new label which will represent image.
frame3.add(title);
frame3.add(year);
frame2.add(RTscore);
frame3.add(jLabelObject);

insert data into database(mongodb)

I have used the following code to insert data into the mongodb database.....the problem with this i have to explicitly specify the data to be entered but however I need to do it dynamically...in the sense using a GUI, whatever has been entered int the text box must be put into the database.
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 512, 355);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Name");
lblNewLabel.setBounds(42, 33, 95, 30);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Manufacturer");
lblNewLabel_1.setBounds(42, 74, 80, 30);
frame.getContentPane().add(lblNewLabel_1);
textField = new JTextField();
textField.setBounds(147, 33, 122, 25);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(147, 79, 122, 25);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnInsert = new JButton("Insert");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MongoClient mongoClient = null;
DBCursor cursor = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "sample" );
DBCollection coll = db.getCollection("sample");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("name","a" ).
append("manufacturer", "b").
append("colour", "c").
append("price", "d");
coll.insert(doc);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );}
}
});
btnInsert.setBounds(148, 223, 89, 23);
frame.getContentPane().add(btnInsert);
JLabel lblNewLabel_2 = new JLabel("Colour");
lblNewLabel_2.setBounds(42, 127, 65, 25);
frame.getContentPane().add(lblNewLabel_2);
textField_2 = new JTextField();
textField_2.setBounds(147, 129, 122, 25);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
JLabel lblNewLabel_3 = new JLabel("Price");
lblNewLabel_3.setBounds(37, 175, 70, 25);
frame.getContentPane().add(lblNewLabel_3);
textField_3 = new JTextField();
textField_3.setBounds(147, 177, 122, 25);
frame.getContentPane().add(textField_3);
textField_3.setColumns(10);
}
}
"i have a front end which has 4 text boxes saying "name","manufacturer","colour" and "price"....so whatever i enter in the text box should be put into the database....however in the above code insertion can be done only by explicitly specifying the values....so i need to change this for a generlized method"
Just change it to something like:
String name = nameField.getText();
String manufacturer = manufacturerField.getText();
String color = colorField.getText();
String price = priceField.getText();
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("name", name ).
append("manufacturer", manufacturer).
append("colour", color).
append("price", price);
coll.insert(doc);
Is that what you're looking for?

delete previous content from JTable every time button event happens

I'm having a hard time removing data from my JTable. I've tried JTable .repaint(), setRowCount(0) , also model.removeRow(). I created print statements to see the row count when using setRowCount and the rows do become 0 however my table does not update. This is the last part of this project I need to implement. I'm not sure why my table isn't updating because I am altering the model with removeRow as well as setRowCount. If you guys could guide me in the right direction I would appreciate it.
public class TemplateGui extends JFrame {
private final ButtonGroup buttonGroup = new ButtonGroup();
private JTextField textField;
private static String [] sortedRoles_Flags,finalFlagsArr,finalHSArr;
private static String finalFlags="",finalHS="",columnToConvert="Result";
private Vector<String> SF,HS,column;
private JTable hotelSecurityTable,securityFlagsTable;
private DefaultTableModel hsTableModel,sfTableModel;
public TemplateGui(){
super("Galaxy Template Generator V1.0");
//column name
column = new Vector(Arrays.asList(columnToConvert));
getContentPane().setForeground(new Color(0, 0, 0));
getContentPane().setLayout(null);
getContentPane().setBackground(new Color(51, 51, 51));
//radio buttons
JRadioButton rdbtnNewRadioButton = new JRadioButton("Central User ");
rdbtnNewRadioButton.setFont(new Font("Tahoma", Font.BOLD, 11));
rdbtnNewRadioButton.setBackground(Color.WHITE);
buttonGroup.add(rdbtnNewRadioButton);
rdbtnNewRadioButton.setBounds(222, 75, 127, 36);
getContentPane().add(rdbtnNewRadioButton);
final JRadioButton rdbtnPropertyUser = new JRadioButton("Property User");
rdbtnPropertyUser.setFont(new Font("Tahoma", Font.BOLD, 11));
rdbtnPropertyUser.setBackground(Color.WHITE);
buttonGroup.add(rdbtnPropertyUser);
rdbtnPropertyUser.setBounds(222, 38, 127, 34);
getContentPane().add(rdbtnPropertyUser);
textField = new JTextField();
textField.setFont(new Font("Tahoma", Font.BOLD, 18));
textField.setBounds(10, 35, 53, 34);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblHotelSecurity = new JLabel("Hotel Security (H S)");
lblHotelSecurity.setHorizontalAlignment(SwingConstants.CENTER);
lblHotelSecurity.setFont(new Font("Tahoma", Font.BOLD, 13));
lblHotelSecurity.setBounds(10, 144, 189, 23);
lblHotelSecurity.setBackground(new Color(204, 204, 204));
lblHotelSecurity.setOpaque(true);
getContentPane().add(lblHotelSecurity);
JLabel label = new JLabel("Security Flags (S F)");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setFont(new Font("Tahoma", Font.BOLD, 13));
label.setBounds(222, 144, 372, 23);
label.setBackground(new Color(204, 204, 204));
label.setOpaque(true);
getContentPane().add(label);
JLabel lblEnterTemplateCode = new JLabel("ENTER TEMPLATE CODE");
lblEnterTemplateCode.setForeground(new Color(255, 255, 255));
lblEnterTemplateCode.setFont(new Font("Tahoma", Font.BOLD, 14));
lblEnterTemplateCode.setBounds(10, 9, 175, 23);
getContentPane().add(lblEnterTemplateCode);
JLabel lblSelectUserRole = new JLabel("SELECT USER ROLE LEVEL");
lblSelectUserRole.setForeground(new Color(255, 255, 255));
lblSelectUserRole.setFont(new Font("Tahoma", Font.BOLD, 14));
lblSelectUserRole.setBounds(222, 13, 195, 14);
getContentPane().add(lblSelectUserRole);
//Submit button action
Button button = new Button("Generate Template");
button.setFont(new Font("Dialog", Font.BOLD, 12));
button.setBackground(new Color(102, 255, 102));
button.setForeground(Color.BLACK);
button.setBounds(467, 83, 127, 41);
getContentPane().add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Query excell = new Query();
//get template text
String template = textField.getText().toUpperCase();
System.out.println(template);
if(rdbtnPropertyUser.isSelected()){
try {
//property user was selected
excell.runProcess(1);
System.out.println("you selected Property user");
} catch (IOException e) {
e.printStackTrace();
}
}
else{
try {
//Central User was selected
excell.runProcess(2);
System.out.println("you selected central user");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("NOW WERE HERE");
//get static variables from Excel Query
for(int i = 0; i< Query.sortedGF.length; i++)
{
if(Query.sortedGF[i].contains(template)){
sortedRoles_Flags =Query.sortedGF[i].split(" ");
System.out.println("THIS RAN"+" :"+i);
break;
}
}
//add data to table
int j=1;
int sizeOfFlags = Query.securityFlags.length;
//Add HS to FinalHS Variable only if Yes
for(int i=0;i< sortedRoles_Flags.length+1-sizeOfFlags;i++)
{
if(sortedRoles_Flags[i].matches("Y|y|Y\\?|\\?Y|y\\?|\\?y"))
{
System.out.println("Hotel security:"+" "+sortedRoles_Flags[i]+" HS Added: "+Query.hotelSecurity[i]);
finalHS += Query.hotelSecurity[i]+"+";
System.out.println("Hotel security:"+" "+finalHS);
}
}
//add Security Flags to Final Flags
for(int i=(sortedRoles_Flags.length-sizeOfFlags+1);i< sortedRoles_Flags.length;i++)
{
finalFlags += Query.securityFlags[j]+"\t\t: "+ sortedRoles_Flags[i]+" + ";
j++;
}
//Leave open just incase they would prefer a text file for template in which case we just write it
System.out.println(finalFlags);
System.out.println(finalHS);
//Convert to String Arrays in order to add to our JTable
finalFlagsArr= finalFlags.split("\\+");
finalHSArr = finalHS.split("\\+");
for(int i=0; i <finalHSArr.length;i++)
finalHSArr[i].replaceAll(" ","");
hsTableModel.setRowCount(0);
for (String row : finalHSArr) {
hsTableModel.addRow(new Object[]{row});
}
sfTableModel.setRowCount(0);
for (String row : finalFlagsArr) {
sfTableModel.addRow(new Object[]{row});
}
}
});
//scroll panes for flags
JScrollPane scrollPaneHS = new JScrollPane();
scrollPaneHS.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPaneHS.setBounds(10, 170, 189, 185);
getContentPane().add(scrollPaneHS);
JScrollPane scrollPaneSF = new JScrollPane();
scrollPaneSF.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPaneSF.setBounds(222, 170, 372, 187);
getContentPane().add(scrollPaneSF);
//tables for updates
hsTableModel = new DefaultTableModel(HS,column);
hotelSecurityTable = new JTable(hsTableModel);
hotelSecurityTable.setBackground(new Color(255, 255, 255));
scrollPaneHS.setViewportView(hotelSecurityTable);
sfTableModel = new DefaultTableModel(SF,column);
securityFlagsTable = new JTable(sfTableModel);
scrollPaneSF.setViewportView(securityFlagsTable);
}
}
Update
my latest attempt. It seemed to work but not the second time around.
if(hsTableModel.getRowCount() !=0 && sfTableModel.getRowCount() !=0){
for(int i=0; i<hsTableModel.getRowCount();i++)
hsTableModel.removeRow(i);
for(int i=0; i<sfTableModel.getRowCount();i++)
sfTableModel.removeRow(i);
sfTableModel.fireTableRowsDeleted(0, sfTableModel.getRowCount()-1);
hsTableModel.fireTableRowsDeleted(0, hsTableModel.getRowCount()-1);
}
when using setRowCount and the rows do become 0 however my table does not update.
Since you are using a DefaultTableModel, the setRowCount(0) is the proper method to use to clear the model of all the entries. The should automatically repaint itself.
Create a simple SSCCE that demonstrates your problem. The SSCCE should consist of a JTable with data, and then a JButton to invoke the setRowCount() method.
Prove to yourself that the basic concept works and then determine why you real code doesn't. If the table does not repaint then it usually means you are invoking the setRowCount() method on a TableModel that has NOT be added to the JTable that is visible on the GUI.
Also, don't:
use Button. You should be using a JButton
use a null layout. Swing was designed to be used with Layout Managers.
setRowCount(0) works.
I was forgetting to reset the string Values of
finalHS =""; finalFlags=""; Therefore the table was printing out the values stored in the variable.
I had the variables obtain their data through += Method as seen below.
Next time I will SSCCE before posting.
for(int i=0;i< sortedRoles_Flags.length+1-sizeOfFlags;i++)
{
if(sortedRoles_Flags[i].matches("Y|y|Y\\?|\\?Y|y\\?|\\?y"))
{
System.out.println("Hotel security:"+" "+sortedRoles_Flags[i]+" HS Added: "+Query.hotelSecurity[i]);
finalHS += Query.hotelSecurity[i]+"+";
System.out.println("Hotel security:"+" "+finalHS);
}
}
//add Security Flags to Final Flags
for(int i=(sortedRoles_Flags.length-sizeOfFlags+1);i< sortedRoles_Flags.length;i++)
{
finalFlags += Query.securityFlags[j]+"\t\t: "+ sortedRoles_Flags[i]+" + ";
j++;
}

Categories

Resources