table with buttons - java

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.

Related

Populating JTable with user input

so I've been having such a problem as for how to populate JTable with user input, i got table created but it just dosn't get the data from an object.
SportClub club = new SportClub();
String name = club.getName();
int points = club.getPoints();
int wins = club.getWins();
int defeats = club.getDefeats();
int draws = club.getDraws();
int goalsFor = club.getGoalsScored();
int goalsAgainst = club.getGoalsReceived();
int difference = goalsFor - goalsAgainst;
Object data[][] = {
{name, wins, draws, defeats, goalsFor, goalsAgainst,difference, points}
};
String column[] = {"Club Name", "Wins", "Draws", "Loses", "GF", "GA", "Goal Difference", "Total Points"};
JTable prTable = new JTable(data, column);
JFrame frame = new JFrame("Premier League Table");
JScrollPane scroll = new JScrollPane(prTable);
prTable.setFillsViewportHeight(true);
frame.add(scroll);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Feel like I should have used the for loop but just have a trouble where to place it.

Java - Adding Arrays of JTextField and JLabel to a JPanel

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.

Is it possible to change the height of each grid in a GridLayout?

I am trying to create a simple menu interface with 4 rows of various buttons and labels using GridLayout with FlowLayout inside each grid for organising the elements. However the space for the buttons and labels which should only take 1 line takes up a huge amount of space.
This is what my interface looks like minimized:
This is what it looks like maximized:
I am looking to set the maximum size of the labels panels/grid so that it only takes a small amount of space.
I am trying to make all the elements visible without anything being hidden with as small a window size as possible like this:
This is my code:
public class Window extends JFrame{
public Window() {
super("TastyThai Menu Ordering");
}
public static void main(String[] args) {
Window w = new Window();
w.setSize(500, 500);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel title = new JLabel("TastyThai Menu Order", SwingConstants.CENTER);
title.setFont(title.getFont().deriveFont(32f));
//generate page title
Container titlePanel = new JPanel(); // used as a container
titlePanel.setBackground(Color.WHITE);
FlowLayout flow = new FlowLayout(); // Create a layout manager
titlePanel.setLayout(flow);// assign flow layout to panel
titlePanel.add(title); // add label to panel
w.getContentPane().add(BorderLayout.NORTH,titlePanel);
//generate row containers
Container r1 = new JPanel(new FlowLayout());
Container r2 = new JPanel(new FlowLayout());
Container r3 = new JPanel(new FlowLayout());
Container r4 = new JPanel(new FlowLayout());
//generate mains radio buttons
Container mains = new JPanel(new GridLayout(7, 0));
mains.setBackground(Color.RED);
JLabel mainsHeader = new JLabel("Mains");
mains.add(mainsHeader);
String[] mainsChoices = {"Vegetarian", "Chicken", "Beef", "Pork", "Duck", "Seafood Mix"};
JRadioButton[] mainsRadioButton = new JRadioButton[6];
ButtonGroup mainsButtons = new ButtonGroup();
for(int i = 0; i < mainsChoices.length; i++) {
mainsRadioButton[i] = new JRadioButton(mainsChoices[i]);
mains.add(mainsRadioButton[i]);
mainsButtons.add(mainsRadioButton[i]);
}
//generate noodles radio buttons
Container noodles = new JPanel(new GridLayout(7, 0));
noodles.setBackground(Color.GREEN);
JLabel noodlesHeader = new JLabel("Noodles");
noodlesHeader.setFont(noodlesHeader.getFont().deriveFont(24f));
noodles.add(noodlesHeader);
String[] noodlesChoices = {"Pad Thai", "Pad Siew", "Ba Mee"};
JRadioButton[] noodlesRadioButton = new JRadioButton[3];
ButtonGroup noodlesButtons = new ButtonGroup();
for(int i = 0; i < noodlesChoices.length; i++) {
noodlesRadioButton[i] = new JRadioButton(noodlesChoices[i]);
noodles.add(noodlesRadioButton[i]);
noodlesButtons.add(noodlesRadioButton[i]);
}
//generate sauces radio buttons
Container sauces = new JPanel(new GridLayout(7, 0));
sauces.setBackground(Color.BLUE);
JLabel saucesHeader = new JLabel("Sauce");
saucesHeader.setFont(saucesHeader.getFont().deriveFont(24f));
sauces.add(saucesHeader);
String[] saucesChoices = {"Soy Sauce", "Tamarind Sauce"};
JRadioButton[] saucesRadioButton = new JRadioButton[2];
ButtonGroup saucesButtons = new ButtonGroup();
for(int i = 0; i < saucesChoices.length; i++) {
saucesRadioButton[i] = new JRadioButton(saucesChoices[i]);
sauces.add(saucesRadioButton[i]);
saucesButtons.add(saucesRadioButton[i]);
}
//generate extras check boxes
Container extras = new JPanel(new GridLayout(7, 0));
extras.setBackground(Color.YELLOW);
JLabel extrasHeader = new JLabel("Extra");
extrasHeader.setFont(extrasHeader.getFont().deriveFont(24f));
extras.add(extrasHeader);
String[] extrasChoices = {"Mushroom", "Egg", "Broccoli", "Beansrpout", "Tofu"};
JCheckBox[] extrasBoxes = new JCheckBox[5];
for(int i = 0; i < extrasChoices.length; i++) {
extrasBoxes[i] = new JCheckBox(extrasChoices[i]);
extras.add(extrasBoxes[i]);
}
JLabel selectionPrice = new JLabel("Selection Price: $ ");
JLabel selectionPriceVal = new JLabel("_______________");
JButton addToOrder = new JButton("Add to Order");
JLabel totalPrice = new JLabel("Total Price: $ ");
JLabel totalPriceVal = new JLabel("_______________");
JButton clearOrder = new JButton("Clear Order");
JRadioButton pickUp = new JRadioButton("Pick Up");
JRadioButton delivery = new JRadioButton("Delivery");
ButtonGroup pickupDelivery = new ButtonGroup();
pickupDelivery.add(pickUp);
pickupDelivery.add(delivery);
JButton completeOrder = new JButton("Complete Order");
Container menuSelection = new JPanel(new GridLayout(4,0));
menuSelection.add(r1);
r1.add(mains);
r1.add(noodles);
r1.add(sauces);
r1.add(extras);
menuSelection.add(r2);
r2.add(selectionPrice);
r2.add(selectionPriceVal);
r2.add(addToOrder);
menuSelection.add(r3);
r3.add(totalPrice);
r3.add(totalPriceVal);
r3.add(clearOrder);
menuSelection.add(r4);
r4.add(pickUp);
r4.add(delivery);
r4.add(completeOrder);
w.getContentPane().add(BorderLayout.CENTER, menuSelection);
w.setVisible(true);
}
}
GridLayout does not support that. All rectangles have the same size.
Take a look at the GridBagLayout, which supports dynamic resizing and much more.

