i´ve been trying to refresh de JTable after inserting data in MySql, but i cant manage to make it work.
The data is filled in the agregar JPanel and saved after clicking a button, checking in the mysql console, the data is added to the database, but when i open the table it doesn´t update unless i restart the program.
This is My code:
public class verTodos extends JPanel {
contactoDAO dao = new contactoDAO();
List<contacto> contactos = dao.getAll();
private JTable table;
public verTodos() {
String[] colName = { "Id", "Nombre", "Apellido", "Telefono",
"Direccion", "Email", "Rubro1", "Rubro2", "Rubro3" };
Object[][] obj = new Object[contactos.size()][10];
for (int i = 0; i < contactos.size(); i++) {
contacto c = contactos.get(i);
obj[i][0] = c.getId();
bj[i][1] = c.getNombre();
obj[i][2] = c.getApellido();
obj[i][3] = c.getTelefono();
obj[i][4] = c.getDireccion();
obj[i][5] = c.getEmail();
obj[i][6] = c.getRubro1();
obj[i][7] = c.getRubro2();
obj[i][8] = c.getRubro3();
setBounds(100, 100, 800, 300);
}
DefaultTableModel contactTableModel = new DefaultTableModel(obj,colName);
table = new JTable(contactTableModel);
setLayout(new BorderLayout(0, 0));
contactTableModel.fireTableDataChanged();
contactTableModel.setColumnIdentifiers(colName);
add(table.getTableHeader(), BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
scrollPane.setViewportView(table);
repaint();
}
}
this is the main screen that contains the JPanels:
public class principal extends JFrame {
JFrame frame = new JFrame();
JPanel container = new JPanel();
CardLayout cl = new CardLayout();
private final JMenuBar menuBar = new JMenuBar();
/.....
.....
private final JMenuItem mntmVerTodos = new JMenuItem("Ver todos");
private final JMenuItem mntmAgregar = new JMenuItem("Agregar");
agregar ag = new agregar();
verTodos ver = new verTodos();
...
...
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new principal();
}
});
}
public principal() {
textField.setMaximumSize(new Dimension(300, 500));
textField.setBounds(new Rectangle(0, 0, 30, 0));
textField.setColumns(10);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int X = (screen.width / 2) - (1366 / 2);
int Y = (screen.height / 2) - (720 / 2);
frame.setBounds(X, Y, 1363, 720);
container.setLayout(cl);
ver.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
container.add(ver, "ver");
container.add(ag, "ag");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
frame.getContentPane().add(container);
frame.setJMenuBar(menuBar);
menuBar.add(mnNewMenu);
cl.show(container, "ver");
mntmVerTodos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "ver");
}
});
mnContactos.add(mntmVerTodos);
mnContactos.add(mntmAgregar);
mntmModificar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.show(container, "mod");
}
});
menuBar.add(btn);
frame.setVisible(true);
}
}
You need to repopulate your model once the database has been updated. Add a refresh button that when clicked, updates contactTableModel
Related
I have a database with tables. I passed the name of the tables into the buttons. When you click, you need a table with fields and filling to appear. The problem is that I have a new table added every time I click on the button.
Can someone please say me how to do it? Thanks in advance!
public class App extends JPanel {
static List<FieldElement> fields = new ArrayList<>();
static List<Map<String, Object>> data = new ArrayList<>();
static JTable jTable = new JTable();
public static void createGUI() throws SQLException {
TableContent tableContent = new TableContent();
JFrame frame = new JFrame();
MetadataHelper databaseMetadata = new MetadataHelper();
List<ButtonElement> elements = databaseMetadata.showTables();
JPanel panel = new JPanel();
JPanel buttons = new JPanel(new GridLayout(0, 1));
for (ButtonElement buttonElements : elements) {
JButton jButton = new JButton(buttonElements.getTablesInMigrateSchema());
buttons.add(jButton);
jButton.addActionListener(new ActionListener() {
#SneakyThrows
#Override
public void actionPerformed(ActionEvent e) {
fields = tableContent.getDatabaseMetadata().showFields(buttonElements.getTablesInMigrateSchema());
data = tableContent.getDatabaseMetadata().selectAll(buttonElements.getTablesInMigrateSchema());
Object[][] objectRows = data.stream().map(m -> m.values().toArray()).toArray(Object[][]::new);
jTable = new JTable(objectRows, fields.toArray());
panel.add(new JScrollPane(jTable));
frame.revalidate();
frame.repaint();
}
});
}
panel.add(buttons, BorderLayout.EAST);
frame.add(panel);
frame.setTitle("SwingSandbox");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#SneakyThrows
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
createGUI();
}
});
}
}
One easy possibility is to store the JScrollPane in a variable (which holds your table that you want to remove):
static JTable jTable = new JTable();
static JScrollPane jScrollPane;
And then in your actionPerformed method:
public void actionPerformed(ActionEvent e) {
...
if (jScrollPane != null) {
panel.remove(jScrollPane);
}
jTable = new JTable(objectRows, fields.toArray());
jScrollPane = new JScrollPane(jTable);
panel.add(jScrollPane);
frame.revalidate();
frame.repaint();
}
I have application where on Jbutton click i create new JFrame with its own class and import file
When i read file i passed that file to method of my MainGui class where i parse data and store it in array of objects which is global field.
When i click on another button from MainGui, i cant access that array of objets and none of its fields(i get nullPointerException)
Here is my code:
MainGui Class
public class MainGui implements ActionListener {
private JFrame frame;
private JPanel panel;
GrupaArtikala[] objektiArtikli; // ARRAY OF OBJECTS
JPanel centerPanel = new JPanel(new BorderLayout());
private final int MAX_TABLES = 8;
JButton buttonImport;
JButton [] buttonsTables = new JButton[MAX_TABLES];
String tables[] = {
"Grupa artikala",
"Osnovna mera",
"Jedinica mere",
"Naknada",
"Popust",
"Artikal",
"Normativ",
"Normativ stavka",
};
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainGui window = new MainGui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createAndShowPodesavanja() {
GuiFileChooser guiPodesavanja= new GuiFileChooser(); // HERE I CREATE NEW FRAME
guiPodesavanja.initialize();
guiPodesavanja.setVisible(true);
// this.setVisible(false);
}
public MainGui() {
initialize();
}
public void pars(String file) {
try {
String content = new String(Files.readAllBytes(Paths.get(file)));
int startArtikitag = content.indexOf(":ISSI");
int endArticalTag = content.indexOf("#TABLENAME:OSNOVNA_MJERA");
String gupaArtikalaString = content.substring(startArtikitag + 5, endArticalTag - 15);
System.out.println(gupaArtikalaString);
String[] lines =gupaArtikalaString.split(System.lineSeparator());
objektiArtikli = new GrupaArtikala[lines.length];
for(int i = 1; i < lines.length; i++) {
objektiArtikli[i] = new GrupaArtikala(lines[i]); // HERE I INITALIAZE ARRAY OF OBJECTS
}
System.out.println("rec u konstruktoru lokalno " + objektiArtikli[1].getId());
System.out.println("rec u gobalno" + objektiArtikli[1].getId());
// HERE I HAVE OUTPUT
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
initialize();
}
private void initialize() {
frame = new JFrame("FreshPos baza podataka");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
// Main paneel
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder( BorderFactory.createEmptyBorder(10,10,10,10) );
frame.getContentPane().add(panel);
//West panel;
JPanel panelWest = new JPanel(new GridLayout(14,0,0,2));
panelWest.setBorder( BorderFactory.createEmptyBorder(200,0,10,10) );
panel.add(panelWest, BorderLayout.WEST);
for (int i = 0; i < MAX_TABLES; i++) {
buttonsTables[i] = new JButton(tables[i]);
//buttonsTables[i].setMaximumSize(new Dimension(Integer.MAX_VALUE, buttonsTables[i].getMinimumSize().height));
//buttonsTables[i].setPreferredSize(new Dimension(200,400));
panelWest.add(buttonsTables[i]);
}
buttonsTables[0].addActionListener(this); // HERE I CLICK ON BUTTON!!
//North panel;
JPanel northPanel = new JPanel(); // Donji layout za dugmice
northPanel.setBorder( BorderFactory.createEmptyBorder(0,0,0,0) );
panel.add(northPanel, BorderLayout.NORTH);
//northPanel.setBackground(Color.green);
buttonImport = new JButton("Importuj datoteku");
buttonImport.setPreferredSize(new Dimension(180,40));
northPanel.add(buttonImport, BorderLayout.WEST);
buttonImport.addActionListener(this);
JButton ButtonRecord = new JButton("Snimi datoteku");
ButtonRecord.setPreferredSize(new Dimension(180,40));
northPanel.add(ButtonRecord, BorderLayout.WEST);
}
public void showGrupaArtikala () {
centerPanel.removeAll();
centerPanel.updateUI();
centerPanel.setBackground(Color.GRAY);
panel.add(centerPanel, BorderLayout.CENTER);
JPanel southInCentral = new JPanel(); // Donji layout za dugmice
centerPanel.add(southInCentral, BorderLayout.SOUTH);
JButton buttonDodaj = new JButton("Dodaj");
//buttonDodaj.setLocation(100, 100);
buttonDodaj.setPreferredSize(new Dimension(180,40));
southInCentral.add(buttonDodaj);
JButton buttonIzmeni = new JButton("Izmeni");
buttonIzmeni.setPreferredSize(new Dimension(180,40));
southInCentral.add(buttonIzmeni);
JButton butonObrisi = new JButton("Obrisi");
butonObrisi.setPreferredSize(new Dimension(180,40));
southInCentral.add(butonObrisi);
// Center layout in central panel
JPanel centralInCentral = new JPanel(); //
centerPanel.add(centralInCentral);
// Jtable
String[] columnNames = {"ID,",
"SIFRA",
"NAZIV",
"IKONA_ID"};
Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe", "Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)}
};
JTable table = new JTable(data, columnNames);
//JTable(Object[][] rowData, Object[] columnNames)
JScrollPane scrollPane = new JScrollPane(table);
centerPanel.add(scrollPane);
panel.repaint();
panel.revalidate();
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == buttonsTables[0]) {
System.out.println("String here "+ objektiArtikli[1].getId()); // HERE OUTPUT IS NULL
showGrupaArtikala();
} else if (e.getSource() == buttonImport) {
System.out.println("aa");
createAndShowPodesavanja();
}
}
}
GuiFileChooser Class
public class GuiFileChooser {
private JFrame frame;
JTextField jEditText;
public GuiFileChooser () {
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GuiFileChooser window = new GuiFileChooser();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void fileChoose(ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
int i=chooser.showOpenDialog(frame);
if(i==JFileChooser.APPROVE_OPTION){
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
MainGui m = new MainGui();
m.pars(filename); // HERE I CALL pars(filename) in MainGui method
jEditText.setText(filename);
}
}
void initialize() {
frame = new JFrame();
frame.setTitle("Dodaj datoteku");
frame.setBounds(750, 350, 460, 150); // top
//Dimension d = new Dimension(440, 200);
// Dimension d1 = new Dimension(451, 451);
frame.setResizable(false);
//frame.setPreferredSize(d);
//frame.setMinimumSize(d);
// frame.setMaximumSize(d1);
// frame.setSize(450, 450);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton lblNaziv = new JButton("Izaberite datoteku..");
lblNaziv.setBounds(10 ,10, 160, 25); // horizontalna margina , vertikalna margina , visina, duzina
lblNaziv.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileChoose(evt);
}
});
frame.getContentPane().add(lblNaziv);
jEditText = new JTextField();
jEditText.setBounds(180 ,10, 250, 25); // horizontalna margina , vertikalna margina , visina, duzina
frame.getContentPane().add(jEditText);
JButton buttonOk = new JButton("OK");
buttonOk.setBounds(180,50, 100, 30); // horizontalna margina , vertikalna margina ,
frame.getContentPane().add(buttonOk);
buttonOk.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
frame.dispose();
}
});
}
public void setVisible(boolean b) {
frame.setVisible(b);
}
}
Can I scroll a JPanel using JButtons added to a JToolBar?
When I generate a large number of thumbnails, they don't all fit onto the JPanel. I want to use an up/down arrow JButton to scroll. Can this be done, and if so, how?
NOTE: I am trying to do this without a JScrollPane because I want the custom arrow icons, not a standard scroll bar.
Here is an SSCCE:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class PicSlider2 {
private JButton thumbs;
private JButton[] thumbnails;
private JLabel picViewer;
private JPanel thumbPanel;
private JToolBar toolBar;
public PicSlider2() {
final JFrame frame = new JFrame("Picture Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
frame.setResizable(false);
frame.setLayout(new BorderLayout());
picViewer = new JLabel();
picViewer.setText("Image here");
picViewer.setHorizontalAlignment(JLabel.CENTER);
picViewer.setVerticalAlignment(JLabel.BOTTOM);
picViewer.setBorder(new LineBorder(Color.BLACK, 2));
JMenuBar frameMenuBar = new JMenuBar();
frame.setJMenuBar(frameMenuBar);
JMenu file = new JMenu("File");
frameMenuBar.add(file);
JMenuBar picViewerMenu = new JMenuBar();
picViewerMenu.setLayout(new FlowLayout(FlowLayout.LEFT));
thumbs = new JButton("THUMBNAILS");//an icon in actual program
thumbs.setPreferredSize(new Dimension(150,45));
thumbs.setToolTipText("Thumbnails");
thumbs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
picViewer.setVisible(false);
thumbPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
thumbPanel.setBorder(BorderFactory.createEmptyBorder(50,100,50,30));
thumbnails = new JButton[30];//example size, chosen so all buttons won't fit on one page
for (int i = 0; i < 30; i++) {
thumbnails[i] = new JButton(Integer.toString(i));
thumbnails[i].setPreferredSize(new Dimension(100, 100));
thumbnails[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("thumbnail clicked - opens full-size view of pic in the JLabel picViewer");
}
});
thumbPanel.add(thumbnails[i]);
thumbPanel.setVisible(true);
}
toolBar = new JToolBar(null, JToolBar.VERTICAL);
toolBar.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 30));
JButton up = new JButton("Up Arrow");
up.setPreferredSize(new Dimension(80,60));
up.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Up Arrow Stub - NEEDS TO SCROLL UP PAGE, as needed");
}
} );
JButton down = new JButton("Down Arrow");
down.setPreferredSize(new Dimension(80,60));
down.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Down Arrow Stub - NEEDS TO SCROLL DOWN PAGE, as needed");
}
} );
toolBar.add(Box.createGlue());
toolBar.add(up);
toolBar.add(Box.createVerticalStrut(40));
toolBar.add(down);
toolBar.add(Box.createGlue());
frame.getContentPane().add(thumbPanel, BorderLayout.CENTER);
frame.getContentPane().add(toolBar, BorderLayout.LINE_END);
}
});
picViewerMenu.add(thumbs);
frame.getContentPane().add(picViewerMenu, BorderLayout.SOUTH);
frame.add(picViewer, BorderLayout.CENTER);
frame.setLocation(300, 50);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PicSlider2 ps = new PicSlider2();
}
});
}
}
I am trying to do this without a JScrollPane because I want the custom arrow icons
You can use a JScrollPane and use the default scroll Action to create a button with your custom Icon:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class ScrollPaneSSCCE extends JPanel
{
public ScrollPaneSSCCE()
{
setLayout( new BorderLayout() );
JTable table = new JTable(50, 5);
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
add(scrollPane);
JScrollBar vertical = scrollPane.getVerticalScrollBar();
JPanel east = new JPanel( new BorderLayout() );
add(east, BorderLayout.EAST);
JButton north = new JButton( new ActionMapAction("UP", vertical, "negativeUnitIncrement") );
east.add(north, BorderLayout.NORTH);
JButton south = new JButton( new ActionMapAction("DOWN", vertical, "positiveUnitIncrement") );
east.add(south, BorderLayout.SOUTH);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("ScrollPaneSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ScrollPaneSSCCE());
frame.setSize(200, 300);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You will need the Action Map Action class which is just a simple wrapper class that gets the default Action from the ActionMap of the specified component.
You will need to set the scroll increment for you panel. Since your image size is 100 you might want to use:
vertical.setUnitIncrement( 100 );
I found a way to achieve your desired result by reordering the items on the JPanel. The JFrame needs to be declared outside of the constructor. I added an index variable for tracking the scroll position and a reloadThumbs() method for reloading the reordered thumbs.
This is the entire code after the changes:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class PicSlider2 {
private JButton thumbs;
private JButton[] thumbnails;
private JLabel picViewer;
private JPanel thumbPanel;
private JToolBar toolBar;
private int scrollIndex;
private final JFrame frame;
public PicSlider2() {
scrollIndex = 0;
frame = new JFrame("Picture Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
frame.setResizable(false);
frame.setLayout(new BorderLayout());
picViewer = new JLabel();
picViewer.setText("Image here");
picViewer.setHorizontalAlignment(JLabel.CENTER);
picViewer.setVerticalAlignment(JLabel.BOTTOM);
picViewer.setBorder(new LineBorder(Color.BLACK, 2));
JMenuBar frameMenuBar = new JMenuBar();
frame.setJMenuBar(frameMenuBar);
JMenu file = new JMenu("File");
frameMenuBar.add(file);
JMenuBar picViewerMenu = new JMenuBar();
picViewerMenu.setLayout(new FlowLayout(FlowLayout.LEFT));
thumbs = new JButton("THUMBNAILS");//an icon in actual program
thumbs.setPreferredSize(new Dimension(150,45));
thumbs.setToolTipText("Thumbnails");
thumbs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
picViewer.setVisible(false);
thumbPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
thumbPanel.setBorder(BorderFactory.createEmptyBorder(50,100,50,30));
thumbnails = new JButton[30];//example size, chosen so all buttons won't fit on one page
for (int i = 0; i < 30; i++) {
thumbnails[i] = new JButton(Integer.toString(i));
thumbnails[i].setPreferredSize(new Dimension(100, 100));
thumbnails[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("thumbnail clicked - opens full-size view of pic in the JLabel picViewer");
}
});
thumbPanel.add(thumbnails[i]);
thumbPanel.setVisible(true);
}
toolBar = new JToolBar(null, JToolBar.VERTICAL);
toolBar.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 30));
JButton up = new JButton("Up Arrow");
up.setPreferredSize(new Dimension(80,60));
up.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Up Arrow Stub - NEEDS TO SCROLL UP PAGE, as needed");
if(scrollIndex > 3) scrollIndex -= 4;
else scrollIndex = 0;
reloadThumbs();
}
} );
JButton down = new JButton("Down Arrow");
down.setPreferredSize(new Dimension(80,60));
down.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Down Arrow Stub - NEEDS TO SCROLL DOWN PAGE, as needed");
if(scrollIndex < 27) scrollIndex += 4;
else scrollIndex = 30;
reloadThumbs();
}
} );
toolBar.add(Box.createGlue());
toolBar.add(up);
toolBar.add(Box.createVerticalStrut(40));
toolBar.add(down);
toolBar.add(Box.createGlue());
frame.getContentPane().add(thumbPanel, BorderLayout.CENTER);
frame.getContentPane().add(toolBar, BorderLayout.LINE_END);
}
});
picViewerMenu.add(thumbs);
frame.getContentPane().add(picViewerMenu, BorderLayout.SOUTH);
frame.add(picViewer, BorderLayout.CENTER);
frame.setLocation(300, 50);
frame.pack();
frame.setVisible(true);
}
private void reloadThumbs(){
thumbPanel.removeAll();
for(int i = scrollIndex; i < 30; ++i){
thumbPanel.add(thumbnails[i]);
}
for(int i = 0; i < scrollIndex; ++i){
thumbPanel.add(thumbnails[i]);
}
thumbPanel.revalidate();
frame.revalidate();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PicSlider2 ps = new PicSlider2();
}
});
}
}
I have been googling an sherthing for an solution to this problem a lot but can't find any answer how to fix this. My problem is that when i start a new jframe from an actionevent from pressing a button the class white the JFrame opens but then the programs starts to freeze and the pop up windows stays blank.
Her is the cod i apologize if there is some bad programing or some words in swedish:
The start upp class:
import java.util.ArrayList;
public class maineClassen {
ArrayList<infoClass> Infon = new ArrayList<>();
public static void main (String [] args)
{
referenser referens = new referenser();
Startskärmen ss = new Startskärmen(referens);
}
}
The "startskärm" the first screen to com to:
public class Startskärmen extends JFrame implements ActionListener {
referenser referens;
ArrayList<infoClass> Infon;
JButton öppna = new JButton("open");
JButton ny = new JButton("create new");
JButton radera = new JButton("erase");
JScrollPane pane = new JScrollPane();
DefaultListModel mod = new DefaultListModel();
JList list = new JList(mod);
JScrollPane sp = new JScrollPane(list);
JLabel texten = new JLabel("pre-alpha 0.1");
public Startskärmen(referenser re)
{
//references should be sent by itself or received
referens = re;
Infon = referens.getInfoReferens();
//build up the window
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.LINE_AXIS));
labelPanel.setBorder(BorderFactory.createEmptyBorder(10,10,0,10));
labelPanel.add(texten);
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.LINE_AXIS));
scrollPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
scrollPanel.add(sp);// man kan ocksä sätta in --> pane <--
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(öppna);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(ny);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(radera);
Container contentPane = getContentPane();
contentPane.add(labelPanel,BorderLayout.NORTH);
contentPane.add(scrollPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(500, 500);
//adda action listener
ny.addActionListener(this);
öppna.addActionListener(this);
radera.addActionListener(this);
//skapaNyIC();
}
infoClass hh;
public void skapaNyIC()
{
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ny)
{
skapaNyIC();
}
else if(e.getSource() == öppna)
{
JOptionPane.showMessageDialog(texten,"This function doesn't exist yet");
}
else if(e.getSource() == radera)
{
JOptionPane.showMessageDialog(texten, "This function doesn't exist yet");
}
}
}
The class where the information will be stored and that creates the window (class) that will show the info:
public class infoClass {
ArrayList<infoClass> Infon;
private infoClass ic;
private String namn = "inget namn existerar";
private String infoOmInfo = null;
private int X_Rutor = 3;
private int Y_Rutor = 3;
private String[] information = new String[X_Rutor + Y_Rutor];
//info om dessa värden
public infoClass()
{
}
public void referenser(infoClass Tic)
{
ic = Tic;
infonGrafiskt ig = new infonGrafiskt(ic);
}
public void referenser(ArrayList<infoClass> Tic)
{
ic = Tic.get((Tic.size() - 1 ));
System.out.println("inna");
infonGrafiskt ig = new infonGrafiskt(ic);
ig.setVisible(true);
System.out.println("efter");
}
public String namnPåInfon()
{
return namn;
}
//namnen
public String getName()
{
return namn;
}
public void setNamn(String n)
{
namn = n;
}
//xkordinaterna
public int getX_Rutor()
{
return X_Rutor;
}
public void setX_Rutor(int n)
{
X_Rutor = n;
}
//y kordinaterna
public int getY_Rutor()
{
return Y_Rutor;
}
public void setY_Rutor(int n)
{
Y_Rutor = n;
}
//informationen
public String[] getInformationen()
{
return information;
}
public void setInformationen(String[] n)
{
information = n;
}
//infoOmInfo
public String getinfoOmInfo()
{
return infoOmInfo;
}
public void setinfoOmInfo(String n)
{
infoOmInfo = n;
}
}
The class that will show the info created by the window a bow:
public class infonGrafiskt extends JFrame implements ActionListener{
infoClass ic;
infonGrafiskt ig;
//tillrutnätet
JPanel panel = new JPanel(new SpringLayout());
boolean pausa = true;
//sakerna till desigen grund inställningar GI = grund inställningar
JButton GIklarKnapp = new JButton("Spara och gå vidare");
JTextField GInamn = new JTextField();
JLabel GINamnText = new JLabel("Namn:");
JTextField GIxRutor = new JTextField();
JLabel GIxRutorText = new JLabel("Antal rutor i X-led:");
JTextField GIyRutor = new JTextField();
JLabel GIyRutorText = new JLabel("Antal rutor i Y-led:");
JLabel GIInfo = new JLabel("Grund Inställningar");
// de olika framm:arna
JFrame GIframe = new JFrame("SpringGrid");
JFrame frame = new JFrame("SpringGrid");
//info om denna infon som finns här
JTextArea textArea = new JTextArea();
JScrollPane infoOmClasen = new JScrollPane(textArea); //hadde text area förut
JLabel infoRutan = new JLabel("Informatin om denna resuldatdatabank:");
//namnet på informationsdatabanken
JLabel namnetPåInfot = new JLabel("Namnet på denna resuldatdatabas.");
JButton ändraNamn = new JButton("Ändra namn");
JButton sparaAllt = new JButton("Spara allt");
public infonGrafiskt(infoClass Tic)
{
//få startinfo
namnOchRutor();
ic = Tic;
//skapar om rutan
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
p1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
namnetPåInfot.setFont(new Font("Dialog",1,22));
p1.add(namnetPåInfot);
//pausa programet tills grundinställningarna är instälda
int m =1;
try {
while(m ==1)
{
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
//Create the panel and populate it. skapar den så alla kommer åt den
//JPanel panel = new JPanel(new SpringLayout());
for (int i = 0; i < ic.getX_Rutor()*ic.getY_Rutor(); i++) {
JTextField textField = new JTextField(Integer.toString(i));
panel.add(textField);
}
//Lay out the panel.
SpringUtilities.makeGrid(panel,
ic.getY_Rutor(), ic.getX_Rutor(), //rows, cols
5, 5, //initialX, initialY
5, 5);//xPad, yPad
//set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//p1.add(ändraNamn);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS));
p2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
p2.add(infoRutan);
infoOmClasen.setPreferredSize(new Dimension(0,100));
p2.add(infoOmClasen);
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
p3.setLayout(new BoxLayout(p3, BoxLayout.LINE_AXIS));
p3.add(ändraNamn);
p3.add(sparaAllt);
//Set up the content pane.
panel.setOpaque(true); //content panes must be opaque
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.add(p1);
frame.add(p2);
frame.add(panel);//frame.setContentPane(panel);
frame.add(p3);
//Display the window.
frame.pack();
sparaAllt.addActionListener(this);
ändraNamn.addActionListener(this);
}
private void namnOchRutor()
{
System.out.println("inna 2");
//sättigång action listner
GIklarKnapp.addActionListener(this);
frame.setVisible(false);
//frameStart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GIframe.setLayout(new BoxLayout(GIframe.getContentPane(), BoxLayout.PAGE_AXIS));
JPanel GIP0 = new JPanel();
GIP0.setLayout(new BoxLayout(GIP0,BoxLayout.LINE_AXIS));
GIP0.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP0.add(GIInfo);
GIInfo.setFont(new Font("Dialog",1,22));
JPanel GIP1 = new JPanel();
GIP1.setLayout(new BoxLayout(GIP1,BoxLayout.LINE_AXIS));
GIP1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP1.add(GINamnText);
GIP1.add(Box.createRigidArea(new Dimension(10, 0)));
GIP1.add(GInamn);
JPanel GIP2 = new JPanel();
GIP2.setLayout(new BoxLayout(GIP2,BoxLayout.LINE_AXIS));
GIP2.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP2.add(GIxRutorText);
GIP2.add(Box.createRigidArea(new Dimension(10, 0)));
GIP2.add(GIxRutor);
JPanel GIP3 = new JPanel();
GIP3.setLayout(new BoxLayout(GIP3,BoxLayout.LINE_AXIS));
GIP3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP3.add(GIyRutorText);
GIP3.add(Box.createRigidArea(new Dimension(10, 0)));
GIP3.add(GIyRutor);
JPanel GIP4 = new JPanel();
GIP4.setLayout(new BoxLayout(GIP4,BoxLayout.LINE_AXIS));
GIP4.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP4.add(GIklarKnapp);
System.out.println("inna 3");
//lägga till sakerna gurund instllnings framen
GIframe.add(GIP0);
GIframe.add(GIP1);
GIframe.add(GIP2);
GIframe.add(GIP3);
GIframe.add(GIP4);
//desigen
System.out.println("inna 4");
GIframe.pack();
GIframe.setVisible(true);
System.out.println("inna5");
}
/*public static void main (String [] args)
{
infoClass i = new infoClass();
infonGrafiskt ig = new infonGrafiskt(i);
}*/
public void referenserna( infonGrafiskt Tig)
{
ig = Tig;
}
private void skrivTillbaka()
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
((JTextField)children[i]).setText(tillfäligString[i]);
System.out.println(tillfäligString[i]);
}
}
namnetPåInfot.setText(ic.getName());
textArea.setText(ic.getinfoOmInfo());
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == GIklarKnapp)
{
//skicka x och y antal ett och så
ic.setNamn(GInamn.getText());
ic.setX_Rutor(Integer.parseInt(GIxRutor.getText()));
ic.setY_Rutor(Integer.parseInt( GIyRutor.getText()));
namnetPåInfot.setText(ic.getName());
pausa = false;
GIframe.setVisible(false);
frame.setVisible(true);
}
if(e.getSource() == sparaAllt)
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
tillfäligString[i] = ((JTextField)children[i]).getText();
System.out.println(tillfäligString[i]);
}
}
ic.setInformationen(tillfäligString);
ic.setNamn(namnetPåInfot.getText());
ic.setinfoOmInfo(textArea.getText());
}
if(e.getSource() == ändraNamn)
{
skrivTillbaka();
}
}
}
so my problem now is that i can't create a new "infoclass" that will show the info in the "infoGrafikst" class. with the code:
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
that am triggered by an button click.
Sorry for all the cod, but didn't know how to show my problem in another way.
Thanks a lot. I did find out that it was this code
int m =1;
try {
while(m ==1) {
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
that made it not work...
Well I haven't gone through your code may be beacuse I am too lazy to read pages of code.Well i think the new window you are creating must be interfering with EDT.
Well i have done a short example which may help you, and its smooth:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameLaunch {
void inti(){
final JFrame f=new JFrame();
final JFrame f2=new JFrame();
final JTextArea ja=new JTextArea();
JButton b =new JButton("press for a new JFrame");
f2.add(b);
f2.pack();
f2.setVisible(true);
b.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e) {
f2.setVisible(false);
f.setSize(200,200);
ja.setText("THIS IS NOT FROZEN");
f.add(ja);
f.setVisible(true);
f.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args)
{
FrameLaunch frame = new FrameLaunch();
frame.inti();
}
}
I am new to Java Swing and I am trying to create an application.
I have a MainApplication.java file which extends SingleFrameApplication and where I am creating a JPanel named MainPanel. This MainPanel has an AnimatingSplitPane with VERTICAL_SPLIT named SplitPane.
On the Top of the SplitPane, I am adding another JPanel named MainContainer. On the bottom of the SplitPane, I am adding a JPanel named FormContainer. The MainContainer loads the another class named DataSheetTable (a JPanel having JTable).
Now, when user clicks on the cells of the DataSheetTable, I want to load the form into the FormContainer. I don't know, how can I achieve this.
For instance, DatasheetTable has Column1, Column2 and Column3. When user clicks on any cell of Column1, I need to show Form1 into the FormContanier. If it clicks on Column2 cell then I need to show Form2 into FormContanier.
Please let me know with some sample code, how can I achieve loading the forms on the fly to FormContainer.
![Thank you in advance.]
Image description for the issue
Here is sample code for App.java
public class App extends SingleFrameApplication {
#Override protected void startup() {
configureDefaults();
View view = getMainView();
view.setComponent(createMainPanel());
show(view);
}
protected JComponent createMainPanel() {
// Create main panel with demo selection on left and demo/source on right
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Create splitpane on right to hold demo and source code
splitPane = new AnimatingSplitPane(JSplitPane.VERTICAL_SPLIT);
mainPanel.add(splitPane, BorderLayout.CENTER);
// Create panel to contain main panel
mainContainer = new JPanel();
splitPane.setTopComponent(mainContainer);
DataSheetTable dataSheetTable = new DataSheetTable();
mainContainer.add(dataSheetTable, BorderLayout.CENTER);
dataSheetTable.start();
formContainer = new JPanel(new BorderLayout());
splitPane.setBottomComponent(formContainer);
formContainer.add(new OrganizationForm());
return mainPanel;
}
}
Here is sample code for DataSheetTable.java file
public class DataSheetTable extends JPanel {
........
controlPanel = createControlPanel();
add(controlPanel, BorderLayout.NORTH);
routingTable = new JTable(routingModel);
.........
}
So here is your code for intercepting events of table cell clicks:
public class App extends JFrame {
private DefaultTableModel model = new DefaultTableModel(new Object[][] {
{ "Value1", "Value2", "Value3" }, { "Object1", "Object2", "Object3" } }, new String[] {
"Column1", "Column2", "Column3" });
private JTable table = new JTable(model);
private JPanel bottomPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
App a = new App();
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
}
public App() {
JSplitPane pane = new JSplitPane();
pane.setOrientation(SwingConstants.HORIZONTAL);
pane.setLeftComponent(new JScrollPane(table));
bottomPanel = new JPanel();
bottomPanel.add(new JLabel("properties for column will be here"));
pane.setRightComponent(bottomPanel);
add(pane);
ListSelectionListener listener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int column = table.getSelectedColumn();
int row = table.getSelectedRow();
if(row != -1 && column != -1) {
bottomPanel.removeAll();
//Here you add your components/create appropriate panel
//e.g. bottomPanel.add(new PropertiesPanelForValue1(...));
bottomPanel.add(new JLabel("User selected column " + column + " and row " + row
+ " with value: '" + table.getValueAt(row, column) + "'"));
bottomPanel.revalidate();
}
}
};
table.getSelectionModel().addListSelectionListener(listener);
table.getColumnModel().getSelectionModel().addListSelectionListener(listener);
pack();
pane.setDividerLocation(0.3);
setSize();
}
private void setSize() {
double widthPart = 0.3;
double heightPart = 0.5;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) (screenSize.getWidth() * widthPart);
int height = (int) (screenSize.getHeight() * heightPart);
setSize(width, height);
Dimension windowSize = getSize();
int x = (int) ((screenSize.getWidth() - windowSize.getWidth()) / 2);
int y = (int) ((screenSize.getHeight() - windowSize.getHeight()) / 2);
setLocation(x, y);
}
}
EDIT
Looking at your update: Just add to DataSheetTable constructor reference to your FormContainer:
formContainer = new JPanel(new BorderLayout());
splitPane.setBottomComponent(formContainer);
formContainer.add(new OrganizationForm());
DataSheetTable dataSheetTable = new DataSheetTable(formContainer);
mainContainer.add(dataSheetTable, BorderLayout.CENTER);
dataSheetTable.start();
and in DataSheetTable add listener:
public class DataSheetTable extends JPanel {
public DataSheetTable(final FormContainer formContainer) {
........
controlPanel = createControlPanel();
add(controlPanel, BorderLayout.NORTH);
routingTable = new JTable(routingModel);
ListSelectionListener listener = new ListSelectionListener() {...};
routingTable.getSelectionModel().addListSelectionListener(listener);
routingTable.getColumnModel().getSelectionModel().addListSelectionListener(listener);
.........
}
}