Create a matrix using JTextFields or JTextAreas - java

I have to do make a program that has to be able to show a matrix in form of Jtextfields or Jtextareas, so that the user can write in them(a number of the matrix for each Jtextfield).
The problem is that I have no idea how to create a custom JPanel with the size and quantity of Jtextfields that the user specifies(a different each time).
I have already googled the question, to no avail.

Take a look at GridLayout. It is pretty simple to put together a grid together with a couple params (row and col count). To paraphrase from the JavaDoc:
public static void main (String[] args) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(new JTextField("1"));
panel.add(new JTextField("2"));
panel.add(new JTextField("3"));
panel.add(new JTextField("4"));
panel.add(new JTextField("5"));
panel.add(new JTextField("6"));
would result in a 3 row by 2 col grid of JTextFields
EDIT:
here is some more, in a class named Demo:
public class Demo {
public static void main(final String[] args) {
if (args.length < 2) {
System.out.print("please enter row and col on commandline");
}
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Demo(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
}
});
}
public Demo(int colCnt, int rowCnt) {
JFrame frame = new JFrame("Demo");
frame.setSize(600, 600);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(colCnt,rowCnt));
for (int i =0; i < rowCnt*colCnt; i++) {
panel.add(new JTextField(""+i));
}
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

First of all, I would build a 2d array of the text fields\areas. When you get the user input you can then initialize the arrays and "new up" all of the widgets. After adding all of them to the parent panel\frame you may have to do some calculation based on the used up size and resize your top level window. Aside from that, as already suggested, GridLayout will be a good choice for the direct parent component.
Hope this helps.

To change the appearance at runtime, all you need to do is replace the content with new components.
So depending on how you get your input, you replace the numbers given in akf's answer with the input.
panel.setLayout(new GridLayout( rows, columns));
and then to show the new panel you add it in the JFrame with
add( panel );
Your assignment however might be something along the lines of subclassing a JPanel to show a matrix. I get that impression in your wording. Then its a whole different solution.
If your only goal is to implement a matrix where you can edit values a JTable is by far the simplest. Put the following in a JFrame
DefaultTableModel data = new DefaultTableModel(3 , 3);// rows, cols
JTable table = new JTable(data);
add(table);
pack();
setVisible(true);
This would also simplify modifying the height and width of the matrix by using data.setRowCount( newValue ).

Related

How can i add JButtons to a panel in vertical way? [duplicate]

