Can I add a Table inside of a JTabbedPane? - java

I'm very new at using JPanels/Tabs and so have run into a bunch of issues with my code.
I've created a table from SQL that I want to be able to be viewed inside of a tab.
So I have a class first of all that includes a login and then takes you to a window with three tabs:
public class UserInterface
{
UserInterface() {
JFrame frame = new JFrame(); //create a frame
frame.setTitle("Bet Worthiness"); //sets title of frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //system exit when user closes window
frame.setResizable(false); //prevents user from resizing frame
JTextField text = new JTextField(10); //creates a text box
frame.getContentPane().setBackground(new Color(255, 243, 181)); //background colour
//Create panels
JPanel accountTab = new JPanel();
JPanel bettingTab = new JPanel();
JPanel leaderboardTab = new JPanel();
JTabbedPane tabs = new JTabbedPane(); //Create the tab container
tabs.setBounds(40, 20, 1400, 700); //Set tab container position
//Account Details label
JLabel accountLabel = new JLabel();
accountLabel.setText("Account Details");
accountLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
accountTab.add(accountLabel);
//Betting label
JLabel bettingLabel = new JLabel();
bettingLabel.setText("Place Bets");
bettingLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
bettingTab.add(bettingLabel);
//Leaderboard label
JLabel leaderboardLabel = new JLabel();
leaderboardLabel.setText("Leaderboard");
leaderboardLabel.setFont(new Font("Helvetica", Font.BOLD, 20));
leaderboardTab.add(leaderboardLabel);
//Associate each panel with the corresponding tab
tabs.add("Account", accountTab);
tabs.add("Betting", bettingTab);
tabs.add("Leaderboard", leaderboardTab);
frame.add(tabs); //Add tabs to the frame
frame.setSize(1500, 800);
frame.setLayout(null);
frame.setVisible(true);
}
}
I have then created a table on SQL in a separate class that I want to be embedded in the 'leaderboard' tab:
public class Leaderboard extends JFrame {
public void displayLeaderboard() {
try
{
String url = "jdbc:mysql://localhost:3306/bettingappdb";
String user = "root";
String password = "lucyb";
Connection con = DriverManager.getConnection(url, user, password);
String query = "SELECT * FROM users";
Statement stm = con.createStatement();
ResultSet res = stm.executeQuery(query);
String columns[] = { "Username", "Success Rate" };
String data[][] = new String[20][3];
int i = 0;
while (res.next()) {
String nom = res.getString("Username");
int successRate = res.getInt("SuccessRate");
data[i][0] = nom;
data[i][1] = successRate + "";
i++;
}
DefaultTableModel model = new DefaultTableModel(data, columns);
JTable table = new JTable(model);
table.setShowGrid(true);
table.setShowVerticalLines(true);
JScrollPane pane = new JScrollPane(table);
JFrame f = new JFrame("Leaderboard");
JPanel panel = new JPanel();
panel.add(pane);
f.add(panel);
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
} catch(SQLException e) {
e.printStackTrace();
}
}
}
Is there any way to put this table within the tab? Thank you :)

You could add the following to your Code.
JPanel lbTab = new JPanel();
Leaderboard leaderboard = new Leaderboard();
lbTab.add(leaderboard);
the Leaderboard is now in your JTabbedPane. If you want to add the Leaderboard as well as the leaderboardLabel in one Tab i suggest something like https://docs.oracle.com/javase/tutorial/uiswing/components/panel.html or How to layout? (JFrame, JPanel, etc.) for your first steps :) .

Related

JDialog is not showing up

