New line using JLabel and java variable from ArrayList - java

I create a button that will onclick show in a separate window (like you see below) the list of all users from my database.
But, they are displayed all in one line! Even though I put /n - it just wont work. I mean, it work in console when I use Sys.out but when I go to the Window and put it there it is all in one line :(
What should I change in order to display all of the users one below another.
public class ViewAll {
private String listax = "";
ViewAll() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
ArrayList<String[]> allUsers = DbBroker.getArray("select * from user");
for(String[] usr : allUsers)
listax += usr[0] + ")" + usr[1] + ", " + usr[2] + ", " + usr[3] + "\n";
}
public void display() {
JFrame lis = new JFrame("List of all users");
lis.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
lis.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel pane = new JPanel(new GridLayout(0,1));
lis.add(pane);
pane.add(new JLabel("This is the complete list of all users in my db: "));
pane.add(new JLabel(listax));
lis.pack();
lis.setSize(500,400);
lis.setVisible(true);
}}

I suggest that you don't use a JLabel but instead use a JList. It was built to do just this sort of a thing. The key here being: use the right tool for the job. It also appears that you're trying to use a JFrame in a dialog capacity, and if so, don't -- use a JDialog instead, or even a JOptionPane:
public void display(List<String> userList) {
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String user : userList) {
listModel.addElement(user);
}
JList<String> userLabel = new JList<String>(listModel);
JScrollPane scrollPane = new JScrollPane(userLabel);
String title = "This is the complete list of all users in my db:";
// mainJFrame is the main JFrame for the GUI
JOptionPane.showMessageOption(mainJFrame, scrollPane, title,
JOptionPane.PLAIN_MESSAGE);
}

Related

Loading images and data from a text file and appending to it (Java)

I've created a platform game where each type of game object is assigned to specific rgb values so I can create levels by drawing them out in paint and loading the image. Right now I have the first two levels already loaded and I am able to get the path of the 3rd level through a textfield input and load a custom 3rd level. Each level needs a path to the png image of the level, and the number of coins needed to progress to the next level. I want to have every level load up from one text file where each line maybe has the level number, the image path, and the # of coins. I'm making it to be customizable so that the user can add or change levels simply by adding these parameters through 3 textfields in my customize menu. This way also my designer can help create levels and by reading from the text file I imagine there will be a lot less code in the long run when there are 20+ levels. Any ideas on how I can load from and append to this file? Here's what I'm working with right now:
public static BufferedImageLoader loader = new BufferedImageLoader();
public Handler(Camera cam){
this.cam = cam;
level1 = loader.loadImage("/level1.png");
level2 = loader.loadImage("/level2.png");
}
public void changeLevel(){
clearLevel();
cam.setX(0);
Player.coinCount = 0;
if(Game.LEVEL == 1){
Player.maxCoins = 4;
LoadImageLevel(level1);
}
if(Game.LEVEL == 2){
LoadImageLevel(level2);
Player.maxCoins = 11;
}
if(Game.LEVEL == 3){
System.out.println(Data.levelPath);
try{
level3 = loader.loadImage(Data.levelPath);
LoadImageLevel(level3);
} catch (Exception e) {
e.printStackTrace();
System.out.println("error loading custom level");
}
}
}
public Menu(Game game, Handler handler){
this.handler = handler;
pathField = new JTextField(10);
levelField = new JTextField(10);
coinField = new JTextField(10);
if(Game.gameState == STATE.Menu){
int selection = JOptionPane.showConfirmDialog(
null, getPanel(), "Input Form : "
, JOptionPane.OK_CANCEL_OPTION
, JOptionPane.PLAIN_MESSAGE);
if(selection == JOptionPane.OK_OPTION) {
Data.levelPath = pathField.getText();
Data.level = levelField.getText();
Data.coinAmount = Double.valueOf(coinField.getText());
System.out.println(Data.levelPath + Data.level + Data.coinAmount);
}
}
private JPanel getPanel(){
JPanel basePanel = new JPanel();
basePanel.setOpaque(true);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 2, 5, 5));
centerPanel.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
centerPanel.setOpaque(true);
JLabel mLabel1 = new JLabel("Enter path: (e.g., /level1.png) ");
JLabel mLabel2 = new JLabel("Enter which level to load the image in: ");
JLabel mLabel3 = new JLabel("Enter the amount of coins you must collect");
centerPanel.add(mLabel1);
centerPanel.add(pathField);
centerPanel.add(mLabel2);
centerPanel.add(levelField);
centerPanel.add(mLabel3);
centerPanel.add(coinField);
basePanel.add(centerPanel);
return basePanel;
}
Any ideas or suggestions are appreciated!
It's actually just....
Given a value of the input.getText() as 1#path#20, It have level number, the image path, and the number of coins separated by # token.
public static String [] separateFields(String input, String separator){
String[] separatedValues = input.split("#");
return separatedValues;
}
Call the function, define the arguments.
// input is textfield.getText() , and the value of input is 1#path#20
String [] result= separateFields(input, "#");
Then you get
int level = Integer.parseInt(result[0]); // level
String aPath = result[1]; // path
int numCoins = Integer.parseInt(result[2]); // number of coins