This is my code to print the jtable on frame

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);
....

How to add buttons to every row in my for-loop

I wish to implement a button to every row in my for-loop. But i have no idea how to do it.
I would like to be able to edit data in each row by pressing a button.
for(HentbestillingsordreRegistrer hentboregistrer: hbor){
if(status.equals("Leveret")){
temp.append("<html>");
temp.append("BestillingsID: ");
temp.append(hentboregistrer.BestillingsID);
temp.append("<br />");
temp.append("Ordre Status:");
temp.append(hentboregistrer.BestillingsStatus);
temp.append("<br />");
temp.append("LeverandoerID: ");
temp.append(hentboregistrer.Leverandoernavn);
temp.append("<br />");
temp.append("Modtaget af: ");
temp.append(hentboregistrer.ModtagetAf);
temp.append("<br />");
temp.append("<br />");
}else{
temp.append("<html>");
temp.append("BestillingsID: ");
temp.append(hentboregistrer.BestillingsID);
temp.append("<br />");
temp.append(hentboregistrer.BestillingsStatus);
temp.append("<br />");
temp.append("LeverandoerID: ");
temp.append(hentboregistrer.Leverandoernavn);
temp.append("<br />");
temp.append("Modtaget af: ");
temp.append(hentboregistrer.ModtagetAf);
temp.append("<br />");
temp.append("<br />");
}
}
return temp.toString();
}
public JPanel HentOrdreGUI(){
JPanel info = new JPanel();
info.setLayout(new BorderLayout());
JLabel labelprintdata = new JLabel(temp.toString());
JScrollPane scroll = new JScrollPane(labelprintdata);
info.add(scroll, BorderLayout.CENTER);
return info;
}
I would change the JLabel into a JTable, and add a JButton as the 3rd column of the table. Something like this...
// Create a container for all your table data.
// There are 3 columns (type, value, button) in the table.
// And each order has 4 items in it (BestillingsId, Status, LeverandoerID, Modtaget)
Object[][] tableData = new Object[numOrders*4][3];
for(int i=0;i<numOrders;i++){
HentbestillingsordreRegistrer hentboregistrer = hbor[i];
// For each order, we need to add 4 rows, each with 3 cells in it (to hold the type, value, and the button)
if(status.equals("Leveret")){
tableData[(i*4)+0] = new Object[]{"BestillingsID",hentboregistrer.BestillingsID,new JButton("Edit")};
tableData[(i*4)+1] = new Object[]{"Ordre Status",hentboregistrer.BestillingsStatus,new JButton("Edit")};
tableData[(i*4)+2] = new Object[]{"LeverandoerID",hentboregistrer.Leverandoernavn,new JButton("Edit")};
tableData[(i*4)+3] = new Object[]{"Modtaget af:",hentboregistrer.ModtagetAf,new JButton("Edit")};
}
else{
tableData[(i*4)+0] = new Object[]{"BestillingsID",hentboregistrer.BestillingsID,new JButton("Edit")};
tableData[(i*4)+1] = new Object[]{"Ordre Status",hentboregistrer.BestillingsStatus,new JButton("Edit")};
tableData[(i*4)+2] = new Object[]{"LeverandoerID",hentboregistrer.Leverandoernavn,new JButton("Edit")};
tableData[(i*4)+3] = new Object[]{"Modtaget af:",hentboregistrer.ModtagetAf,new JButton("Edit")};
}
}
// Headings for the table columns
String[] tableHeadings = new String[]{"Type","Value","Button"};
JPanel info = new JPanel();
info.setLayout(new BorderLayout());
// Create the table from the data above
JTable table = new JTable(tableData,tableHeadings);
JScrollPane scroll = new JScrollPane(table);
info.add(scroll, BorderLayout.CENTER);

Categories