I added MouseListener to select a particular row from table,the content of row is getting printed on console but I want to print this content on new frame what should I do for this.
I attached my code along with the screenshot of the table.
thanks for help.
This is my code.
final JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
cp.add(scrollPane,BorderLayout.CENTER);
frame.add(cp);
frame.setSize(300,300);
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==1){
JTable target = (JTable)e.getSource();
System.out.println(target);
int row = target.getSelectedRow();
System.out.println(row);
Object [] rowData = new Object[table.getColumnCount()];
Object [] colData = new Object[table.getRowCount()];
for(int j = 0;j < table.getRowCount();j++)
for(int i = 0;i < table.getColumnCount();i++)
{
rowData[i] = table.getValueAt(j, i);
System.out.println(rowData[i]);
}
}
}
});
}
First of all, if you make a graphical interface with swing, you can't use System.out.print.
You need to set every row in a Label and print it out that way. If it is a Label then you can select it with your mouse
In the Mouse Listener method, Call the new JFrame,
in that JFrame , put the Contents of selected Row to Constructor Parameters.
JFrame newframe=new JFrame("Selected Contents);
When you output the result (System.out.println(rowData[i]);) just create a new JFrame and place the text you want to output here :
...
JFrame secondFrame = new JFrame();
JPanel myPanel = new JPanel();
for(int j = 0;j < table.getRowCount();j++){
for(int i = 0;i < table.getColumnCount();i++){
rowData[i] = table.getValueAt(j, i);
JLabel label = new JLabel(rowData[i]);
myPanel.add(label);
}
}
secondFrame.add(myPanel);
secondFrame.setVisible(true);
....
Related
I'm hoping this is an easy question. I have a JComboBox with the choices of 0, 1, 2, 3,...10. Depending on what number is selected in the JComboBox, I want my GUI to add a JLabel and a JTextField. So if the number 3 is chosen, the GUI should add 3 JLabels and 3 JTextFields. and so forth.
I'm using an array of JLabels and JTextFields to accomplish this, but I am getting a null pointer exception at runtime, and no labels or fields are being added.
Code:
private void createComponents()
{
//Create Action Listeners
ActionListener comboListener = new ComboListener();
//Create Components of the GUI
parseButton = new JButton("Parse Files");
parseButton.addActionListener(comboListener);
numberLabel = new JLabel("Number of Files to Parse: ");
String[] comboStrings = { "","1", "2","3","4","5","6","7","8","9","10" };
inputBox = new JComboBox(comboStrings);
inputBox.setSelectedIndex(0);
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(2,10));
centerPanel = new JPanel();
centerPanel.add(numberLabel);
centerPanel.add(inputBox);
totalGUI = new JPanel();
totalGUI.setLayout(new BorderLayout());
totalGUI.add(parseButton, BorderLayout.SOUTH);
totalGUI.add(centerPanel, BorderLayout.CENTER);
add(totalGUI);
}
ActionListener Code:
public void actionPerformed(ActionEvent e)
{
JTextField[] fileField = new JTextField[inputBox.getSelectedIndex()];
JLabel[] fieldLabel = new JLabel[inputBox.getSelectedIndex()];
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i].setText("File "+i+":"); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fieldLabel[i]); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fileField[i]);
}
centerPanel.add(fieldPanel);
repaint();
revalidate();
}
Thanks to MadProgrammer's comment, this question has been answered.
Editing the loop to:
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i] = new JLabel();
fileField[i] = new JTextField();
fieldLabel[i].setText("File "+i+":");
fieldPanel.add(fieldLabel[i]);
fieldPanel.add(fileField[i]);
}
resolved the issue.
I am trying to create GUI like given in first picture, but I am not able to do it.here is the image
I am getting only one combo1, combo2, combo3 and serialNoLabel instead of 5 [5 is the size of list]
ArrayList<String> list; // the size of the list is 5
JComboBox combo1[] = new JComboBox[list.size()];
JComboBox combo2[] = new JComboBox[list.size()];
JComboBox combo3[] = new JComboBox[list.size()];
JLabel SerialNoLabel[] = new JLabel[list.size()];
JPanel masterPanel[] = new JPanel[list.size()];
JDialog masterDialog = new JDialog();
masterDialog.setVisible(true);
masterDialog.setSize(800, 500);
masterDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
masterDialog.setVisible(true);
for(int j =0; j < list.size(); j++) {
masterPanel[j] = new JPanel();
SerialNoLabel[j] = new JLabel(list.get(j));
masterPanel[j].add(SerialNoLabel[j]);
combo1[j] = new JComboBox();
masterPanel[j].add(combo1[j]);
combo2[j] = new JComboBox();
masterPanel[j].add(combo2[j]);
combo3[j] = new JComboBox();
masterPanel[j].add(combo3[j]);
masterDialog.add(masterPanel[j]);
masterDialog.revalidate();
}
I believe it's a layout issue leading your masterPanels to be on top of each other.
So I would do something like this:
JPanel mainPanel = new JPanel();
FlowLayout experimentLayout = new FlowLayout();
mainPanel.setLayout(experimentLayout);
for(int j =0; j < list.size(); j++) {
masterPanel[j] = new JPanel();
SerialNoLabel[j] = new JLabel(list.get(j));
masterPanel[j].add(SerialNoLabel[j]);
combo1[j] = new JComboBox();
masterPanel[j].add(combo1[j]);
combo2[j] = new JComboBox();
masterPanel[j].add(combo2[j]);
combo3[j] = new JComboBox();
mainPanel.add(masterPanel[j]);
}
Of course you could other layouts as well. But I believe you want to go for a FlowLayout. See the documentation about FlowLayout here.
You can learn more about other layouts here
in my code I am calling a few items(my buttons with their names leading to different project. The names and everything are taken from a database)
I want a J ScrollPane to surround my buttons, what can I do? I just want the buttons to be called inside the scroll pane. Here is my code
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AdminClass implements ActionListener {
ProjectButton[] buttons = new ProjectButton[35];
//Creating data field for unique Ids in the form of array list
ArrayList<Integer> uniqueIDList = new ArrayList<Integer>();
String[] projectNames;
int[] uniqueIds;
Connection conn1 = null;
Statement stmt1 = null;
JFrame frame = new JFrame("Admin Panel");
private JPanel panel = new JPanel();
JButton btnNewButton = new JButton("Add New Project");
public AdminClass() {
panel.setLayout(new GridLayout(10, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
conn1 = sqliteConnection.dbConnector();
try{
Class.forName("org.sqlite.JDBC");
conn1.setAutoCommit(false);
stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery( "SELECT * FROM Project;" );
List<String> projectNameList = new ArrayList<String>();
while ( rs1.next() ){
int id = rs1.getInt("uniqueid");
String projectName = rs1.getString("name");
projectNameList.add(projectName);
uniqueIDList.add(id);
}
// Converting array list to array
projectNames = new String[projectNameList.size()];
projectNameList.toArray(projectNames);
uniqueIds = convertIntegers(uniqueIDList);
rs1.close();
stmt1.close();
conn1.close();
}
catch ( Exception e1 ) {
JOptionPane.showMessageDialog(null, e1);
}
// Adding buttons to the project
try{
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttons[i].addActionListener(this);
}
}
catch (Exception e2){
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel);
frame.setVisible(true);
frame.setSize(500, 500);
}
public void actionPerformed(ActionEvent e) {
for (int j = 0; j < buttons.length; j ++){
if (e.getSource() == buttons[j]){
AdminStatus sc = new AdminStatus(buttons[j].getId());
frame.dispose();
}
}
if (e.getSource() == btnNewButton){
frame.dispose();
WindowProjectAdmin wpa = new WindowProjectAdmin();
}
}
//Method to convert integar array list to integar array
public int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
}
This may seem very normal but it's really not, for some reason they are not visible or are not called inside a scroller. Please edit my code maybe?
Start by adding the buttons to their own container, this way you can control the layout of the buttons separately from the rest of the UI
JPanel panelFullOfButtons = new JPanel();
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panelFullOfButtons.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
Then add the "main" panel to the NORTH position of the frame and the "buttons" panel to the CENTER
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(panelFullOfButtons), BorderLayout.CENTER);
Mind you, in this case, I'd be very tempted to use something like a JList instead. See How to Use Lists for more details
I have done the same, can you tell me what's wrong?
// Problem #1...
JScrollPane pane = new JScrollPane();
pane.add(buttonPanel);
//...
// Problem #2...
panel.add(pane);
frame.add(panel);
These are competing with each other, moving the content around and overlapping with existing content...
public AdminClass() {
panel.setLayout(new GridLayout(3, 1));
panel.add(new JLabel("Welcome to Admin Panel"));
btnNewButton.addActionListener(this);
panel.add(btnNewButton);
panel.add(new JLabel("Existing Projects"));
List<String> projectNameList = new ArrayList<String>();
for (int index = 0; index < 1000; index++) {
projectNameList.add("Project " + index);
}
projectNames = projectNameList.toArray(new String[0]);
// Adding buttons to the project
buttons = new JButton[projectNameList.size()];
try {
for (int i = 0; i < projectNames.length; i++) {
buttons[i] = new JButton(projectNames[i]);
btnPnl1.add(buttons[i]);
buttons[i].addActionListener(this);
}
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, e2);
}
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(btnPnl1), BorderLayout.CENTER);
frame.setVisible(true);
frame.setSize(500, 500);
}
In this case I'd prefer to use either a JList to show the projects or a WrapLayout for laying out the buttons
Its useless to create a GridLayout like this: panel.setLayout(new GridLayout(10, 1));. If you declare the rows as a non zero value, the column count will be ignored. When you declare the maximum number of rows as ten, you force the eleventh component to be added in a second column (then a third, a forth and so on). Use panel.setLayout(new GridLayout(0, 1)); instead to force the only one column and frame.add(new JScrollPane(panel)); to create the ScrollPane.
But note that GridLayout will try to shrink your components the maximum as possible to fit the container size before scrolling is enabled.
I just want the button part to be inside J Scroll Pane
If you just want the JButton's (those added within the loop):
Create a new JPanel that you add the buttons to
Add (1) to a JScrollPane
Add (2) to panel
For example:
JPanel buttonPanel = new JPanel(new FlowLayout());
for (int i = 0; i < projectNames.length; i++){
buttons[i] = new ProjectButton(projectNames[i]);
buttons[i].setId(uniqueIds[i]);
panel.add(buttons[i]);
buttonPanel[i].addActionListener(this);
}
JScrollPane scroller = new JScrollPane(buttonPanel);
panel.add(scroller);
You might also consider using a different Component that doesn't require a JScrollPane, of course depending upon your needs - for instance a JComboBox.
I have come up with the below code:
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;
JFrame frame = new JFrame("SpringDemo1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
Container contentPane = frame.getContentPane();
SpringLayout layout = new SpringLayout();
contentPane.setLayout(layout);
for (int i = 0; i < numPairs; i++)
{
JLabel lable = new JLabel(labels[i]);
contentPane.add(lable);
contentPane.add(new JTextField(15));
}
//Display the window.
frame.pack();
frame.setVisible(true);
Expectation:
What I am getting:
Default:
when resized:
The result is noway related to how code actually/normally looks like!
I also tried copy pasting and running the ready-made code: downloaded from here:
and this is how the result looks :
To put the components in the right place using SpringLayout, you should use the ( SpringUtilities class ), download it then include it in your project.
your code should be:
private static void createAndShowGUI() {
String[] labels = {"Name: ", "Fax: ", "Email: ", "Address: "};
int numPairs = labels.length;
//Create and populate the panel.
JPanel p = new JPanel(new SpringLayout());
for (int i = 0; i < numPairs; i++) {
JLabel l = new JLabel(labels[i], JLabel.TRAILING);
p.add(l);
JTextField textField = new JTextField(10);
l.setLabelFor(textField);
p.add(textField);
}
//Lay out the panel.
SpringUtilities.makeCompactGrid(p,
numPairs, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
//Create and set up the window.
JFrame frame = new JFrame("SpringForm");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
p.setOpaque(true); //content panes must be opaque
frame.setContentPane(p);
//Display the window.
frame.pack();
frame.setVisible(true);
}
i hope that helps you!
I want to create a column and install a button in this last column in this table.
public JPanel pinakas(String[] pinaka) {
int sr = 0;
//int ari8mos =0;
String[] COLUMN_NAMES = {"Κωδικός", "Ποσότητα", "Τιμή", "Περιγραφή", "Μέγεθος", "Ράτσα"};
//pio panw mporoume na pros8esoume ws prwto column to "#", wste na deixnei ton ari8mo ths ka8e kataxwrhshs
DefaultTableModel modelM = new DefaultTableModel(COLUMN_NAMES, 0);
JTable tableM = new JTable(modelM);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JScrollPane(tableM), BorderLayout.CENTER);
Display disp = new Display();
while (pinaka[sr] != null) // !!!!tha ektupwsei kai mia parapanw "/n" logo ths kataxwrhshs prwtou h teleytaiou mahmatos
{
String[] temp5 = disp.lineDelimiter(pinaka[sr],6, "#");
Object[] doge = { temp5[0], temp5[1], temp5[2], temp5[3], temp5[4], temp5[5]};//edw mporoume sthn arxh na valoume to ari8mos gia na fainetai o ari8mos twn kataxwrhsewn
modelM.addRow(doge);
sr++;
//ari8mos++;
}
return mainPanel;
}
Table Button Column shows one possible solution.