JScrollPane on dynamic filled JPanel with null layout - java

i want a scrollpane on my GUI. The area, i want to have "scrollable" is a JPanel without any LayoutManager, because the content is something between static and dynamic... but maybe a part of my code will help
Here it is:
pane = getContentPane();
jpane = new JPanel();
// jpane.setBounds(0, 75, 680, 255);
jpane.setLayout(null);
jsp = new JScrollPane(jpane, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setBounds(0, 75, 680, 255);
jsp.setPreferredSize(new Dimension(680,255));
pane.add(jsp);
My JPanel will be filled with this piece of code...
for(int i = 0; i < Integer.parseInt(spaltenzahl.getText()); i++) {
JTextField spaltennamen_feld = new JTextField();
spaltennamen_feld.setBounds(10, 10+35*i, 150, 25);
spaltennamen_arraylist.add(spaltennamen_feld);
JComboBox<String> datentypen_box = new JComboBox<String>(types);
datentypen_box.setBounds(170, 10+35*i, 150, 25);
datentypen_arraylist.add(datentypen_box);
JComboBox<String> datenzusatz_box = new JComboBox<String>(comb);
datenzusatz_box.setBounds(330, 10+35*i, 100, 25);
datenzusatz_arraylist.add(datenzusatz_box);
jpane.add(spaltennamen_feld);
jpane.add(datentypen_box);
jpane.add(datenzusatz_box);
}
Problem: i can't add a screenshot of my GUI, cause of missing ehr... i forgot the name of this required things here ^_^
But i the real problem is: overflowing content won't be displayed on my JPanel and my ScrollPane does not scroll. Any idea?
Thanks alot :)

