I have to program that takes ip Addresses from a file and outputs the country its in onto a JTable. I have no errors but when i click the button the JTable doesn't open up. How do i make the JTable open up?
package org.koushik.javabrains;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import net.webservicex.GeoIP;
import net.webservicex.GeoIPService;
import net.webservicex.GeoIPServiceSoap;
public class IPLocationFinder {
public static void main(String[] args) {
final JFileChooser filechooser = new JFileChooser();
filechooser.setVisible(false);
final JTable jt;
final String[] columns= {"IP address","Country"};
final String[][] data = {{}};
final DefaultTableModel model = new DefaultTableModel(data, columns);
jt = new JTable(model);
jt.setPreferredScrollableViewportSize(new Dimension(450, 60));
jt.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane();
jt.add(jps);
final JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER);
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,10,10);
panel.add(b1, c);
frame.setBounds(400,150,600,200);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
new IPLocationFinder();
BufferedReader inputStream = null;
try {
inputStream = new BufferedReader(new FileReader("C:/IP Addresses/ip.txt"));
String l;
try {
while ((l = inputStream.readLine()) != null) {
String ipAddress = l;
GeoIPService ipService = new GeoIPService();
GeoIPServiceSoap geoIPServiceSoap = ipService.getGeoIPServiceSoap();
GeoIP geoIp = geoIPServiceSoap.getGeoIP(ipAddress);
model.addRow(new String[][]{{"Column 1", geoIp.getCountryName()}});
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
b1.addActionListener(actionListener);
}
}
You have several problems:
You never add the JTable to your panel.
You're adding a JScrollPane to your JTable when it should be the other way around. The JScrollPane should have its view set to the scrollable component, which in this case is the JTable. Otherwise, as your table's rows increase, the elements above it are simply going to be pushed up.
You've added an empty row to your table by saying final String[][] data = { {} };. When you start adding rows, you'll have a blank row to start. Therefore, you should remove the inner curly braces.
You should be aware that your JTable data is being prescribed as a 2D String array and although you're technically adding the data correctly, it's going to show up as an address in your first column:
To fix the above issue, change your addRow data to a 2D array such as model.addRow(new String[] { "Column 1", "Country 1" });
Below is a simplified, corrected version:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class IPLocationFinder {
public static void main(String[] args) {
final String[] columns = { "IP address", "Country" };
final String[][] data = {};
final DefaultTableModel model = new DefaultTableModel(data, columns);
final JTable jt = new JTable(model);
final JFrame frame = new JFrame();
final JScrollPane jps = new JScrollPane(jt);
final JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JButton b1 = new JButton("Start");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10, 10, 10, 10);
panel.add(b1, c);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(jps, BorderLayout.CENTER);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
model.addRow(new String[] { "Column 1", "Country 1" });
}
};
b1.addActionListener(actionListener);
frame.pack();
frame.setVisible(true);
}
}
I'm gessing you're using a panel to show the jtable, however as you can notice, there's no a panel.add(jt); line.
So, go ahead and add that line inside the Action
EDIT
As #Braj comment, the jt must be added to the scroll. Then instead add the JTable, add the JScroll.
panel.add(jsp);
Related
I have a JTextArea that is filled with numbers with no duplicates. There is an add and remove button. I have programmed the add button, but I am struggling with programming the remove button. I know how to remove the number from the array, but I'm not sure how to remove the number from the text area.
How do I remove a line from a text area that contains a certain number?
Extra notes:
The only input is integers.
Your question may in fact be an XY Problem where you ask how to fix a specific code problem when the best solution is to use a different approach entirely. Consider using a JList and not a JTextArea. You can easily rig it up to look just like a JTextArea, but with a JList, you can much more easily remove an item such as a line by removing it from its model.
For example:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class NumberListEg extends JPanel {
private static final int VIS_ROW_COUNT = 10;
private static final int MAX_VALUE = 10000;
private DefaultListModel<Integer> listModel = new DefaultListModel<>();
private JList<Integer> numberList = new JList<>(listModel);
private JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, MAX_VALUE, 1));
private JButton addNumberButton = new JButton(new AddNumberAction());
public NumberListEg() {
JPanel spinnerPanel = new JPanel();
spinnerPanel.add(spinner);
JPanel addNumberPanel = new JPanel();
addNumberPanel.add(addNumberButton);
JPanel removeNumberPanel = new JPanel();
JButton removeNumberButton = new JButton(new RemoveNumberAction());
removeNumberPanel.add(removeNumberButton);
JPanel eastPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
// gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(3, 3, 3, 3);
eastPanel.add(spinner, gbc);
gbc.gridy = GridBagConstraints.RELATIVE;
eastPanel.add(addNumberButton, gbc);
eastPanel.add(removeNumberButton, gbc);
// eastPanel.add(Box.createVerticalGlue(), gbc);
numberList.setVisibleRowCount(VIS_ROW_COUNT);
numberList.setPrototypeCellValue(1234567);
numberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane listPane = new JScrollPane(numberList);
listPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(listPane, BorderLayout.CENTER);
add(eastPanel, BorderLayout.LINE_END);
}
private class AddNumberAction extends AbstractAction {
public AddNumberAction() {
super("Add Number");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
}
#Override
public void actionPerformed(ActionEvent arg0) {
int value = (int) spinner.getValue();
if (!listModel.contains(value)) {
listModel.addElement(value);
}
}
}
private class RemoveNumberAction extends AbstractAction {
public RemoveNumberAction() {
super("Remove Number");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
#Override
public void actionPerformed(ActionEvent e) {
Integer selection = numberList.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
}
}
}
private static void createAndShowGui() {
NumberListEg mainPanel = new NumberListEg();
JFrame frame = new JFrame("Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
can not be remove from the array,you can to make index to be empty,for example String a= Integer.toString(type for int),then a.replace("your int","");
I'm having a problem with a JFrame not showing a JTable that is added to it. I've tried getContentPane().add(..), I've switched to just add to keep the code a little shorter. Any help is more than appreciated!
package com.embah.Accgui;
import java.awt.*;
import javax.swing.*;
public class accCreator extends JFrame {
private String[] columnNames = {"Username", "Password", "Members", "World"};
private Object[][] data = {{"b", "b", "b", "b"},
{ "e", "e", "e", "e"}};
private JTable tbl_Accounts;
private JScrollPane scrollPane;
private JLabel lbl_Account = new JLabel();
private JLabel lbl_Username = new JLabel();
private JLabel lbl_Password = new JLabel();
private JLabel lbl_Homeworld = new JLabel();
private JButton btn_Select = new JButton();
private JButton btn_Addacc = new JButton();
private JButton btn_Delacc = new JButton();
private JTextArea txt_Username = new JTextArea();
private JTextArea txt_Password = new JTextArea();
private JTextArea txt_Homeworld = new JTextArea();
private JCheckBox cbox_Members = new JCheckBox();
private JCheckBox cbox_RanWrld = new JCheckBox();
public accCreator() {
setLayout(null);
setupGUI();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setupGUI() {
tbl_Accounts = new JTable(data, columnNames);
tbl_Accounts.setLocation(5, 30);
tbl_Accounts.setPreferredScrollableViewportSize(new Dimension(420, 250));
tbl_Accounts.setFillsViewportHeight(true);
tbl_Accounts.setVisible(true);
add(tbl_Accounts);
scrollPane = new JScrollPane(tbl_Accounts);
add(scrollPane);
lbl_Account.setLocation(4, 5);
lbl_Account.setSize(100, 20);
lbl_Account.setText("Select Account:");
add(lbl_Account);
lbl_Username.setLocation(5, 285);
lbl_Username.setSize(70, 20);
lbl_Username.setText("Username:");
add(lbl_Username);
lbl_Password.setLocation(5, 310);
lbl_Password.setSize(70, 20);
lbl_Password.setText("Password:");
add(lbl_Password);
lbl_Homeworld.setLocation(310, 310);
lbl_Homeworld.setSize(80, 20);
lbl_Homeworld.setText("Home World:");
add(lbl_Homeworld);
btn_Select.setLocation(305, 5);
btn_Select.setSize(120, 20);
btn_Select.setText("Select Account");
add(btn_Select);
btn_Addacc.setLocation(300, 285);
btn_Addacc.setSize(60, 20);
btn_Addacc.setText("Add");
btn_Addacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String worldSel = "";
if(cbox_RanWrld.isSelected()){
worldSel = "Random";
} else {
worldSel = txt_Homeworld.getText();
}
Object[] row = {txt_Username.getText(), txt_Password.getText(), cbox_Members.isSelected(), worldSel};
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
model.addRow(row);
}
});
add(btn_Addacc);
btn_Delacc.setLocation(365, 285);
btn_Delacc.setSize(60, 20);
btn_Delacc.setText("Del");
btn_Delacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
}
});
add(btn_Delacc);
txt_Username.setLocation(80, 285);
txt_Username.setSize(100, 20);
txt_Username.setText("");
txt_Username.setRows(5);
txt_Username.setColumns(5);
add(txt_Username);
txt_Password.setLocation(80, 310);
txt_Password.setSize(100, 20);
txt_Password.setText("");
txt_Password.setRows(5);
txt_Password.setColumns(5);
txt_Password.setTabSize(0);
add(txt_Password);
txt_Homeworld.setLocation(395, 310);
txt_Homeworld.setSize(30, 20);
txt_Homeworld.setText("82");
txt_Homeworld.setRows(5);
txt_Homeworld.setColumns(5);
txt_Homeworld.setTabSize(0);
add(txt_Homeworld);
cbox_Members.setLocation(185, 285);
cbox_Members.setSize(80, 20);
cbox_Members.setText("Members");
cbox_Members.setSelected(false);
add(cbox_Members);
cbox_RanWrld.setLocation(185, 310);
cbox_RanWrld.setSize(115, 20);
cbox_RanWrld.setText("Random World");
cbox_RanWrld.setSelected(false);
add(cbox_RanWrld);
setTitle("Account Manager");
setSize(440, 370);
setVisible(true);
setResizable(false);
}
public static void main(String args[]) {
new accCreator();
}
}
I know thats not the problem tho because everything else shows up just fine
Oh... really? Not in my computer...
Let's have a picture of your actual GUI shown in my PC:
Does the GUI looks the same in your computer? I bet no.
But... why does it looks like that in my PC?
Well, as stated above in the comments by #MadProgrammer this is because of the setLayout(null); line. You might want to read Why is it frowned upon to use a null layout in Java Swing? for more information.
Now, that being said, you should also want to read and learn how to use the various layout managers that will let you create complex GUIs.
In your code you never set the location / bounds for scrollPane, and the size of it, so the component has a default size of 0, 0.
But... I think it's better to show you how you can get a really similar GUI (I'm in a hurry so I didn't make an even more similar GUI). You can copy-paste my code and see the same output (with slight differences because of the OS maybe) but text won't be cropped.
The code that produces the above image is this one:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AccountCreator {
private JFrame frame;
private JPanel mainPane;
private JPanel topPane;
private JPanel tablePane;
private JPanel bottomPane;
private JLabel selectAccountLabel;
private JLabel userNameLabel;
private JLabel passwordLabel;
private JLabel homeWorldLabel;
private JTextField userNameField;
private JTextField homeWorldField;
private JPasswordField passwordField;
private JCheckBox membersBox;
private JCheckBox randomBox;
private JButton selectAccountButton;
private JButton addButton;
private JButton deleteButton;
private JTable table;
private JScrollPane scroll;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AccountCreator().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
int rows = 30;
int cols = 3;
String[][] data = new String[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = i + "-" + j;
}
}
String[] columnNames = { "Column1", "Column2", "Column3" };
table = new JTable(data, columnNames);
scroll = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
table.setPreferredScrollableViewportSize(new Dimension(420, 250));
table.setFillsViewportHeight(true);
selectAccountLabel = new JLabel("Select Account");
userNameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
homeWorldLabel = new JLabel("Home world");
selectAccountButton = new JButton("Select Account");
addButton = new JButton("Add");
deleteButton = new JButton("Del");
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
homeWorldField = new JTextField(3);
membersBox = new JCheckBox("Members");
randomBox = new JCheckBox("Random world");
topPane = new JPanel();
topPane.setLayout(new BorderLayout());
topPane.add(selectAccountLabel, BorderLayout.WEST);
topPane.add(selectAccountButton, BorderLayout.EAST);
tablePane = new JPanel();
tablePane.add(scroll);
bottomPane = new JPanel();
bottomPane.setLayout(new GridLayout(0, 5, 3, 3));
bottomPane.add(userNameLabel);
bottomPane.add(userNameField);
bottomPane.add(membersBox);
bottomPane.add(addButton);
bottomPane.add(deleteButton);
bottomPane.add(passwordLabel);
bottomPane.add(passwordField);
bottomPane.add(randomBox);
bottomPane.add(homeWorldLabel);
bottomPane.add(homeWorldField);
mainPane = new JPanel();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
frame.add(topPane, BorderLayout.NORTH);
frame.add(tablePane, BorderLayout.CENTER);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also, you might have noticed that the main() method is different, well, the code inside it is placing the program on the Event Dispatch Thread (EDT).
So, be sure to include it in your future programs
I tried to add data to the JTable Dynamically using DefaultTableModel, but it isn't working.
I had created two classes: One class (Input.java) represents a popup which allows you to write the data (name, option and constraint) and save it. Another class represents a popup which includes a table (InputMain.java). InputMain will then transform those info (if received) to a row with in the table that list out those all the information in three columns. In Input, I created an instance of InputMain, and set the model of the table to a new DefaultTableModel() (if I don't do this, it will throw an error) (a table is already created in InputMain, so that if I create an instance of InputMain, I am probably calling the table within InputMain). Then, according to actionPerformed(ActionEvent e), after the 'enter' button is clicked within the JPanel, it will create a new array of data with nameText, optionText and constraintText. And finally, the data will be added to the model.
I don't know why I can't add all those data into the table, except that method above sounds logical to me.
Here's the InputMain.java class:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class InputMain {
JButton add;
JButton change;
JButton delete;
JTable table;
String[] columns;
String[][] data;
JButton create;
JPanel labelPanel;
JPanel bigPanel;
JPanel centerPanel;
public InputMain() {
int fontSize = 50;
add = new JButton("add");
change = new JButton("change");
delete = new JButton("delete");
create = new JButton("create");
columns = new String[]{"name","option","constraint"};
data = new String[][]{{"","",""}};
table = new JTable(data,columns) {
#Override
public boolean isCellEditable(int row, int column) {
return false; //to avoid it from being changable by double clicking any data
}
};
table.setPreferredScrollableViewportSize(new Dimension(450,63));
table.setFillsViewportHeight(true);
JScrollPane jsp = new JScrollPane(table); // not always can the table be fully shown --> add a scrollbar
add.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
change.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
delete.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
create.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.setFont(new Font(table.getName(),Font.PLAIN,fontSize));
//table.getEditorComponent().setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.getTableHeader().setFont(new Font(table.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(add);
labelPanel.add(change);
labelPanel.add(delete);
labelPanel.setLayout(new FlowLayout(10,30,10));
centerPanel = new JPanel();
centerPanel.add(labelPanel);
centerPanel.setLayout(new GridBagLayout());
bigPanel = new JPanel();
bigPanel.setLayout(new GridLayout(3,0));
bigPanel.add(centerPanel);
bigPanel.add(jsp);
bigPanel.add(create);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
}); // pressing add button pops up the Input Frame
}
}
And here's the Input.java class:
package com.company;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class Input extends JPanel{
JLabel nameLabel;
JLabel optionLabel;
JLabel constraintLabel;
JButton enter;
JPanel labelPanel;
JPanel jp2;
JPanel jp3;
JPanel jp4;
JTextField nameText;
String[] optionStrings;
JComboBox<String> optionText;
JCheckBox wk1;
JCheckBox wk2;
JCheckBox wk3;
JCheckBox wk4;
JCheckBox wk5;
public Input() {
nameLabel = new JLabel("name: ");
optionLabel = new JLabel("option: ");
constraintLabel = new JLabel("constraint:");
enter = new JButton("add");
nameText = new JTextField(10);
Options c = new Options();
optionStrings = new String[]{c.satNight,c.sunEight,c.sunNineThirty,c.sunEleven,c.sunNight};
optionText = new JComboBox<String>(optionStrings);
wk1 = new JCheckBox("1");
wk2 = new JCheckBox("2");
wk3 = new JCheckBox("3");
wk4 = new JCheckBox("4");
wk5 = new JCheckBox("5");
int fontSize = 50;
nameLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
constraintLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
enter.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
nameText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk1.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk2.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk3.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk4.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk5.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(nameLabel);
labelPanel.add(nameText);
labelPanel.add(optionLabel);
labelPanel.add(optionText);
labelPanel.add(constraintLabel);
labelPanel.add(wk1);
labelPanel.add(wk2);
labelPanel.add(wk3);
labelPanel.add(wk4);
labelPanel.add(wk5);
labelPanel.add(enter);
labelPanel.setLayout(new FlowLayout(10,30,10));
InputMain i = new InputMain();
i.table.setModel(new DefaultTableModel());
DefaultTableModel model = (DefaultTableModel) i.table.getModel();
enter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String constraintText = "";
String[] data = new String[]{nameText.getText(),optionText.getSelectedItem().toString(),constraintText};
model.addRow(data);
nameText.setText("");
}
});
}
}
Thanks in advance.
I think the problem lies in the actionPerformed of InputMain.
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
});
You construct a new instance of Input. That means that you create a new empty DefaultTableModel and attach it to your table each time you click on the add button. Try move the construction of the Input outside of your actionPerformed like this:
Input i = new Input();
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
s.add(i.labelPanel);
s.setVisible(true);
}
UPDATE
Of course the instantiation of InputMain inside of Input should be removed, too. Instead have a member of Type InputMain in Input:
private InputMain inputMain;
and change the constructor of Input to set the value:
public Input (InputMain inputMain) {
this.inputMain = inputMain;
...
And change the instantiation of Input in InputMain to
Input i = new Input(this);
Reference to the given code..i can access the print statement inside the if statement in for-loop(inside try-catch block) but the checkboxes are not adding.
I am using the revalidating and repaint function but still its not working.
The for loop inside the try-catch block is running except for the adding jscrollpane. Where am i wrong?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.anurag;
import com.anurag.HttpURLConnectionExample;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
/**
*
* #author Anurag
*/
public class MainGui {
static JFrame frame = new JFrame("Rest Testing");
public static void main(String args[]) {
frame.setLayout(new FlowLayout());
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField path = new JTextField("getresponse.xls");
frame.add(path);
JButton upload = new JButton("Upload");
frame.add(upload);
upload.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JScrollPane jscrlpLabel = new JScrollPane(new JLabel(
"<HTML>A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br></HTML>"));
jscrlpLabel.setPreferredSize(new Dimension(200, 100));
frame.add(jscrlpLabel);
frame.revalidate();
frame.repaint();
try{
System.out.println(path.getText());
HttpURLConnectionExample http = new HttpURLConnectionExample();
int noOfRows = http.setPath(path.getText());
Workbook workbook = Workbook.getWorkbook(new File(path.getText()));
Sheet sheet = workbook.getSheet(0);
Cell cell= sheet.findCell("S. No.");
int col=cell.getColumn();
int row=cell.getRow();
row=row+2;
//System.out.println("row="+row+"col="+col);
for(int i=row;i<noOfRows;i++,row++)
{
int p=http.readFile(col,row);
if(p==1){
JCheckBox cb = new JCheckBox("CheckBox");
JScrollPane jscrlp = new JScrollPane(cb);
jscrlp.setPreferredSize(new Dimension(140, 95));
frame.add(jscrlp);
frame.revalidate();
frame.repaint();
System.out.println("Checkbox created");
}
else if(p==2){
JCheckBox cb1 = new JCheckBox("CheckBox ");
Box box = Box.createVerticalBox();
box.add(cb1);
JScrollPane jScrollPane1 = new JScrollPane(box);
jScrollPane1.setPreferredSize(new Dimension(140, 95));
frame.add(jScrollPane1);
frame.revalidate();
frame.repaint();
System.out.println("Checkbox created with textfield");
}
}
http.getData();
}catch(Exception e){System.out.println("Exception is "+e);}
}
});
//JOptionPane.showMessageDialog(null, "Done", "Alert", WIDTH);
JCheckBox a = new JCheckBox("A");
JCheckBox b = new JCheckBox("B");
JLabel label = new JLabel("Option");
Box box = Box.createVerticalBox();
box.add(label);
box.add(a);
box.add(b);
JScrollPane jscrlpBox = new JScrollPane(box);
jscrlpBox.setPreferredSize(new Dimension(240, 150));
//f.add(jscrlpLabel);
frame.add(jscrlpBox);
frame.setVisible(true);
}
}
Start by having a read through Creating a GUI With JFC/Swing, Laying Out Components Within a Container, Concurrency in Swing and How to Use Scroll Panes
Box is not really a "visible" component, it's meant as a feature to be used with BoxLayout
You're adding multiple JScrollPanes to the single view, which kind of feels weird to me
Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
You're updating the UI from within the Event Dispatching Thread, but the process by which you're making your decisions may take time to run, this could make the UI look like it's doing nothing until the actionPerformed method exist
There's little point in calling revaldiate all the time, leave it until you have finished updating the whole UI, it will provide better performance in the long run
Start by creating a JPanel which you then wrap a JScrollPane around, add the JScrollPane to the base UI
As required, add and remove components from this JPanel, for example...
public class MainGui {
public static void main(String args[]) {
new MainGui();
}
private JFrame frame = new JFrame("Rest Testing");
private JPanel checkboxes;
public MainGui() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField path = new JTextField("getresponse.xls");
JPanel fields = new JPanel();
fields.add(path);
JButton upload = new JButton("Upload");
fields.add(upload);
frame.add(fields, BorderLayout.NORTH);
checkboxes = new JPanel(new GridBagLayout());
JScrollPane scrollPane = new JScrollPane(checkboxes);
frame.add(scrollPane);
upload.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
checkboxes.add(new JLabel("<HTML>A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br></HTML>"), gbc);
try {
int noOfRows = 100;
for (int row = 0; row < noOfRows; row++, row++) {
int p = (int) ((Math.random() * 2) + 1);
System.out.println(p);
if (p == 1) {
JCheckBox cb = new JCheckBox("CheckBox");
checkboxes.add(cb, gbc);
} else if (p == 2) {
JCheckBox cb1 = new JCheckBox("CheckBox ");
JPanel stuff = new JPanel();
stuff.add(cb1);
stuff.add(new JTextField(10));
checkboxes.add(stuff, gbc);
}
}
} catch (Exception e) {
System.out.println("Exception is " + e);
}
checkboxes.revalidate();
checkboxes.repaint();
}
});
//JOptionPane.showMessageDialog(null, "Done", "Alert", WIDTH);
JCheckBox a = new JCheckBox("A");
JCheckBox b = new JCheckBox("B");
JLabel label = new JLabel("Option");
JPanel stuff = new JPanel();
stuff.add(label);
stuff.add(a);
stuff.add(b);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
checkboxes.add(stuff, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Now, I'm not 100% sure, but you might find using a JTable produces the look you're after. How to Use Tables
You can't add the checkboxes directly to the scroll pane, you need to make a list model. You will need a Scroll Pane, a list renderer, a model, and a custom JCheckboxList class. See the following questions:
How do I make a list with checkboxes in Java Swing?
Also, you might run into a problem that I did where the JScrollPane's viewport:
Components in JList are Hidden by White Square Thing Until Clicked
I have a problem with JTable/JScrollPane. My data table is not refreshing/updating. I am using DefultTableModel and according to the code everything is fine and I don't have any errors. Also I have a table with paging and that's why I am using action listeners and buttons "prev" and "next". I am passing from other function to function that is coded in class where is JTable. Problem is that I fill arrays which contains data for table but table won't update/refresh it. Here is my code. Thanks advance.
BIG EDIT Old code was removed. I added new codes that will help you guys/girls to understand problem that I have. Hope that this will help. Regards.
First here is class that show gui:
import javax.swing.*;
public class Glavni {
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
gui Scanner = new gui();
Scanner.setVisible(true);
}
});
}
}
Second here is class that pass String to gui class that contains jtable
public class passDatatoTable {
public void passData(){
String str1,str2,str3,str4;
gui SendStringsToGUI = new gui();
for (int i =0;i<=10;i++){
str1="Column 1 of row: "+i;
str2="Column 2 of row: "+i;
str3="Column 3 of row: "+i;
str4="Column 4 of row: "+i;
SendStringsToGUI.WriteMonitorData(str1, str2, str3, str4);
}
}
}
Next here is declaration of gui (contructor):
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class gui extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
String[][] data = new String[100][4];
String[] columnNames = new String[]{
"IP", "PC_NAME", "ttl", "db"
};
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
int i=0;
public void WriteMonitorData (String IP, String PC_NAME, String ttl, String gw)
{
System.out.println(IP);//just for testing (check if data was passed)
model.setValueAt(IP, i, 0);
model.setValueAt(PC_NAME, i, 1);
model.setValueAt(ttl, i, 2);
model.setValueAt(gw, i, 3);
i++;
model.fireTableDataChanged();
table.repaint();
scrollPane.repaint();
}
gui(){
JButton addData= new JButton("Add Data");
JButton next = new JButton("next");
JButton prev = new JButton("prev");
addData.addActionListener(this);
next.addActionListener(this);
prev.addActionListener(this);
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.add(addData);
buttonPanel.add(prev);
buttonPanel.add(next);
panel.add(buttonPanel, BorderLayout.SOUTH);
panel.add(table.getTableHeader(), BorderLayout.PAGE_START);
panel.add(scrollPane, BorderLayout.CENTER);
getContentPane().add(panel);
}
Here is actionListeners:
public void actionPerformed(ActionEvent e) {
if ("Add Data".equals(e.getActionCommand())){
passDatatoTable passSomeData = new passDatatoTable();
passSomeData.passData();
}
if ("next".equals(e.getActionCommand())) {
Rectangle rect = scrollPane.getVisibleRect();
JScrollBar bar = scrollPane.getVerticalScrollBar();
int blockIncr = scrollPane.getViewport().getViewRect().height;
bar.setValue(bar.getValue() + blockIncr);
scrollPane.scrollRectToVisible(rect);
}
if ("prev".equals(e.getActionCommand())) {
Rectangle rect = scrollPane.getVisibleRect();
JScrollBar bar = scrollPane.getVerticalScrollBar();
int blockIncr = scrollPane.getViewport().getViewRect().height;
bar.setValue(bar.getValue() - blockIncr);
scrollPane.scrollRectToVisible(rect);
}
}
Your first snippet shows this:
JTable table = new JTable(model);
but your gui() constructor shows:
JTable table = new JTable(data, columnNames);
You initiate the table twice. Once using the TableModel (JTable(TableModel tm)) the next using JTable(int rows,int cols) this is not good, initiate the JTable once in the constructor:
gui() {
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
JButton next = new JButton("next");
JButton prev = new JButton("prev");
next.addActionListener(this);
prev.addActionListener(this);
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.add(prev);
buttonPanel.add(next);
panel.add(buttonPanel, BorderLayout.SOUTH);
panel.add(table.getTableHeader(), BorderLayout.PAGE_START);
panel.add(scrollPane, BorderLayout.CENTER);
getContentPane().add(panel);
}
UPDATE:
Here is an example that has a thread which will start 2.5 secinds after the UI is visible and change a value of the JTable:
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Test extends JFrame {
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.pack();
frame.setVisible(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2500);
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
model.setValueAt("hello", 0, 0);
}
});
}
}).start();
}
static DefaultTableModel model;
private void initComponents(JFrame frame) {
String data[][] = {
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"10", "11", "12"}
};
String col[] = {"Col 1", "Col 2", "Col 3"};
model = new DefaultTableModel(data, col);
JTable table = new JTable(model);
frame.getContentPane().add(new JScrollPane(table));
}
}
From what I understand from the comments and the question, you have first created a DefaultTableModel by passing the data as arrays in the constructor
String[][] data = new String[100][4];
String[] columnNames = new String[]{
"IP", "PC_NAME", "ttl", "db"};
DefaultTableModel model = new DefaultTableModel(data,columnNames);
and you try to modify the table afterwards by adjusting those arrays. That will never ever have any effect, as the DefaultTableModel does not use those arrays. This can be seen in the source code of that class
public DefaultTableModel(Object[][] data, Object[] columnNames) {
setDataVector(data, columnNames);
}
which in the end comes down to
protected static Vector convertToVector(Object[][] anArray) {
if (anArray == null) {
return null;
}
Vector<Vector> v = new Vector<Vector>(anArray.length);
for (Object[] o : anArray) {
v.addElement(convertToVector(o));
}
return v;
}
So all the elements of the array are copied into an internal Vector and the array is no longer used.
Solution: do not update the arrays but update the DefaultTableModel. That class provides all the API you need to add/remove data to/from it.