creating JFrame with variable amount of JLabels

I am currently trying to make a JFrame which should contain one String followed by a text entry field for each entry in a HashMap (longToShortNamesMap). Currently I am displaying the entries as follws in a JOptionPane:
String paneMessage = "";
List keys = new ArrayList(longToShortNameMap.keySet());
for(int i = 0 ; i < keys.size();i++){
paneMessage += "Field name " + keys.get(i) + " has been shortened to " + longToShortNameMap.get(keys.get(i)) + "\n";
}
JOptionPane.showMessageDialog (null, paneMessage, "Data Changed", JOptionPane.INFORMATION_MESSAGE);
Instead, I would like a frame to appear which will have the same message appear but will have the "longToShortNameMap.get(keys.get(i))" part appear in an editable text field. I'm not quite sure how ot go about this but this is what I have so far which is popping one JFrame with one label (which is not an editable text field).
private static void showFrames(Map<String,String> longToShortNameMap) {
JFrame frame = new JFrame("Data Changed");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(400, 500);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel(new BorderLayout());
List<String> keys = new ArrayList(longToShortNameMap.keySet());
for (String key : keys) {
JLabel label = new JLabel(longToShortNameMap.get(key));
panel.add(label);
}
frame.add(panel);
}
EDIT: As a contextual side note, I am doing this because field names are limited to 10 characters in a place in my application so I am forced to trim the field names down to 10 characters. When I do this, I want to notify the user what each trimmed field has been trimmed to and additionally give them the option to change the trimmed named
Your main issue is your choice of layout manager. BorderLayout allows one component in each of its 5 areas. When you're adding your labels to the center area (the default), you keep replacing the last one instead of appending it. I recommend adding each label and JTextField (your editable field) to a GridLayout panel.
private static void showFrames(Map<String,String> longToShortNameMap) {
JFrame frame = new JFrame("Data Changed");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(400, 500);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel(new GridLayout(0, 2)); //use gridlayout
List<String> keys = new ArrayList(longToShortNameMap.keySet());
for (String key : keys) {
JLabel label = new JLabel(key); // your label is the key itself
JTextField textField = new JTextField(longToShortNameMap.get(key));
panel.add(label); // Populate textfield with the key's value
panel.add(textField);
}
frame.add(panel);
}

How to set the Radio Button based on the value fetched from the database