Your solution is none of the above. I think that you want to use a JTable, one with three columns, the last two whose editor is a JComboBox.
Edit
For example:
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Foo2 {
private static void createAndShowGui() {
String[] columns = {"Spaltennamen", " Datentypen", "Datenzusatz"};
String[] dataStrings1 = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
String[] dataStrings2 = {"One", "Two", "Three", "Four", "Five"};
Random random = new Random();
DefaultTableModel model = new DefaultTableModel(columns, 0);
int spaltenzahl = 10; // this can change
for (int i = 0; i < spaltenzahl; i++) {
Vector<String> rowData = new Vector<>();
rowData.add("Row Number " + (i + 1));
rowData.add(dataStrings1[random.nextInt(dataStrings1.length)]);
rowData.add(dataStrings2[random.nextInt(dataStrings2.length)]);
model.addRow(rowData);
}
JTable table = new JTable(model);
table.getColumn(columns[1]).setCellEditor(new DefaultCellEditor(new JComboBox<>(dataStrings1)));
table.getColumn(columns[2]).setCellEditor(new DefaultCellEditor(new JComboBox<>(dataStrings2)));
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Related

Why can't I add buttons to my GridLayout JPanel?

I am trying to add 24 JButtons to the GridLayout of my JPanel buttonPanel, but when I run it, I see that no buttons are added. (At least, they are not visible!). I tried giving the buttonPanel a background color, and it
was visible.
Does anyone know what I'm doing wrong?
This is my code (there is an other class):
package com.Egg;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class NormalCalc implements ActionListener {
static JPanel normalCalcPanel = new JPanel();
JPanel buttonPanel = new JPanel(new GridLayout(6,4,10,10));
Font font = new Font("Monospaced Bold", Font.BOLD, 18);
JButton powB = new JButton("^");
JButton sqrtB = new JButton("sqrt(");
JButton hOpenB = new JButton("(");
JButton hCloseB = new JButton(")");
JButton delB = new JButton("DEL");
JButton acB = new JButton("AC");
JButton mulB = new JButton("*");
JButton divB = new JButton("/");
JButton addB = new JButton("+");
JButton minB = new JButton("-");
JButton decB = new JButton(".");
JButton equB = new JButton("=");
JButton negB = new JButton("(-)");
JButton[] numberButtons = new JButton[10];
JButton[] functionButtons = new JButton[13];
public NormalCalc() {
functionButtons[0] = powB;
functionButtons[1] = delB;
functionButtons[2] = acB;
functionButtons[3] = sqrtB;
functionButtons[4] = mulB;
functionButtons[5] = divB;
functionButtons[6] = hOpenB;
functionButtons[7] = addB;
functionButtons[8] = minB;
functionButtons[9] = hCloseB;
functionButtons[10] = decB;
functionButtons[11] = negB;
functionButtons[12] = equB;
for (int i=0; i<10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].setFocusable(false);
numberButtons[i].setFont(font);
numberButtons[i].addActionListener(this);
}
for (int i=0; i <13; i++) {
functionButtons[i].setFocusable(false);
functionButtons[i].setFont(font);
functionButtons[i].addActionListener(this);
}
normalCalcPanel.setBounds(0, 0, 500, 700);
buttonPanel.setBounds(50, 200, 400, 400);
// Adding the buttons;
buttonPanel.add(functionButtons[0]);
buttonPanel.add(numberButtons[7]);
buttonPanel.add(numberButtons[8]);
buttonPanel.add(numberButtons[9]);
buttonPanel.add(functionButtons[1]);
buttonPanel.add(functionButtons[2]);
buttonPanel.add(functionButtons[3]);
buttonPanel.add(numberButtons[4]);
buttonPanel.add(numberButtons[5]);
buttonPanel.add(numberButtons[6]);
buttonPanel.add(functionButtons[4]);
buttonPanel.add(functionButtons[5]);
buttonPanel.add(functionButtons[6]);
buttonPanel.add(numberButtons[1]);
buttonPanel.add(numberButtons[2]);
buttonPanel.add(numberButtons[3]);
buttonPanel.add(functionButtons[7]);
buttonPanel.add(functionButtons[8]);
buttonPanel.add(functionButtons[9]);
buttonPanel.add(numberButtons[0]);
buttonPanel.add(functionButtons[10]);
buttonPanel.add(functionButtons[11]);
buttonPanel.add(functionButtons[12]);
buttonPanel.repaint();
normalCalcPanel.add(buttonPanel);
normalCalcPanel.add(MainMath.exitButton);
MainMath.frame.add(normalCalcPanel);
MainMath.frame.repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
Other (main) class:
package com.Egg;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MainMath implements ActionListener {
static JFrame frame = new JFrame("Math Tools");
static JButton exitButton = new JButton("Exit");
JPanel mainPanel = new JPanel();
JLabel mainLabel = new JLabel("Select your tool.", SwingConstants.CENTER);
JButton nB = new JButton("Normal Calc.");
JButton tB = new JButton("Right Triangle Calc.");
JButton eB = new JButton("Equations Calc.");
public MainMath() {
frame.setBounds(300, 300, 500, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setResizable(false);
mainPanel.setLayout(null);
mainPanel.setBounds(0, 0, 500, 700);
mainLabel.setBounds(100, 25, 300, 50);
mainLabel.setFont(new Font("Monospaced Bold", Font.BOLD, 18));
nB.setBounds(100, 100, 300, 40);
tB.setBounds(100, 150, 300, 40);
eB.setBounds(100, 200, 300, 40);
nB.setFocusable(false);
tB.setFocusable(false);
eB.setFocusable(false);
nB.addActionListener(this);
tB.addActionListener(this);
eB.addActionListener(this);
mainPanel.add(mainLabel);
mainPanel.add(nB);
mainPanel.add(tB);
mainPanel.add(eB);
frame.add(mainPanel);
frame.setVisible(true);
exitButton.setBounds(16, 10, 80, 35);
exitButton.setFocusable(false);
exitButton.addActionListener(this);
}
public static void main(String[] args) {
new MainMath();
System.out.println("");
}
public void setMainScreen() {
frame.remove(exitButton);
frame.remove(NormalCalc.normalCalcPanel);
frame.add(mainPanel);
frame.repaint();
}
public static JFrame getFrame() {
return frame;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exitButton)
setMainScreen();
if (e.getSource() == nB) {
frame.remove(mainPanel);
new NormalCalc();
}
if (e.getSource() == tB)
new TriangleCalc();
if (e.getSource() == eB)
new EquationCalc();
}
}
I see multiple issues in your code:
Your arrangement of your buttons is weird looking at first glance.
normalCalcPanel is static, why? It should never be
setBounds(...) when using layout managers, those statements are ignored, so no need for them
repaint() unless you've added / removed any element AFTER you've displayed your GUI, these calls are unnecessary, and should come with revalidate() as well.
MainMath.exitButton another static component, STOP
MainMath.frame.add(normalCalcPanel) implies that your JFrame called frame is static as well, which again, shouldn't be
And (I'm gonna guess here) more than probably you're creating a second instance inside MainMath, but because we don't have the code from that class we don't know what's going on
I ran your code and it looks ok, so that's why I believe your MainMath is creating another instance of JFrame
Here's an example of a calculator arrangement, that should help you to structure your code similarly, not the GUI but the components and classes
Edit
Okay, I understand now that I should not use static things, but how can I add a panel to a frame which I created in another class? I used 'static', because it seemed to work
Let's make an analogy for this case, imagine that your JFrame is a book, and that your JPanels are the sheets of that book, when you write on those sheets, you don't add / paste the book to the sheets, you add the sheets to the book.
So, in this case it's the same, your main class should create the JPanels and add those to your JFrame, your JPanel classes shouldn't have knowledge of your JFrame
In the case of the book, your sheets don't need to know to which book the belong, you know that and the book knows which sheets belong to it, not viceversa.
I made an example to show you what I mean by this, I didn't recreate your GUI but made it as simple as I could for you to get the idea:
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class AnotherCalculator {
private JFrame frame;
private CalculatorPanel calculatorPanel;
public static void main(String[] args) {
SwingUtilities.invokeLater(new AnotherCalculator()::createAndShowGUI);
}
private void createAndShowGUI() {
frame = new JFrame(getClass().getSimpleName());
calculatorPanel = new CalculatorPanel();
frame.add(calculatorPanel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class CalculatorPanel extends JPanel {
private String[] operations = {"+", "-", "*", "/", "DEL", "AC", "(", ")", "-", "^", "SQRT", ".", "+/-", "="};
private static final int NUMBER_OF_DIGITS = 10;
private JButton[] buttons;
public CalculatorPanel() {
this.setLayout(new GridLayout(0, 4, 5, 5));
buttons = new JButton[operations.length + NUMBER_OF_DIGITS];
for (int i = 0; i < buttons.length; i++) {
if (i < NUMBER_OF_DIGITS) {
buttons[i] = new JButton(String.valueOf(i));
} else {
buttons[i] = new JButton(operations[i - NUMBER_OF_DIGITS]);
}
this.add(buttons[i]);
}
}
}

populate DefaultTableModel after insert a row java

I am running a program with two frames. First one has a table, the second one has a form which allows adding a new user to the table. I think the problem is I didn't add a reference from the mainframe. I was trying different methods to refresh the mainframe programmatically, but it did not help so much. I read many articles on how to to it but I could find a solution. My table usually changes when I close my app and open it again. But I don't think is the right way to do it. I tried to delete elements from DefaultTableModel and populated jtable again, but did not get any results. Here is my code:
public Vector vector_jtable = new Vector();
public MainApp() {
initComponents();
Database b = new Database();
b.getAmountOfRows(getCount);
this.setLocationRelativeTo(null);
printResultDB();
}
//add function that is responsible for addding data to the table
public void postDataJtable() {
System.out.println("The vector is: " + vector_jtable);
Vector<String> header = new Vector<String>();
header.add("Number");
header.add("Name");
header.add("First Payment");
header.add("Next Payment");
header.add("Picture");
header.add("Phone");
header.add("Amount");
header.add("Age");
model = (DefaultTableModel)jTable2.getModel();
model.setDataVector(vector_jtable,header);
}
I created a vector that allows putting data from the second frame.
MainApp app;
public AddStudents(MainApp a) {
initComponents();
app = a;
this.setLocationRelativeTo(null);
jDateChooser1.setDateFormatString("yyyy-MM-dd");
jDateChooser2.setDateFormatString("yyyy-MM-dd");
}
After that, I push the button to send it out and update the mainframe, but nothing happened:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
app.vector_jtable.add(name);
app.vector_jtable.add(first_p);
app.vector_jtable.add(next_p);
app.vector_jtable.add(picture);
app.vector_jtable.add(phone);
app.vector_jtable.add(amount);
app.vector_jtable.add(age);
app.postDataJtable();
My question. How to add a row in jtable and refresh it. I really stuck in this topic. I need your help.
Don't update the Vector.
When you want to change the data in the table you need to change the data in the TableModel.
You can use the addRow(...) method of the DefaultTableModel to add a new row of data.
So the basic logic is:
Vector<Object> row = new Vector<Object>();
row.add( someVariable1 );
row.add( someVariable2 );
...
modal.addRow( row ):
The model will then tell the table to repaint itself.
Edit:
There is no trick all you need is a reference to the model. Then you update the model.
Here is a simple example to prove the concept works:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
private DefaultTableModel model;
SSCCE()
{
setLayout( new BorderLayout() );
model = new DefaultTableModel(0, 2);
JTable table = new JTable( model );
add(new JScrollPane( table ));
JButton button = new JButton( "Add Row" );
add(button, BorderLayout.PAGE_END);
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
Vector<Object> row = new Vector<Object>();
row.add( "" + model.getRowCount() );
row.add( new Date().toString() );
model.addRow( row );
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
If it doesn't work for you then you need to debug your code. Maybe you have two "model" variables? Maybe you have to "table" variables. Maybe your code isn't even executed. Did you add any debug statements to the code to make sure it is executed.
We can't solve your problem only point you in the right direction.
You can try some aspects from this example below. The example has two JFrame's - one with a JTable and the other the data entry fields. When the data is entered and the "UpdateTable" button is pressed (in the data entry class) the table is updated.
The example uses java.util.Observer and Observable to achieve this functionality.
The class with table:
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.util.Observer;
import java.util.Observable;
public class TableUpdateTester implements Observer {
private JTable table;
private static final Object[] TABLE_COLUMNS = {"Book", "Author"};
private static final Object [][] TABLE_DATA = {
{"Book 1", "author 1"}, {"Book 2", "author 1"}
};
public static void main(String [] args) {
TableUpdateTester tester = new TableUpdateTester();
new DataEntryClass(tester);
}
public TableUpdateTester() {
JFrame frame = new JFrame("Table Update Tester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(getTablePanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel getTablePanel() {
table = new JTable(new DefaultTableModel(TABLE_DATA, TABLE_COLUMNS));
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setPreferredSize(new Dimension(400, 150));
scrollpane.setViewportView(table);
JPanel panel = new JPanel();
panel.add(scrollpane);
return panel;
}
// This is Observer's override method.
#Override public void update(Observable o, Object arg) {
String [] data = (String []) arg;
System.out.println("Data recieving: " + java.util.Arrays.toString(data));
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(data);
}
}
The data entry class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Observable;
public class DataEntryClass {
public DataEntryClass(TableUpdateTester observer) {
final DataObservable observable = new DataObservable();
observable.addObserver(observer);
JLabel label = new JLabel("Book: ");
final JTextField text = new JTextField(15);
JLabel label2 = new JLabel("Author: ");
final JTextField text2 = new JTextField(15);
JButton button = new JButton("Update Table");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data1 = text.getText().isEmpty() ? "empty" : text.getText();
String data2 = text2.getText().isEmpty() ? "empty" : text2.getText();
String [] data = {data1, data2};
System.out.println("Data sent: " + java.util.Arrays.toString(data));
observable.changeData(data);
}
});
JPanel panel = new JPanel();
GridLayout grid = new GridLayout(3, 2);
panel.setLayout(grid);
panel.add(label);
panel.add(text);
panel.add(label2);
panel.add(text2);
panel.add(new JLabel(""));
panel.add(button);
JFrame frame = new JFrame();
frame.setTitle("Data Entry");
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.pack();
}
}
class DataObservable extends Observable {
DataObservable() {
super();
}
void changeData(Object data) {
// the two methods of Observable class
setChanged();
notifyObservers(data);
}
}
Finally, I found a solution to my problem. I will post my code here.
The Mainframe. I know the app with two frames is not a good option, because it's hard to fix the problem and it usually takes a lot of time to debug it.
/**
* Create the application.
*/
public MainApp() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 689, 345);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//add table in DefaultTableModel
model = new DefaultTableModel(0,2);
table = new JTable(model);
table.setBounds(58, 38, 524, 197);
frame.getContentPane().add(table);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 0, 4, 4);
frame.getContentPane().add(scrollPane);
JButton btnNewButton = new JButton("Add");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Call a second frame
//add reference for DefaultTableModel and send it to another frame
AddData frame = new AddData(model);
frame.setVisible(true);
}
});
btnNewButton.setBounds(239, 269, 117, 29);
frame.getContentPane().add(btnNewButton);
}
The second frame, that is responsible for adding a new row in a table.
/**
* Create the frame.
*/
public AddData(DefaultTableModel model) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(115, 71, 188, 41);
contentPane.add(dateChooser);
JButton btnNewButton = new JButton("Send");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//MainApp app = new MainApp();
Vector<Object> row = new Vector<Object>();
row.add(""+model.getRowCount());
row.add(dateChooser.getDate().toString());
model.addRow(row);
}
});
btnNewButton.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
btnNewButton.setBounds(165, 192, 117, 41);
contentPane.add(btnNewButton);
}
I found my mistake. I did not send a link of DefaultTableModel into the second frame. That's why it was null every time. It was a really painful experience, but I learned from my mistakes. Thanks, everyone for your help. I really appriciate.