I have this problem over and over again when i call my JDialog class is not showing anything this is the code for the JDialog interface:
public JMovie() {
JFrame f = new JFrame();
JDialog jmovie = new JDialog(f,"JMovie Dialog");
jmovie.setLayout(new BorderLayout());
okbutton = new JButton("Ok");
cancelbutton = new JButton("Cancel");
title = new JLabel("Title", SwingConstants.RIGHT);
date = new JLabel("Date made on ", SwingConstants.RIGHT);
price = new JLabel("Price", SwingConstants.RIGHT);
inputdate = new JLabel("dd/mm/yyyy");
Ttitle = new JTextField(null, 15);
TMadeon = new JTextField(null, 10);
TPrice = new JTextField(null, 6);
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jb = new JPanel();
jl = new JPanel();
okbutton.addActionListener(this);
cancelbutton.addActionListener(this);
Ttitle.setName("Title");
TMadeon.setName("Date Made on");
TPrice.setName("Price");
jb.add(okbutton);
jb.add(cancelbutton);
title.setAlignmentX(Component.RIGHT_ALIGNMENT);
date.setAlignmentX(Component.RIGHT_ALIGNMENT);
price.setAlignmentX(Component.RIGHT_ALIGNMENT);
JPanel south = new JPanel(new FlowLayout());
south.add(jb, BorderLayout.SOUTH);
JPanel west = new JPanel(new GridLayout(3,1));
west.add(title,BorderLayout.WEST);
west.add(date,BorderLayout.WEST);
west.add(price,BorderLayout.WEST);
JPanel center = new JPanel(new GridLayout(3,1));
center.add(jp3,FlowLayout.LEFT);
center.add(jp2,FlowLayout.LEFT);
center.add(jp1,FlowLayout.LEFT);
inputdate.setEnabled(false);
jmovie.setSize(350, 150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
}
This is the code of the interface JMovie DIalog and i call it here in another class.
public void actionPerformed(ActionEvent event) {
if(event.getSource().equals(btnMAdd))
{
JMovie ne = new JMovie();
ne.setVisible(true);
}
}
when i run it is showing this:
First of all, variable names should NOT start with an upper case character. Some variables are correct, others are not. Follow Java conventions and be consistent!
jmovie.setSize(350, 150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
Component should be added to the dialog BEFORE the dialog is made visible.
So the code should be:
jmovie.add(south);
jmovie.add(west);
jmovie.add(center);
jmovie.setSize(350, 150);
jmovie.setLocation(300,300);
jmovie.setVisible(true);
You should be using pack() instead of setVisible(...). This will allow all the components to be displayed at their preferred size.
JFrame f = new JFrame();
Also, you should not be create a JFrame. The parameter you want to pass to the JDialog, is the current visible JFrame.
So in your ActionListener you can get the current frame with logic like:
Window window = SwingUtilities.windowForComponent( btnMAdd );
Now when you create your dialog you pass the window as a parameter:
JMovie ne = new JMovie(window);
and you use this value to specify the parent window of your dialog.

refresh a JLabel

This is as the title says, I need your help to refresh the contents of a JLabel.
I explain my worries.
I have a first JFarm or I have a calendar (a DatePicker) which allows me to select a date and a button.
When I click on the button it opens a new window and in this famous window I have my JLabel or I would like to see my date.
In this last window I wrote:
System.out.println(datePicker.getDate());
labelDate.setText(datePicker.getDate());
When I first open my window everything works fine, but if I close it, I change the date in my DatePicker and reopen the window by clicking on my button the date does not change !!!
It always remains on the first date sent.
Yet my:
System.out.println(datePicker.getDate());
Returns the correct date correctly each time.
Do you have an idea ?
Thank you all.
I post my full code but it's very long and not very clean... sorry.
the main window :
public class App extends JFrame{
private JPanel contentPane;
static final int rowMultiplier = 4;
private DatePicker datePicker;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App frame = new App();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() throws SQLException{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
this.setTitle("Absences Management");
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
// =================== PanelTitle ===================================
JPanel panelTitle = new JPanel();
contentPane.add(panelTitle, BorderLayout.NORTH);
JLabel labelTitle = new JLabel("Absence Management");
panelTitle.add(labelTitle);
// ================== PanelMenu =====================================
JPanel panelMenu = new JPanel();
contentPane.add(panelMenu, BorderLayout.WEST);
panelMenu.setLayout(new BoxLayout(panelMenu, BoxLayout.Y_AXIS));
// Border and name for the panel
panelMenu.setBorder(BorderFactory.createTitledBorder(" Menu "));
// create buttons and set the actions for the menu
JButton buttonAddClass = new JButton(new ActionButtonClassManagement(this,"Class management"));
JButton buttonQuit = new JButton(new ActionButtonQuit(this," Quit "));
// add different components in the Panel Menu
panelMenu.add(buttonAddClass);
panelMenu.add(buttonQuit);
// ================= PanelCalendar ==================================
JPanel panelCalendar = new JPanel();
contentPane.add(panelCalendar, BorderLayout.CENTER);
panelCalendar.setAlignmentX(CENTER_ALIGNMENT);
// black border for the panel
panelCalendar.setBorder(BorderFactory.createTitledBorder(" Calendar "));
JLabel labelCalendar = new JLabel("CALENDAR :");
panelCalendar.add(labelCalendar);
// ===== create the calendar
// settings
DatePickerSettings dateSettings = new DatePickerSettings();
dateSettings.setVisibleClearButton(false);
// set the current date by default
dateSettings.setAllowEmptyDates(false);
datePicker = new DatePicker(dateSettings);
// create a icon
URL dateImageURL = FullDemo.class.getResource("/img/calendar20x20.png");
Image calendarImage = Toolkit.getDefaultToolkit().getImage(dateImageURL);
ImageIcon calendarIcon = new ImageIcon(calendarImage);
// create button and set the icon
JButton datePickerButton = datePicker.getComponentToggleCalendarButton();
datePickerButton.setText("");
datePickerButton.setIcon(calendarIcon);
// add the calendar to the PanelCalendar
panelCalendar.add(datePicker);
// create a button Show absences
JButton buttonAbsence = new JButton(new ActionButtonAbsences(this,"Absences", datePicker));
//add the button to the panelCalendar
panelCalendar.add(buttonAbsence);
}
}
The class for my button Absence :
public class ActionButtonAbsences extends AbstractAction{
private App windowAbsence;
private DatePicker datePicker = new DatePicker();
private String dateString = new String();
public ActionButtonAbsences(App app, String textButton, DatePicker datePicker) {
// TODO Auto-generated constructor stub
super(textButton);
this.datePicker = datePicker;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
dateString = datePicker.getText();
WindowAbsence fen = new WindowAbsence(windowAbsence, datePicker, dateString);
}
}
And the window that opens when I press the button Absence :
public class WindowAbsence extends JDialog implements ActionListener{
private static JPanel panelWindow = new JPanel(new BorderLayout());
private JPanel panelTitle = new JPanel();
private JPanel panelWindowLeft = new JPanel();
private JPanel panelWindowRight = new JPanel();
private JComboBox comboBoxClass;
private JComboBox comboBoxStudent;
private DatePicker datePicker;
private JLabel labelDate = new JLabel();
private String dateString = new String();
private ModelTable modelTableAbsence = new ModelTable();
private JTable tableAbsence = new JTable(modelTableAbsence);
public WindowAbsence(Frame frame, DatePicker datePicker, String date){
//super call the constructor of the main window
// the first argument is the mother window
// the second argument disable this window
super(frame,true);
labelDate.setText(datePicker.getText());
this.dateString = date;
// add BorderLayout in this Window
this.setLayout(new BorderLayout());
// name of the window
this.setTitle("Absences");
// size of the window
this.setSize(700, 600);
// effect for the red cross
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.datePicker = datePicker;
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// ================== PANEL TITLE ==================================
//JLabel labelDate = new JLabel();
panelTitle.add(labelDate);
//labelDate.setText(datePicker.getText());
date = datePicker.getText();
System.out.println("date: "+date);
labelDate.setText(date);
panelWindow.add(panelTitle, BorderLayout.NORTH);
// ================ PANEL LEFT =====================================
panelWindowLeft.setBorder(BorderFactory.createTitledBorder(" Absences "));
// =========== panelComboBoxLabelClass ======================
JPanel panelLabelComboBoxClass = new JPanel();
panelLabelComboBoxClass.setLayout(new BoxLayout(panelLabelComboBoxClass, BoxLayout.LINE_AXIS));
JLabel labelComboBoxClass = new JLabel("Class :");
comboBoxClass = new JComboBox();
comboBoxClass.addItem("");
panelLabelComboBoxClass.add(labelComboBoxClass);
panelLabelComboBoxClass.add(comboBoxClass);
Statement statementClass = DataBase.connection.createStatement();
ResultSet resultClass = statementClass.executeQuery("SELECT class FROM Class");
//receive the MetaData
ResultSetMetaData resultMetaClass = (ResultSetMetaData) resultClass.getMetaData();
// add the data in the row
while(resultClass.next()){
comboBoxClass.addItem(resultClass.getObject(1));
}
comboBoxClass.addActionListener(this);
resultClass.close();
statementClass.close();
// =========== panelComboBoxLabelStudent ======================
JPanel panelLabelComboBoxStudent = new JPanel();
panelLabelComboBoxStudent.setLayout(new BoxLayout(panelLabelComboBoxStudent, BoxLayout.LINE_AXIS));
JLabel labelComboBoxStudent = new JLabel("Student :");
comboBoxStudent = new JComboBox();
panelLabelComboBoxStudent.add(labelComboBoxStudent);
panelLabelComboBoxStudent.add(comboBoxStudent);
// ========== panelComboBoxHour ===============================
int rowMultiplier = 4;
int row = rowMultiplier;
TimePickerSettings timeSettings = new TimePickerSettings();
timeSettings.setDisplayToggleTimeMenuButton(true);
timeSettings.setDisplaySpinnerButtons(false);
JPanel panelComboBoxHour = new JPanel();
panelComboBoxHour.setLayout(new BoxLayout(panelComboBoxHour, BoxLayout.LINE_AXIS));
JLabel labelComboBoxFrom = new JLabel("From :");
panelComboBoxHour.add(labelComboBoxFrom);
TimePicker timePickerFrom = new TimePicker(timeSettings);
timePickerFrom = new TimePicker();
panelComboBoxHour.add(timePickerFrom, getConstraints(1, (row * rowMultiplier), 1));
//panelComboBoxHour.addLabel(panelComboBoxHour, 1, (row++ * rowMultiplier), "Time 1, Default Settings:");
JLabel labelComboBoxTo = new JLabel("To :");
panelComboBoxHour.add(labelComboBoxTo);
TimePicker timePickerTo = new TimePicker();
timePickerTo = new TimePicker();
panelComboBoxHour.add(timePickerTo, getConstraints(1, (row * rowMultiplier), 1));
// ========== panel button add absence ==============
JPanel panelButtonAddAbsence = new JPanel();
panelButtonAddAbsence.setLayout(new BoxLayout(panelButtonAddAbsence, BoxLayout.LINE_AXIS));
JButton buttonAddAbsence = new JButton("Add Absence");
panelButtonAddAbsence.add(buttonAddAbsence);
// ========================================
panelWindowLeft.setLayout(new BoxLayout(panelWindowLeft, BoxLayout.PAGE_AXIS));
panelWindowLeft.add(panelLabelComboBoxClass);
panelWindowLeft.add(panelLabelComboBoxStudent);
panelWindowLeft.add(panelComboBoxHour);
panelWindowLeft.add(panelButtonAddAbsence);
panelWindow.add(panelWindowLeft, BorderLayout.WEST);
// ====================== PANEL RIGHT ================================
panelWindowRight.setBorder(BorderFactory.createTitledBorder(" Absences "));
//=================== TABLE =======================================
Statement statementAbsence = DataBase.connection.createStatement();
// requet SQL
ResultSet resultAbsence;
ResultSetMetaData resultMetaAbsence;
modelTableAbsence.addColumn("Student");
modelTableAbsence.addColumn("Date");
modelTableAbsence.addColumn("To");
modelTableAbsence.addColumn("From");
// requete SQL
resultAbsence = statementAbsence.executeQuery("SELECT * FROM Absence WHERE `dateAbsence`='"+datePicker.getDate().toString()+"'");
//receive the MetaData
resultMetaAbsence = (ResultSetMetaData) resultAbsence.getMetaData();
modelTableAbsence.fireTableDataChanged();
if(!resultAbsence.next()){
System.out.println("null");
}else{
// add the data in the row
do{
modelTableAbsence.addRow(new Object[]{
resultAbsence.getObject(2).toString(),
resultAbsence.getObject(3).toString(),
resultAbsence.getObject(4).toString(),
resultAbsence.getObject(5).toString()
});
}while(resultAbsence.next());
// close the statementClass
statementAbsence.close();
resultAbsence.close();
// ========= replace id student by firstName and lastName
Statement statementNameStudent = DataBase.connection.createStatement();
ResultSet resultNameStudent = null;
int nbRow = modelTableAbsence.getRowCount();
for(int i = 0; i < nbRow; i++){
resultNameStudent = statementNameStudent.executeQuery("SELECT firstName, lastName FROM Student WHERE `id`='"+modelTableAbsence.getValueAt((i), 0)+"'");
// add the data in the row
while(resultNameStudent.next()){
modelTableAbsence.setValueAt(
(resultNameStudent.getObject(1)+" "+resultNameStudent.getObject(2)),i,0);
}
}
statementNameStudent.close();
resultNameStudent.close();
}
// =================================================================
JScrollPane scrollPane = new JScrollPane(tableAbsence);
panelWindowRight.add(scrollPane);
panelWindow.add(panelWindowRight, BorderLayout.CENTER);
this.setContentPane(panelWindow);
this.setVisible(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static GridBagConstraints getConstraints(int gridx, int gridy, int gridwidth) {
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.WEST;
gc.gridx = gridx;
gc.gridy = gridy;
gc.gridwidth = gridwidth;
return gc;
}
// model table for table schedule
public class ModelTableSchedule extends DefaultTableModel {
ModelTableSchedule(Object[][] dataStudent, String[] columnNamesStudent) {
super(dataStudent, columnNamesStudent);
}
// the function return always false, the table is never editable
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
public void actionPerformed(ActionEvent arg0) {
modelTableAbsence.fireTableDataChanged();
// =================== Data bases connection ============================
/**
* download mysql-connector-java-5.1.40.tar.gz
* https://dev.mysql.com/downloads/file/?id=470332
* Clic droit sur le dossier du projet
* Clic right on the folder of the project
* Build Path
* Add external Archive
*/
DataBase database = new DataBase();
String url = "jdbc:mysql://localhost:3306/AbsenceManagement";
String user = "root";
String pass = "";
String driver = "com.mysql.jdbc.Driver";
try {
database.connectionDataBase(url, user, pass, driver);
// add value in ComboBox
Statement statementStudent;
comboBoxStudent.removeAllItems();
statementStudent = DataBase.connection.createStatement();
ResultSet resultStudent = statementStudent.executeQuery("SELECT * FROM `Student` WHERE `class` LIKE '"+comboBoxClass.getSelectedItem().toString()+"'");
//receive the MetaData
ResultSetMetaData resultMetaStudent = (ResultSetMetaData) resultStudent.getMetaData();
// add the data in the row
while(resultStudent.next()){
comboBoxStudent.addItem((resultStudent.getObject(2)+" "+resultStudent.getObject(3)));
}
comboBoxStudent.revalidate();
resultStudent.close();
statementStudent.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thank you for your help.
Again me,
I found my error !
In my WindowAbsence :
private static JPanel panelWindow = new JPanel(new BorderLayout());
The panel it was in static...
i hope will serve for someone !

access input that get from user in UI in java and show them in console

i want save input that i get from user and save them in element .
i want to access elements that user write in my UI.
and if i want save the elements in array list which kind of array list i should build.
in my UI i have text field name and text field middle name and combo box city has got 3 city name and and a radio box that it depend sex.
in final show them in console what should i do ?
this all of my code:
package ui;
import java.awt.*;
import javax.swing.*;
public class UI extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(500, 600);
BorderLayout blayout = new BorderLayout();
JButton center = new JButton();
JButton north = new JButton();
JButton south = new JButton();
JComboBox combo = new JComboBox();
combo.addItem("-");
combo.addItem("Tehran");
combo.addItem("Tabriz");
combo.addItem("Shiraz");
JRadioButton rb1 = new JRadioButton("man");
JRadioButton rb2 = new JRadioButton("weman");
frame.setLayout(blayout);
FlowLayout fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
JLabel jb1 = new JLabel("Name :");
JTextField name = new JTextField(20);
center.add(jb1);
center.add(name);
JLabel jb2 = new JLabel("Family :");
JTextField family = new JTextField(20);
center.add(jb2);
center.add(family);
JLabel jb4 = new JLabel("City :");
center.add(jb4);
center.add(combo);
JLabel jb5 = new JLabel("Sex :");
center.add(jb5);
center.add(rb1);
center.add(rb2);
JLabel jb6 = new JLabel("Comment :");
JTextField comment = new JTextField(50);
JLabel jb7 = new JLabel("Save");
south.add(jb7);
JPanel cpanel = new JPanel();
cpanel.add(center);
JPanel spanel = new JPanel();
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
cpanel.add(jb6);
cpanel.add(comment);
frame.add(cpanel,BorderLayout.CENTER);
frame.add(spanel,BorderLayout.SOUTH);
}
}
You need to use listeners to create code that runs when ui component is pressed. I added listener to every component. try it:
public class UI extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout blayout = new BorderLayout();
JButton center = new JButton();
JButton north = new JButton();
JButton south = new JButton();
south.addActionListener(e->{System.out.println("Save button is pressed");});
JComboBox combo = new JComboBox();
combo.addItem("-");
combo.addItem("Tehran");
combo.addItem("Tabriz");
combo.addItem("Shiraz");
combo.addActionListener(e -> {
System.out.println(((JComboBox<String>) e.getSource()).getSelectedItem());
});
JRadioButton rb1 = new JRadioButton("man");
rb1.addActionListener(e -> {
System.out.println("man: " + ((JRadioButton) e.getSource()).isSelected());
});
JRadioButton rb2 = new JRadioButton("weman");
rb2.addActionListener(e -> {
System.out.println("weman: " + ((JRadioButton) e.getSource()).isSelected());
});
frame.setLayout(blayout);
FlowLayout fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
JLabel jb1 = new JLabel("Name :");
JTextField name = new JTextField(20);
center.add(jb1);
center.add(name);
name.addActionListener(e -> {
System.out.println("name: " + ((JTextField) e.getSource()).getText());
});
JLabel jb2 = new JLabel("Family :");
JTextField family = new JTextField(20);
center.add(jb2);
center.add(family);
family.addActionListener(e -> {
System.out.println("family: " + ((JTextField) e.getSource()).getText());
});
JLabel jb4 = new JLabel("City :");
center.add(jb4);
center.add(combo);
JLabel jb5 = new JLabel("Sex :");
center.add(jb5);
center.add(rb1);
center.add(rb2);
JLabel jb6 = new JLabel("Comment :");
JTextField comment = new JTextField(50);
comment.addActionListener(e -> {
System.out.println("comment: " + ((JTextField) e.getSource()).getText());
});
JLabel jb7 = new JLabel("Save");
south.add(jb7);
JPanel cpanel = new JPanel();
cpanel.add(center);
JPanel spanel = new JPanel();
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
cpanel.add(jb6);
cpanel.add(comment);
frame.add(cpanel, BorderLayout.CENTER);
frame.add(spanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
}
You will have to put JRadioButton into RadioGroup to select one of them.
At first, you need to check your GUI, because from skimming it works not good. Later you can get data from the different component using an appropriate listener for each component or you can use any General button to reading data from all components and print it in a console or anywhere else.
To get data from combo, for example, will be here:
String data = combo.getSelectedIndex();
More information you can get here:
How can I get the user input in Java?

JFrame Window not showing any content unless resized

I have an Interface class that extends JFrame. I am creating 3 JPanels and adding them to a Container (Border Layout) in different areas of the layout.
When I run the application, nothing shows but a blank window and a title. If I resize the application it will then show all the content and work as intended.
I'm not sure what I did differently this time, I've used this method before and it works in previous programs.
Any help is appreciated.
Here is my Interface Class Constructor code: http://pastebin.com/4UyEXsBr
Code:
public class Interface extends JFrame implements ActionListener {
private Container contentPane;
private JPanel buttonPanel, userPanel;
private JButton loginButton, createUserButton, logoutButton, withdrawButton, depositButton, switchToRegisterButton, switchToLoginButton;
private JLabel headerLabel, inputTopJTFLabel, inputPW1JPFLabel, toastLabel, inputPW2JPFLabel;
public JTextField inputTopJTF;
public JPasswordField inputPW1JPF, inputPW2JPF;
JRootPane rootPane;
public Interface(int width, int height, String title) {
//Setting up Interface
setTitle(title);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100,100);
setVisible(true);
Font header = new Font("TimesRoman", Font.PLAIN, 50);
///////////////////////BUTTON PANEL///////////////////////
//Button Panel
buttonPanel = new JPanel();
//Buttons
//loginButton
loginButton = new JButton("Login");
loginButton.addActionListener(this);
loginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
//switchToRegisterButton
switchToRegisterButton = new JButton("New User?");
switchToRegisterButton.addActionListener(this);
switchToRegisterButton.setAlignmentX(Component.CENTER_ALIGNMENT);
//switchToLoginButton
switchToLoginButton = new JButton("Switch to Login");
switchToLoginButton.addActionListener(this);
switchToLoginButton.setAlignmentX(Component.CENTER_ALIGNMENT);
switchToLoginButton.setVisible(false);
//createUserButton
createUserButton = new JButton("Register");
createUserButton.addActionListener(this);
createUserButton.setAlignmentX(Component.CENTER_ALIGNMENT);
createUserButton.setVisible(false);
//logoutButton
logoutButton = new JButton("Logout");
logoutButton.addActionListener(this);
logoutButton.setAlignmentX(Component.CENTER_ALIGNMENT);
logoutButton.setVisible(false);
//withdrawButton
withdrawButton = new JButton("Withdraw");
withdrawButton.addActionListener(this);
withdrawButton.setAlignmentX(Component.CENTER_ALIGNMENT);
withdrawButton.setVisible(false);
//depositButton
depositButton = new JButton("Deposit");
depositButton.addActionListener(this);
depositButton.setAlignmentX(Component.CENTER_ALIGNMENT);
depositButton.setVisible(false);
//Adding items to buttonPanel
buttonPanel.add(loginButton);
buttonPanel.add(switchToRegisterButton);
buttonPanel.add(switchToLoginButton);
buttonPanel.add(createUserButton);
buttonPanel.add(logoutButton);
buttonPanel.add(withdrawButton);
buttonPanel.add(depositButton);
///////////////BODY PANEL//////////////////////
//Body Panel
userPanel = new JPanel();
userPanel.setLayout(new BoxLayout(userPanel, BoxLayout.PAGE_AXIS));
//JTextFields
//inputTopJTF
Dimension inputTopJTFDimension = new Dimension(100, 20);
inputTopJTF = new JTextField();
inputTopJTF.setMaximumSize(inputTopJTFDimension);
//inputPW1JPF
Dimension inputPW1JPFDimension = new Dimension(100, 20);
inputPW1JPF = new JPasswordField();
inputPW1JPF.setMaximumSize(inputPW1JPFDimension);
//inputPW2JPF
Dimension inputPW2JPFDimension = new Dimension(100, 20);
inputPW2JPF = new JPasswordField();
inputPW2JPF.setMaximumSize(inputPW2JPFDimension);
inputPW2JPF.setVisible(false);
//JLabels
//toastLabel
toastLabel = new JLabel("Please sign in or create new account.");
toastLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputTopJTFLabel
inputTopJTFLabel = new JLabel("Username:");
inputTopJTFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputPW1JPFLabel
inputPW1JPFLabel = new JLabel("Password:");
inputPW1JPFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
//inputPW2JPFLabel
inputPW2JPFLabel = new JLabel("Confirm Password:");
inputPW2JPFLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
inputPW2JPFLabel.setVisible(false);
//Adding items to userPanel
userPanel.add(toastLabel);
userPanel.add(inputTopJTFLabel);
userPanel.add(inputTopJTF);
userPanel.add(inputPW1JPFLabel);
userPanel.add(inputPW1JPF);
userPanel.add(inputPW2JPFLabel);
userPanel.add(inputPW2JPF);
///////////////CONTENT PANE/////////////////////
//Content Pane
contentPane = getContentPane();
//JLabels
//headerLabel
headerLabel = new JLabel("Bank", SwingConstants.CENTER);
headerLabel.setFont(header);
//PAGE_START
contentPane.add(headerLabel, BorderLayout.PAGE_START);
//LINE_START
//CENTER
contentPane.add(userPanel, BorderLayout.CENTER);
//LINE_END
//PAGE_END
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
userPanel.setFocusable(true);
userPanel.requestFocus();
//Default Button
rootPane = getRootPane();
rootPane.setDefaultButton(loginButton);
}
call
setVisible(true);
in last line .because component added after line setvisible will not be shown until you call repaint(),revalidate().when you resize ,repaint() method get called and frame will visible correctly .so call setvisible after add all component
after line rootPane.setDefaultButton(loginButton); call setvisible
rootPane.setDefaultButton(loginButton);
setVisible(true);//after add all component to frame call setvisible method
this is full working code

Adding a list of images in jscrollpane and show it

I need to add some images in jscrollpane and show the correct image when my jlist string is selected with relative image... but i have some doubt to do it.
public class Tela{
private JList<String> list;
public Tela(){
JFrame display = new JFrame();
display.setTitle("Maquina de Refrigerante");
String labels[] = { "Coca-Cola", "Fanta Laranja", "Fanta-Uva",
"Sprite"};
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel secondPanel = new JPanel();
//downPanel.add(BorderLayout.SOUTH);
//downPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 30, 260));
secondPanel.setBackground(Color.WHITE);
secondPanel.setPreferredSize(new Dimension(110,110));
final JButton comprar = new JButton("Comprar");
comprar.setEnabled(false);
list = new JList<String>(labels);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
list.setSelectedIndex(0);
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
firstPanel.add(pane);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int selections[] = list.getSelectedIndices();
//String selectedValue = list.getSelectedValue();
Object selectionValues[] = list.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
if (i == 0) {
System.out.println("Value" + selectionValues[i] );
}}
comprar.setEnabled(true);
}
});
ImageIcon image = new ImageIcon("assets/fantalogo.jpg");
JScrollPane jsp = new JScrollPane(new JLabel(image));
panel.add(jsp);
buttonPanel.add(comprar);
buttonPanel.add(Box.createRigidArea(new Dimension(0,4)));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panel.add(firstPanel);
panel.add(secondPanel);
panel.add(buttonPanel);
//panel.add(buttonPanel, BorderLayout.CENTER);
panel.setBackground(Color.BLACK);
display.add(panel);
display.setSize(550, 500);
display.setLocationRelativeTo(null);
display.setDefaultCloseOperation(display.EXIT_ON_CLOSE);
display.setVisible(true);
comprar.addActionListener(new Paga());
}
}
in my code how i can implemments it and view the correctly output?
Take a look at the section from the Swing tutorial on How to Use Combo Boxes. You find an example that does almost exactly what you want. The example uses a combo box, but the code for a JList will be very similar. That is the combo box contains a list of Strings and when you select an item the matching image is displayed.

Categories