How can be components added dynamically in the JDialog? - java

I am trying to create GUI like given in first picture, but I am not able to do it.here is the image
I am getting only one combo1, combo2, combo3 and serialNoLabel instead of 5 [5 is the size of list]
ArrayList<String> list; // the size of the list is 5
JComboBox combo1[] = new JComboBox[list.size()];
JComboBox combo2[] = new JComboBox[list.size()];
JComboBox combo3[] = new JComboBox[list.size()];
JLabel SerialNoLabel[] = new JLabel[list.size()];
JPanel masterPanel[] = new JPanel[list.size()];
JDialog masterDialog = new JDialog();
masterDialog.setVisible(true);
masterDialog.setSize(800, 500);
masterDialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
masterDialog.setVisible(true);
for(int j =0; j < list.size(); j++) {
masterPanel[j] = new JPanel();
SerialNoLabel[j] = new JLabel(list.get(j));
masterPanel[j].add(SerialNoLabel[j]);
combo1[j] = new JComboBox();
masterPanel[j].add(combo1[j]);
combo2[j] = new JComboBox();
masterPanel[j].add(combo2[j]);
combo3[j] = new JComboBox();
masterPanel[j].add(combo3[j]);
masterDialog.add(masterPanel[j]);
masterDialog.revalidate();
}

I believe it's a layout issue leading your masterPanels to be on top of each other.
So I would do something like this:
JPanel mainPanel = new JPanel();
FlowLayout experimentLayout = new FlowLayout();
mainPanel.setLayout(experimentLayout);
for(int j =0; j < list.size(); j++) {
masterPanel[j] = new JPanel();
SerialNoLabel[j] = new JLabel(list.get(j));
masterPanel[j].add(SerialNoLabel[j]);
combo1[j] = new JComboBox();
masterPanel[j].add(combo1[j]);
combo2[j] = new JComboBox();
masterPanel[j].add(combo2[j]);
combo3[j] = new JComboBox();
mainPanel.add(masterPanel[j]);
}
Of course you could other layouts as well. But I believe you want to go for a FlowLayout. See the documentation about FlowLayout here.
You can learn more about other layouts here

Related

Java AWT controls issue