background image hidding the other components like buttons labels and other, and vicce versa

how to solve hidding of components in this code
code is running without errors
but background image not displayed
how to change code to get the background image
when using validation method, its creating error in validation()
public class TEST{
public TEST() {
String[] strm = {"Jan", "Feb", "Mar", "Apr", "May"};
String[] stry = {"2016", "2017", "2018","2019"};
String[] strf={"NEW Delhi", "Bangalore", "Chennai"};
String[] strt={"Goa","Kashmir","Hyderabad"};
JFrame f = new JFrame("test");
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lfr = new JLabel("FROM");
JLabel lto = new JLabel("TO");
JLabel lda = new JLabel("DATE");
JLabel ld = new JLabel("DAY");
JLabel lm = new JLabel("MONTH");
JLabel y = new JLabel("YEAR");
JComboBox cfr = new JComboBox(strf);
JComboBox cto = new JComboBox(strt);
JComboBox cd = new JComboBox();
JComboBox cm = new JComboBox(strm);
JComboBox cy = new JComboBox(stry);
JButton bs = new JButton("Search");
JPanel p1 = new JPanel(null);
p1.setPreferredSize(new Dimension(500,500));
JLabel jimage = new JLabel();
jimage.setIcon(new ImageIcon("air.jpg"));
for(int i = 1; i <= 31; i++)
cd.addItem(i);
lfr.setBounds(20, 40, 100, 20);
cfr.setBounds(100, 40, 100, 20);
lto.setBounds(20, 100, 25, 20);
cto.setBounds(100, 100, 100, 20);
lda.setBounds(20, 160, 50, 20);
cd.setBounds(100, 160, 50, 20);
cm.setBounds(160, 160, 65, 20);
cy.setBounds(240, 160, 75, 20);
ld.setBounds(100, 190, 50, 20);
lm.setBounds(160, 190, 50, 20);
y.setBounds(240, 190, 50, 20);
bs.setBounds(20, 230, 100, 20);
p1.add(lfr);
p1.add(cfr);
p1.add(lto);
p1.add(cto);
p1.add(lda);
p1.add(cd);
p1.add(cm);
p1.add(cy);
p1.add(ld);
p1.add(lm);
p1.add(y);
p1.add(bs);
p1.add(jimage);
// validate();
f.add(p1);
f.setVisible(true);
}
public static void main(String[] args) {
new TEST();
}
}
The best you can do is something like:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
JLabel label;
JComboBox combo;
JButton button;
JPanel pane;
JFrame frame;
JPanel create1stRow() {
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
String options[] = {"New Delhi", "Bangalore", "Chennai"};
label = new JLabel("FROM");
combo = new JComboBox(options);
pane.add(label);
pane.add(combo);
return pane;
}
JPanel create2ndRow() {
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
String options[] = {"Goa", "Kashmir", "Hyderabad"};
label = new JLabel("TO");
combo = new JComboBox(options);
pane.add(label);
pane.add(combo);
return pane;
}
JPanel create3rdRow() {
JPanel pane = new JPanel();
JPanel dataPane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
dataPane.setOpaque(false); //forgot to add this line when I took the pic
dataPane.setLayout(new GridLayout(2, 3)); //2 rows, 3 cols, so we can have the combos with their text aligned
String days[] = {"1", "2", "3", "4", "5"}; //Too lazy to write 31 days
String months[] = {"Jan", "Feb", "Mar", "Apr", "May"}; //Too lazy to write 12 months
String years[] = {"2016", "2017", "2018", "2019", "2020"};
label = new JLabel("DATE");
combo = new JComboBox(days);
//We add the combos
dataPane.add(combo);
combo = new JComboBox(months); //We're reusing the object, but change the data
dataPane.add(combo);
combo = new JComboBox(years); //The same as above
dataPane.add(combo);
//Now we add the labels
dataPane.add(new JLabel("DAYS"));
dataPane.add(new JLabel("MONTHS"));
dataPane.add(new JLabel("YEARS"));
pane.add(label);
pane.add(dataPane); //We add the whole pane to another one
return pane;
}
JPanel create4thRow() {
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
button = new JButton("Search");
pane.add(button);
return pane;
}
public Test() {
frame = new JFrame("Test");
frame.setContentPane(new JLabel(new ImageIcon("C:/Users/Frakcool/workspace/StackOverflowProjects/src/test/Air.jpg")));
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
pane = create1stRow();
frame.add(pane);
pane = create2ndRow();
frame.add(pane);
pane = create3rdRow();
frame.add(pane);
pane = create4thRow();
frame.add(pane);
frame.pack();
//frame.setSize(500, 500); //If your image is too large use this
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String args[]) {
new Test();
}
}
As you can see in the above code, I'm not using a null layout but a combination of multiple Layout Managers and I suggest you to do it like this in the future.
But if you still want to use that ugly null layout, you were missing this line:
jimage.setBounds(0, 0, 500, 500);
before this one:
lfr.setBounds(20, 40, 100, 20);
The output that my above code gives is:
And the output given by your code with the line I added is:
As you can see, both are really similar, and I could have done them identical but I don't have enough time to do so, but you can by combining the Layout Managers I posted above.
Note: I forgot to mention that to make this program to show the background image, I needed to make every other panels not opaque with pane.setOpaque(false); so, be sure to use this whenever you need to show something that is behind another panel.