I have a JTable filled with data about students (student id, name...), and when I select a row from a table, the form opens and its field need to be filled with same values (eg. if Johny Bravo was selected from the table.
Then his name should be shown in text filed Name on the form, I did like this txtfieldName.setText(student.getName).
My question is how do I set my Radio button automatically (my radio button is Male or Female) when I clicked the field.
enter code here
tableGuest.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try{
int row = tableGuest.getSelectedRow();
String guestEdit=(tableGuest.getModel().getValueAt(row, 0).toString());
String query = "Select guest_id,guest_fname,guest_lname,guest_contact,guest_age,guest_gender,guest_address,guest_email from guest_tbl where guest_id= '"+guestEdit+"'";
PreparedStatement pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery();
buttonGroupEdit.add(rdbtnMaleEdit);
buttonGroupEdit.add(rdbtnFemaleEdit);
while(rs.next())
{
String genderEdit=rs.getString("guest_gender");
if(genderEdit.equals("Male"))
{
rdbtnMaleEdit.setSelected(true);
}
else if(genderEdit.equals("Female"))
{
rdbtnFemaleEdit.setSelected(true);
}
else
{
JOptionPane.showMessageDialog(null, "error !");
}
tfEditFname.setText(rs.getString("guest_fname"));
tfEditLname.setText(rs.getString("guest_lname"));
tfEditEmail.setText(rs.getString("guest_email"));
tfEditContact.setText(rs.getString("guest_contact"))
}
pst.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
});
String gender = "male"
// this comes from db - since we don't know the structure this is a plain guess.
if (gender.equals("male") {
rbtMale.setSelected(true);
} else {
rbtFemale.setSelected(true);
}
And like MadProgrammer said, you will need a ButtonGroup and add all relevant buttons to it.
private final ButtonGroup genderButtons = new ButtonGroup();
genderButtons.add(rbtMale);
genderButtons.add(rbtFemale);
I've worked with same kinda solution in my work I am generating radiobutton with database values and showing them in java dialog.
We have a values from database stored in list like below:
List Titles; //This is a list containing your database values
First count the values of this list elements:
int list_count=Titles.size();
Now to proceed with radio function first we need to convert list elements into array like below:
String[] col = new String[list_count]; //created an array with limit of list count values
for(int i=0; i < list_count; i++){
col[i]=Titles.get(i).toString(); // add values of list into array with loop
}
Below is the function that is creating radio buttons with database array we created above:
public String get_key(int list_count, String[] col){
JRadioButton jb[] = new JRadioButton[col.length]; //Create Radion button array
ButtonGroup rb = new ButtonGroup(); //Group Radio Button
JPanel panel = new JPanel( new GridLayout(0, 1) ); //Set layout of radion button to display each after other
JScrollPane sp = new JScrollPane(panel); // Create a scrollpane to put all these radio button on that
GridBagLayout gridbag = new GridBagLayout(); //Layout for scrollpane
sp.setViewportBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); //bordre for scrollpane
List<Component> q = new ArrayList<>(); // q is a component to store and display each radio button
JLabel h1=new JLabel("Select a value"); //put a heading on top of jpanel before radio button
h1.setFont(new Font("Serif", Font.BOLD, 18)); // set heading text
panel.add(h1); //add heading on top of jpanel
panel.setBorder(new EmptyBorder(10, 10, 10, 10)); //set panel border to padding each radio button
for(int i=0; i < list_count; i++){
jb[i]=new JRadioButton(col[i]); //create radion button dynamacially "col[i]" is the value of each radio
rb.add(jb[i]); //it is important also to put all radio in a group we created so only one element should be selected
panel.add(jb[i]); // add all radio on jpanel
}
sp.setPreferredSize( new Dimension( 350, 300 ) ); //set size of scrollpane
int act=JOptionPane.showConfirmDialog(null, sp, "Select Primary Key",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE); //add and show scrollpane in dialog
}
Calling this function with parameter values we created first "list_count" & "col":
get_key(list_count, col);
Create a Student.java class to get particular table value from database.
In the current form AddStudent create a function call as getStudentList to fill the GUI form with database data to particular id.
public ArrayList<Student> getStudentList() {
ArrayList<Student> studentList = new ArrayList<>();
conn = DbConnection.ConnectDb();
String selectQuery = "SELECT * FROM student";
try {
PreparedStatement pst = conn.prepareStatement();
ResultSet rs = pst.executeQuery();
Donor donor;
while(rs.next()) {
student = new Student(rs.getString("id"),
rs.getString("gender"));
studentList.add(student);
}
} catch (SQLException ex) {
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
return studentList;
}
After create a function called showStudent to show the particular data value to called id.(In below code male,female are the checkbox values)
public void showStudent(int index) throws ParseException {
if(getStudentList().get(index).getGender().equals("male")) {
male.setSelected(true);
female.setSelected(false);
gender = "male";
}
else {
female.setSelected(true);
male.setSelected(false);
gender = "female";
}
}
Set action to the jbutton, When get value id from jtextfield then fill the checkbox in particular gender value.

Printing all content of a JList as output

I have a JList in my GUI, which uses an ArrayList as data:
ArrayList Cruise = new ArrayList();
Cruise.add("Scottish to Greek Waters");
Cruise.add("Greek to Scottish Waters");
JScrollPane scrollPane = new JScrollPane();
CruiseList = new JList(Cruise.toArray());
CruiseList.setPreferredSize(new Dimension(200, 200));
scrollPane.setViewportView(CruiseList);
CruiseList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
CruiseList.setSelectedIndex(0);
CruiseList.setVisibleRowCount(6);
listPanel.add(scrollPane);
Frame1.setVisible(true);
I have a button - List all Cruises, which once clicked on should display this as output:
"Scottish to Greek Waters"
"Greek to Scottish Waters"
However, upon clicking the button, it only displays the selected list option as output.
This is what I have so far:
listallCruises.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String AllCruises = CruiseList.getSelectedValue().toString();
System.out.print("All Cruises:\n" + AllCruises + CruiseList.getModel() + "\n");
}
});
How do I print out all element in the list upon clicking the button?
You are outputting just the selected value because that's the method you are calling, getSelectedValue().
To display ALL the values, you have to get the model and iterate through the values, like so:
int size = CruiseList.getModel().getSize();
StringBuilder allCruises = new StringBuilder("All cruises:");
for(int i = 0; i < size; i++) {
allCruises.append("\n").append(CruiseList.getModel().getElementAt(i));
}
System.out.print(allCruises);