I'd like to create a calculator using Java AWT library, however I'm having problems putting a label and a textfield on the same row. Also, everything is mixing up. When I run the program, at first it shows 2 labels and 2 textfields on the same row, but if I resize it, the labels, buttons & textfields are one on top of another. Could you please help me?
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class Calculator extends Frame {
public static void main(String[] args) {
Frame frame= new Frame();
frame.setTitle("Mini Calculator App");
frame.setVisible(true);
frame.setSize(300,300);
LayoutManager gridBagLayout = new GridBagLayout();
frame.setLayout(gridBagLayout);
Label firstNumber = new Label("Add a number");
frame.add(firstNumber);
TextField numar1 = new TextField();
frame.add(numar1);
Label secondNumber = new Label("Add another number");
frame.add(secondNumber);
TextField numar2 = new TextField();
frame.add(numar2);
Choice operatie = new Choice();
operatie.add("+"); operatie.add("-");
operatie.add("*"); operatie.add("/");
frame.add(operatie);
Button calcul = new Button("Calculate");
frame.add(calcul);
Label result = new Label("Result is");
frame.add(result);
GridBagConstraints afisare;
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 0;
frame.add(firstNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 0;
afisare.gridy = 1;
afisare.gridwidth = 10;
afisare.gridheight = 10;
frame.add(numar1, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 0;
frame.add(secondNumber, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 1;
afisare.gridy = 1;
frame.add(numar2, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 2;
afisare.gridy = 1;
frame.add(operatie, afisare);
afisare = new GridBagConstraints();
afisare.gridx = 4;
afisare.gridy = 0;
frame.add(result, afisare);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
enter image description here
enter image description here

Java - Adding Arrays of JTextField and JLabel to a JPanel

I'm hoping this is an easy question. I have a JComboBox with the choices of 0, 1, 2, 3,...10. Depending on what number is selected in the JComboBox, I want my GUI to add a JLabel and a JTextField. So if the number 3 is chosen, the GUI should add 3 JLabels and 3 JTextFields. and so forth.
I'm using an array of JLabels and JTextFields to accomplish this, but I am getting a null pointer exception at runtime, and no labels or fields are being added.
Code:
private void createComponents()
{
//Create Action Listeners
ActionListener comboListener = new ComboListener();
//Create Components of the GUI
parseButton = new JButton("Parse Files");
parseButton.addActionListener(comboListener);
numberLabel = new JLabel("Number of Files to Parse: ");
String[] comboStrings = { "","1", "2","3","4","5","6","7","8","9","10" };
inputBox = new JComboBox(comboStrings);
inputBox.setSelectedIndex(0);
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(2,10));
centerPanel = new JPanel();
centerPanel.add(numberLabel);
centerPanel.add(inputBox);
totalGUI = new JPanel();
totalGUI.setLayout(new BorderLayout());
totalGUI.add(parseButton, BorderLayout.SOUTH);
totalGUI.add(centerPanel, BorderLayout.CENTER);
add(totalGUI);
}
ActionListener Code:
public void actionPerformed(ActionEvent e)
{
JTextField[] fileField = new JTextField[inputBox.getSelectedIndex()];
JLabel[] fieldLabel = new JLabel[inputBox.getSelectedIndex()];
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i].setText("File "+i+":"); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fieldLabel[i]); //NULL POINTER EXCEPTION HERE
fieldPanel.add(fileField[i]);
}
centerPanel.add(fieldPanel);
repaint();
revalidate();
}
Thanks to MadProgrammer's comment, this question has been answered.
Editing the loop to:
for(int i = 0; i < fileField.length; i++)
{
fieldLabel[i] = new JLabel();
fileField[i] = new JTextField();
fieldLabel[i].setText("File "+i+":");
fieldPanel.add(fieldLabel[i]);
fieldPanel.add(fileField[i]);
}
resolved the issue.

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

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

Trying to change image when JButton pressed

I am trying to change the Image on the panel when the any of the JButtons are pressed. I have set up an array of images and need it to change to the next image in the array once it has been pressed. Here is my code:
public class SimpleGui implements ActionListener {
JButton button = new JButton("Very Happy");
JButton buttonTwo = new JButton("Happy");
JButton buttonThree = new JButton("Neutral");
JButton buttonFour = new JButton("Sad");
JButton buttonFive = new JButton("Very Sad");
static int[] ButtonArray = new int[5];
private static String[] imageList = { "res/snow.jpg", "res/test-gm.jpg" };
public int i = 0;
public static void main(String[] args) throws FileNotFoundException {
SimpleGui gui = new SimpleGui();
gui.go();
File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
}
public void go() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
button.addActionListener(this);
buttonTwo.addActionListener(this);
buttonThree.addActionListener(this);
buttonFour.addActionListener(this);
buttonFive.addActionListener(this);
panel.add(button);
panel.add(buttonTwo);
panel.add(buttonThree);
panel.add(buttonFour);
panel.add(buttonFive);
frame.getContentPane().add(BorderLayout.EAST, panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 600);
frame.setVisible(true);
ImageIcon image = new ImageIcon(imageList[i]);
ImageIcon image1 = new ImageIcon(imageList[i + 1]);
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(label, BorderLayout.CENTER);
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
frame.add(panel2, BorderLayout.CENTER);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button) {
ButtonArray[0] = 1;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Very Happy");
}
// buttonTwo = (JButton) event.getSource();
if (event.getSource() == buttonTwo) {
ButtonArray[0] = 0;
ButtonArray[1] = 1;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Happy");
}
// buttonThree = (JButton) event.getSource();
if (event.getSource() == buttonThree) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 1;
ButtonArray[3] = 0;
ButtonArray[4] = 0;
System.out.println("Neutral");
}
// buttonFour = (JButton) event.getSource();
if (event.getSource() == buttonFour) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 1;
ButtonArray[4] = 0;
System.out.println("Sad");
}
// buttonFive = (JButton) event.getSource();
if (event.getSource() == buttonFive) {
ButtonArray[0] = 0;
ButtonArray[1] = 0;
ButtonArray[2] = 0;
ButtonArray[3] = 0;
ButtonArray[4] = 1;
System.out.println("Very Sad");
}
// System.out.println(Arrays.toString(ButtonArray));
// ImageIcon image = (imageList[i]);
}
}
I don't really see what most parts of you code are supposed to do. So instead, here's a minimal example that should do what you are asking about: One label, and two buttons setting different images to that label.
ImageIcon[] images = new ImageIcon[] {
new ImageIcon("foo.gif"),
new ImageIcon("bar.gif"),
new ImageIcon("blub.gif")
};
JFrame frame = new JFrame("Test");
frame.getContentPane().setLayout(new FlowLayout());
JLabel label = new JLabel(images[0]);
frame.getContentPane().add(label);
JButton button1 = new JButton("Image 1");
button1.addActionListener(e -> label.setIcon(images[0]));
frame.getContentPane().add(button1);
JButton button2 = new JButton("Image 2");
button2.addActionListener(e -> label.setIcon(images[1]));
frame.getContentPane().add(button2);
frame.pack();
frame.setVisible(true);
Note that this is using Lambda functions (Java 8) but you can do the same with one or more "real" ActionListener classes. The important part is that you call label.setIcon(theImage); this part seems to be missing in your code.
If instead you want to cycle through a list or array of pictures, you can do like this:
AtomicInteger index = new AtomicInteger(0);
JButton buttonCycle = new JButton("Cycle");
buttonCycle.addActionListener(e -> label.setIcon(images[index.getAndIncrement() % images.length]));
frame.getContentPane().add(buttonCycle);
Here, the AtomicInteger is used so I can declare it as a local variable and use it in the lambda. You can just as well use a regular int if you make it a member variable of the surrounding class.
private int c = 0;
...
buttonCycle.addActionListener(e -> label.setIcon(images[c++ % images.length]));
The takeaway is: Create a counter variable, increment it each time the button is called and set the label's icon to the element with that count, module the size of the array.