miglayout with jtable with issue

I have used miglayout in swing applicaion.I have encounted one issue like jtable cant appear in whole frame it show only left side some area.
i want to show untill at right side end of jframe edge
My implemantaion code is below
package test;
import java.awt.EventQueue;
import java.util.Arrays;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
public class ProductPanel2 extends JPanel {
private JLabel lblProd;
private JButton butAdd;
private JButton butRemove;
private JButton butEdit;
private JScrollPane scroll;
private JTable table;
private static final long serialVersionUID = 1L;
public JList<String> lst_Options;
private JScrollPane scr_Data;
private JComboBox<ComboItem> cmb_Suppliers;
//Generar de inmediato
private JButton btn_NewUpdate;
private JButton btn_Delete;
private JButton btn_Copy;
private JTable tbl_Settings;
private JLabel lbl_SelectedOption;
DefaultListModel<String> modeloOpciones;
public ProductPanel2() {
initComponents();
}
private void initComponents() {
lblProd = new JLabel("Product List: ");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
lst_Options = new JList<String>();
modeloOpciones = new DefaultListModel<String>();
btn_Delete = new JButton("Eliminar");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
cmb_Suppliers = new JComboBox<ComboItem>();
modeloOpciones.addElement("Proveedores");
modeloOpciones.addElement("Productos");
modeloOpciones.addElement("Partidas");
lst_Options.setModel(modeloOpciones);
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
JPanel filterPanel=new JPanel();
setLayout(new MigLayout("debug", "[96px][][94.00][grow][149.00px][2px][161px]", "[16px][240px,grow][12px][29px]"));
//add(lbl_SelectedOption, "cell 1 0,alignx left,sgx");
add(lst_Options, "cell 0 1 1 5,grow");
filterPanel.add(scr_Data,"wrap, sg buttons");
// filterPanel.add(cmb_Suppliers, "");
add(filterPanel,"span 2 3, grow, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
add(lbl_Opciones, "cell 0 0,growx,aligny top");
add(btn_Delete, "cell 6 3,alignx right,aligny bottom");
add(btn_NewUpdate, "cell 4 3,alignx right,aligny bottom");
refreshCombo(cmb_Suppliers);
}
private void refreshCombo(JComboBox<ComboItem> combo) {
combo.removeAllItems();
try {
combo.addItem(new ComboItem("0","ashjish"));
combo.addItem(new ComboItem("2","ashjish"));
combo.addItem(new ComboItem("3","ashjish"));
} catch (Exception e) {
//log.logToFile("refreshCombo: " + e.getClass().getName() + ": " + e.getMessage(), 1);
e.printStackTrace();
}
}
private JTable createTable() {
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
int rows = 30;
int cols = columnNames.length;
String[][] data = new String[rows][cols];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
data[i][j] = "R"+i+" C"+j;
}
}
JTable table = new JTable(data, columnNames);
return table;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
ProductPanel2 pane = new ProductPanel2();
frame.setContentPane(pane);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
i dont want space betweeb combo and jtable whuich in mention at screenshot
package test;
import java.awt.EventQueue;
import java.util.Arrays;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import net.miginfocom.swing.MigLayout;
public class ProductPanel2 extends JPanel {
private JLabel lblProd;
private JButton butAdd;
private JButton butRemove;
private JButton butEdit;
private JScrollPane scroll;
private JTable table;
private static final long serialVersionUID = 1L;
public JList<String> lst_Options;
private JScrollPane scr_Data;
private JComboBox<ComboItem> cmb_Suppliers;
//Generar de inmediato
private JButton btn_NewUpdate;
private JButton btn_Delete;
private JButton btn_Copy;
private JTable tbl_Settings;
private JLabel lbl_SelectedOption;
private JPanel filterPanel;
private JLabel lbl_cmb_supplier;
private JButton btn_search;
public ProductPanel2() {
initComponents();
}
private void initComponents() {
lblProd = new JLabel("Product List: ");
lbl_cmb_supplier = new JLabel("Proveedor");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
cmb_Suppliers = new JComboBox<ComboItem>();
btn_Delete = new JButton("Eliminar");
btn_search = new JButton("Search");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
JComboBox<String> cmb_Suppliers = new JComboBox<String>();
JButton btn_New = new JButton("Nuevo");
JButton btn_Delete = new JButton("Cancelar");
JButton btn_PDF = new JButton("Crea PDF");
JButton btn_Send = new JButton("Envia por correo");
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
tbl_Settings.setPreferredScrollableViewportSize(tbl_Settings.getPreferredSize());
filterPanel = new JPanel();
/*setLayout(new MigLayout("","[right]"));
add(lbl_Opciones, "growx,aligny, top, wrap");
filterPanel.add(lbl_cmb_supplier, "split 2, wrap");
filterPanel.add(cmb_Suppliers, "wrap");
filterPanel.add(btn_search, "grow, spany, wrap");
add(filterPanel, "growx 5,split 2, flowy, top, sgx");
add(scr_Data, "width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);*/
setLayout(new MigLayout("debug", "[122px][129px][23px][45px][148px,grow]", "[][100px,grow][]"));
add(lbl_Opciones, "growx, wrap");
filterPanel.add(lbl_cmb_supplier);
filterPanel.add(cmb_Suppliers);
filterPanel.add(btn_search, "grow, spany, wrap");
add(filterPanel, "wrap");
add(scr_Data, "width 100%, growx, push, span, wrap");
add(btn_New);
add(btn_PDF);
add(btn_Send);
add(btn_Delete);
refreshCombo(cmb_Suppliers);
}
private void refreshCombo(JComboBox<String> combo) {
combo.removeAllItems();
try {
} catch (Exception e) {
//log.logToFile("refreshCombo: " + e.getClass().getName() + ": " + e.getMessage(), 1);
e.printStackTrace();
}
}
private JTable createTable() {
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
int rows = 30;
int cols = columnNames.length;
String[][] data = new String[rows][cols];
for(int i=0; i<rows; i++) {
for(int j=0; j<cols; j++) {
data[i][j] = "R"+i+" C"+j;
}
}
JTable table = new JTable(data, columnNames);
return table;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
ProductPanel2 pane = new ProductPanel2();
frame.setContentPane(pane);
frame.setSize(1000,1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
You should re-think, how you are using the MigLayout! Please consider reading the quickstart guide: http://www.miglayout.com/QuickStart.pdf
Also your variable naming needs some work, it is very unclear, which variable is for what.
In order to solve your problem, do this:
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
// I have created a new Dimension-object. Those dimensions are FIXED! You might want to put a new dimension in, that is relative to the window size.
scr_Data.setPreferredSize(new Dimension(800, 800));
JPanel filterPanel=new JPanel();
Change this line (where you are setting absolute widths and heights for rows and columns!):
setLayout(new MigLayout("debug", "[96px][][94.00][grow][149.00px][2px][161px]", "[16px][240px,grow][12px][29px]"));
To this:
setLayout(new MigLayout());
Remove all the cells you have added, because you have mixed them with other layout-parts, that are not cells:
add(lst_Options, "grow");
filterPanel.add(scr_Data,"wrap");
// filterPanel.add(cmb_Suppliers, "");
add(filterPanel,"width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
add(lbl_Opciones, "growx,aligny top");
add(btn_Delete, "alignx right,aligny bottom");
add(btn_NewUpdate, "alignx right,aligny bottom");
Looks like this:
PS: I did not know that this would work:
String[] columnNames = "Name 1,Name 2,Name 3,Name 4,Name 5".split(",");
The usual way is:
String[] columnNames = {"Name 1","Name 2","Name 3","Name 4","Name 5"};
I've learned something!
EDIT:
I've learned, that split() works by using regular expression, so you have to be careful, how to use it!
This will return an empty field and NOT "aaa" and "bbb":
"aaa.bbb".split(".");
Update:
I have updated my answer, this is the code in the initComponents()-method. I again urge you to read more about the MigLayout and stop mixing cell-components like this add(lst_Options, "cell 0 1,grow"); with non-cell components. This is messy and hard to understand / fix. I removed those cells in my answer and added alignments for the buttons. Now everything works as expected.
private void initComponents() {
lblProd = new JLabel("Product List: ");
btn_NewUpdate = new JButton("Add");
btn_Delete = new JButton("Remove");
lbl_SelectedOption = new JLabel("Tipo de datos");
JLabel lbl_Opciones = new JLabel("Opciones");
lst_Options = new JList<String>();
modeloOpciones = new DefaultListModel<String>();
btn_Delete = new JButton("Eliminar");
btn_NewUpdate = new JButton("Nuevo");
scr_Data = new JScrollPane();
cmb_Suppliers = new JComboBox<String>();
modeloOpciones.addElement("Proveedores");
modeloOpciones.addElement("Productos");
modeloOpciones.addElement("Partidas");
lst_Options.setModel(modeloOpciones);
tbl_Settings = createTable();
tbl_Settings.setFillsViewportHeight(true);
scr_Data = new JScrollPane(tbl_Settings);
tbl_Settings.setPreferredScrollableViewportSize(tbl_Settings.getPreferredSize());
setLayout(new MigLayout("","[right]"));
add(lbl_Opciones, "growx,aligny, top, wrap");
add(lst_Options, "grow");
add(scr_Data, "width 100%, growx, push, span, wrap");
scr_Data.setViewportView(tbl_Settings);
lbl_Opciones.setHorizontalAlignment(SwingConstants.CENTER);
btn_Delete.setHorizontalAlignment(SwingConstants.RIGHT);
btn_NewUpdate.setHorizontalAlignment(SwingConstants.RIGHT);
add(btn_Delete, "bottom, span 2");
add(btn_NewUpdate, "bottom");
refreshCombo(cmb_Suppliers);
}
Looks like this:

Separating JLayeredPanel

I have a set of panels across a layered pane. I need a separator between to separate the sideBar from the topBar and the tabbedPanel. I left a buffer of 10 pixels for it to be placed. unfortunately, possibly due to it being a JLayeredPane, I canot get it to view.
Is there a way to define the separator's X location? as this should solve it. Either way, here's a sample of the code, which I've removed most information from.
Alternatively, offer a different solution entirely, so long as I can get a defined split from the sideBar and other two panels. I've already tried to apply the BorderLayout.WEST to the sideBar, but due to it being a JLayeredPane, it gives me errors.
lPane = new JLayeredPane();
lPane.setBounds(0, 0, 1024, 768);
calendarFrame = new JFrame ("Calendar Frame");
calendarFrame.setPreferredSize(new Dimension(1024, 768));
calendarFrame.setLayout(null);
//Prepare side bar
sideBar = new JPanel ();
sideBar.setLayout(null);
sideBar.setBounds(0, 0, 210, 768);
//Prepare top bar
topBar = new JPanel ();
topBar.setLayout(null);
topBar.setBounds(220, 0, 774, 50);
//Create tabbed pane
tabbedPane = new JTabbedPane();
tabbedPane.setBounds(220, 50, 774, 700);
//Tab code here, but not needed for questuion
calendarFrame.add(lPane, BorderLayout.CENTER);
lPane.add(sideBar, new Integer(0), 0);
lPane.add(Box.createHorizontalStrut(5));
lPane.add(new JSeparator(SwingConstants.VERTICAL));
lPane.add(Box.createHorizontalStrut(5));
lPane.add(topBar, new Integer(1), 0);
lPane.add(tabbedPane, new Integer(2), 0);
EDIT:
if you want to create fixed 10pixels gap,
you can use
EmptyBorder (or CompoundBorder)
BorderLayout(int horizontalGap, int verticalGap) or GridLayout(int rows, int cols, int hgap, int vgap)
just my curiosity are you ...
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class EditableListExample extends JFrame {
private static final long serialVersionUID = 1L;
public EditableListExample() {
super("Editable List Example");
String[] data = {"a", "b", "c", "d", "e", "f", "g"};
JList list = new JList(data);
JScrollPane scrollList = new JScrollPane(list);
scrollList.setMinimumSize(new Dimension(100, 80));
Box listBox = new Box(BoxLayout.Y_AXIS);
listBox.add(scrollList);
listBox.add(new JLabel("JList"));
DefaultTableModel dm = new DefaultTableModel();
Vector<String> dummyHeader = new Vector<String>();
dummyHeader.addElement("");
dm.setDataVector(strArray2Vector(data), dummyHeader);
JTable table = new JTable(dm);
table.setShowGrid(false);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollTable = new JScrollPane(table);
scrollTable.setColumnHeader(null);
scrollTable.setMinimumSize(new Dimension(100, 80));
Box tableBox = new Box(BoxLayout.Y_AXIS);
tableBox.add(scrollTable);
tableBox.add(new JLabel("JTable"));
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
c.add(listBox);
c.add(new JSeparator(SwingConstants.VERTICAL));
//c.add(new JLabel("test"));
//c.add(new JSeparator(SwingConstants.HORIZONTAL));
c.add(tableBox);
pack();
setVisible(true);
}
private Vector<Object> strArray2Vector(String[] str) {
Vector<Object> vector = new Vector<Object>();
for (int i = 0; i < str.length; i++) {
Vector<Object> v = new Vector<Object>();
v.addElement(str[i]);
vector.addElement(v);
}
return vector;
}
public static void main(String[] args) {
final EditableListExample frame = new EditableListExample();
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

Categories

Resources