This question already has answers here:
Java: vertical alignment within JPanel
(3 answers)
Closed 4 years ago.
the task i am trying to do is simple. I want to add JButtons to a panel in a vertical way, but using a loop to adding it, i tried to do it using .setBounds() and .setLocation() mehtod, but i dont have any results.
In a simple way, i want to do this but adding the buttons vertically and keeping the JScroll bar...:
public class NewMain {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setLayout(null);
for (int i = 0; i < 10; i++) {
JButton asd=new JButton("HOLA "+i);
asd.setLocation(i+20, i+20);
panel.add(asd);
}
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(50, 30, 300, 50);
JPanel contentPane = new JPanel(null);
contentPane.setPreferredSize(new Dimension(500, 400));
contentPane.add(scrollPane);
frame.setContentPane(contentPane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
Give the JPanel that holds the JButtons an appropriate layout manager that adds components in a vertical manner. A GridLayout(0, 1) would work, the parameters referring to 0 rows -- meaning variable number of rows, and 1 column. This will add the JButtons into a vertical grid, column of one
Other possible solutions include BoxLayout and GridBagLayout, both of which are a little more complex than the GridLayout.
Also avoid using null layouts as you're doing as this leads to inflexible GUI's painful debugging and changes.

MigLayout - panel with grow and push

I am trying to create a panel, using MigLayout, divided on three rows. The first and last row should have a pushY of some ratio (in this case, 2f) and the row in between should grow as mush as possible in order to occupy the remaining space.
However, I have some cases in which the last row, for example, which is a panel on its own, will have no components in it. In this case, I want the 2nd row to occupy all the height and I can't achieve that.
Please not that making it invisible is not possible due to other flow-dependencies.
I've attached the code here:
public class TestClass {
public static void main(String[] args) {
createPanel(true);
createPanel(false);
}
private static void createPanel(boolean removeAll) {
JFrame frame = new JFrame();
JPanel panel = new JPanel(new MigLayout(new LC().fill().gridGap("0", "0").insetsAll("0")));
panel.add(new JLabel("first row"), new CC().grow().newline().pushY(2f));
JTextArea abc = new JTextArea("abc");
abc.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
panel.add(abc, new CC().push().grow().newline());
JPanel pnl = new JPanel(new MigLayout(new LC().fill().gridGap("0", "0").insetsAll("0")));
pnl.add(new JLabel("aaa"), new CC());
pnl.add(new JLabel("bbb"), new CC().newline());
pnl.add(new JLabel("ccc"), new CC().newline());
panel.add(pnl, new CC().grow().newline().pushY(2f));
if (removeAll) {
pnl.removeAll();
}
frame.setContentPane(panel);
frame.setSize(100,800);
frame.setVisible(true);
}
}
Use dock feature for that, so top will dock in north, bottom in south, and middle row will grow between them. http://www.miglayout.com/QuickStart.pdf check the page no.5 for docking tutorial.

JFrame, JPanel, and Gridlayout Issues

As a quick overview, my project involves taking a .txt file and converting that into a 2d array, then drawing it into a JFrame. As I was testing, I used JButtons instead of a custom class that will be built later. I have ran into two bugs that I don't know how to solve. For these pictures, this is all based on a Gridlayout that is 2 Rows and 16 Columes. When I add JButtons to the panel, it looks like this.
When I add them to the JFrame, it looks like this.
Here is my code for creating the JFrame and JPanel and rendering it:
/**
* This method creates a JFrame, JPanel, and then renders
* all of the level in the JFrame
*/
public void render()
{
JFrame frame = new JFrame("<Insert Title>");
//Make it full screen for any computer monitor
frame.setSize(JFrame.MAXIMIZED_HORIZ, JFrame.MAXIMIZED_HORIZ);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setUndecorated(true);
frame.setVisible(true);
JPanel panel = new JPanel(grid);
frame.setLayout(grid);
frame.add(panel);
panel.getInputMap(IFW).put(KeyStroke.getKeyStroke("ESCAPE"), "quit");
panel.getActionMap().put("quit", quit);
//Draw!
for(int row = 0; row < drawStuff.length; row++)
{
for(int col = 0; col < drawStuff[row].length; col++)
{
//Either panel.add or frame.add here
panel.add(new JButton("Row :"+row+" Col: "+col));
}
}
panel.revalidate();
panel.repaint();
}
Anything that I am doing wrong here?
Thanks!
Remove frame.setLayout(grid); - this will allow the panel to occupy the entire content area of the frame, instead of been one row of one column
frame.setSize(JFrame.MAXIMIZED_HORIZ, JFrame.MAXIMIZED_HORIZ) really isn't doing what you think it is, not unless you want a frame which is 2x4

How can get components to stretch across an entire row using BoxLayout?

I'm looking at the How To Use BoxLayout documentation, which clearly says that
What if none of the components has a maximum width? In this case, if
all the components have identical X alignment, then all components are
made as wide as their container.
Let's assume we're adding a lot of JButton instances to a JPanel. If the maximum width of these buttons are none AND we invoke setAlignmentX(Component.LEFT_ALIGNMENT) on all of these buttons - then each of these buttons should stretch across its entire row. The documentation even illustrates this using the below picture.
I can't get this to work!
I've tried doing setMaximumSize(null) and setMaximumSize(new Dimension(-1,-1)) and setMaximumSize(new Dimension(0,0)) on the buttons but nothing gives me the described behaviour.
What excactly does the documentation mean when it says :
What if none of the components has a maximum width?
What is a maximum width of none?
The best I've been able to produce is the below. Reading the documentation I would expect that the buttons should be able to stretch across their entire rows. I know I can use other layout managers as well for this, but I would like to achieve this with BoxLayout (granted the documentation is right / I've understood the documentation right).
public class CustomList extends JPanel {
private final Box box = Box.createVerticalBox();
public CustomList() {
for (int i = 0; i < 10; i++) {
JButton b = new JButton("Button item" + i);
//b.setMaximumSize(new Dimension(0,0));
b.setAlignmentX(Component.LEFT_ALIGNMENT);
box.add(b);
}
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(box, BorderLayout.CENTER);
}
public static void main(String[] args) {
CustomList l = new CustomList();
l.setSize(200, 200);
l.setBackground(Color.red);
JFrame frame = new JFrame("Vertical Box");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(l, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Your buttons actually have a maximum width.
What you can do is create JPanel objects with BorderLayout in your loop, add each button to each panel (to BorderLayout.CENTER, which is the default anyway).
BorderLayout.CENTER doesn't care about the maximum size of its child Component, so you end up with a JPanel whose whole content is filled by a JButton.
Since the JPanel itself has a huge default maximum size of new Dimension(Short.MAX_VALUE, Short.MAX_VALUE) (this is width=32767,height=32767 !!) which is the default maximum size of Component, you will get the expected result :
public CustomList() {
for (int i = 0; i < 10; i++) {
JPanel panel = new JPanel(new BorderLayout());
JButton b = new JButton("Button item" + i);
//b.setMaximumSize(new Dimension(0,0));
b.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(b);
box.add(panel);
}
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(box, BorderLayout.CENTER);
}

Need a layout? How it should be used?

So im writing a small test program for fun replicating a inventory from games like minecraft and runescape. Basically a frame with another one inside it, and pictures of your items in it, and a scroll bar to scroll down through all the stuff you have in your inventory. The "Stuff" i would have in my inventory would be buttons added later on with their own functionality, so you can scroll through vertically and see all the "stuff." Right now i have some test buttons being added to deomsntrate the error. Basically i want the buttons to be 100,100 and for them to be in a row of 4, and go onto the next column. I though GridLayout would be the best choice, but it seems to add more rows after being added into a scrollpane. Well heres the code skimmed down:
public class inventory extends JFrame{
public static void main(String[] args){
new inventory();
}
JPanel mainInv = new JPanel();
JScrollPane sp;
public inventory(){
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = this.getToolkit();
setLocation(tk.getScreenSize().width/2-getWidth()/2, tk.getScreenSize().height/2-getHeight()/2);
setLayout(null);
mainInv.setSize(getWidth()-10, 1000);
mainInv.setBackground(Color.blue);
mainInv.setLayout(new GridLayout(8,4));
sp = new JScrollPane(mainInv, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
sp.setMaximumSize(new Dimension(400,400));
sp.setBounds(5, 5, 500-10, 500-130);
JButton[] testButs = new JButton[100];
for(int i = 0; i < 50; i++){
testButs[i] = new JButton("Test Button " + i);
testButs[i].setSize(100,100);
mainInv.add(testButs[i]);
}
add(sp);
setVisible(true);
}
}
With GridLayout the number of rows is the dominating factor.
If you have 8 rows and 4 columns that can only fit 48 buttons, if you try to add a 49th button it will create a 5th column not a 9th row.
You can solve your problem by setting up the GridLayout with more rows.

Categories