Split labels in JTabbedPane

I need to change my label's distribution on a JTabbedPane.
I have this:
And I want to do this:
Can someone help me?
I post the code below:
tabbedResultsPane = new JTabbedPane(SwingConstants.TOP);
JPanel featurePanel = new JPanel(new GridLayout(TOTAL_FEATURES, 2, 3, 3));
estadoScroll = new JScrollPane(featurePanel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
lblFeatureHdr = new JLabel[TOTAL_FEATURES];
lblFeature = new JLabel[TOTAL_FEATURES];
for(int i=0; i<TOTAL_FEATURES; i++)
{
lblFeatureHdr[i] = new JLabel(strHeader[i], JLabel.RIGHT);
lblFeatureHdr[i].setOpaque(true);
lblFeatureHdr[i].setBackground(new Color(220,255,220));//.lightGray);
lblFeature[i] = new JLabel("", JLabel.LEFT);
lblFeature[i].setForeground(Color.blue);// black);
featurePanel.add(lblFeatureHdr[i]);
featurePanel.add(lblFeature[i]);
}
Define 4 columns GridLayout (rather than 2 columns you have).
and correct your code yo add 2 more labels for each row.
for(int i=0; i<TOTAL_FEATURES; i++)
{
lblFeatureHdr[i] = new JLabel(strHeader[i], JLabel.RIGHT);
lblFeatureHdr[i].setOpaque(true);
lblFeatureHdr[i].setBackground(new Color(220,255,220));//.lightGray);
lblFeature[i] = new JLabel("", JLabel.LEFT);
lblFeature[i].setForeground(Color.blue);// black);
featurePanel.add(lblFeatureHdr[i]);
featurePanel.add(lblFeature[i]);
// add 2 more lables to the same row
JLabel l=new JLabel(strHeader[i], JLabel.RIGHT);
l.setBackground(new Color(220,255,220));//.lightGray);
featurePanel.add(l);
featurePanel.add(new JLabel("", JLabel.LEFT));
}

Categories