Using a textbox for input for a JList

Okay I know this has got to be something very simple I am trying to do but I am pulling my hair out trying to figure it out. I have a GUI with three text boxes and one JList I am trying to add to the list. Here is my addButton code below:
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String emailText = custEmailTextBox.getText();
String firstText = firstNameTextBox.getText();
String lastText = lastNameTextBox.getText();
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement(firstText + " : " + lastText + " : " + emailText);
custList.setModel(model);
}
I can add text to my list but if I try to add a second line of text it just overwrites the first one. How can I just add to the list with out overwriting the other?
I can add text to my jlist box but if I try to add a second line of
text it just overwrites the first one.
Because, each time your are adding a text to JList you are creating new DefaultListModel and setting that model to the JList which removes the already added texts in JList. To overcome this problem create the object of DefaultListModel once outside the addButtonActionPerformed method.Also set the model for JList once. Your code should be something like this:
DefaultListModel<String> model = new DefaultListModel<>();
private void someMethod() //call this method in your constructor or method where you have initialized your GUI
{
custList.setModel(model);
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
String emailText = custEmailTextBox.getText();
String firstText = firstNameTextBox.getText();
String lastText = lastNameTextBox.getText();
model.addElement(firstText + " : " + lastText + " : " + emailText);
}
By default a JList will use a DefaultListModel.
Cast the JList model via list.getModel(), and just remove your setModel method call which resets the list data.

Categories