Can someone please tell me what's wrong with this code?
I need it to pop up a frame and fill the frame with certain field a namer field and an intake field and also display a button at the bottom of the grid.
Any help would be welcomed, Thanks!!
import java.awt.*;
import javax.swing.*;
public class FrameDemo
//To create the gui and show it.
{
public static void createAndShowGUI()
{
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(1,14);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow handler for user input on Empty Textfield?
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
//add job to event scheduler
//create and show GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This is not how you use GridLayout:
frame.getContentPane().add(PL, first);
Instead you'd set the container's layout using the layout manager:
frame.getContentPane().setLayout(first);
and then add components to the container:
frame.getContentPane().add(PL);
frame.getContentPane().add(PLv);
frame.getContentPane().add(AD);
frame.getContentPane().add(ADv);
frame.getContentPane().add(AV);
frame.getContentPane().add(Avv);
frame.getContentPane().add(TS);
frame.getContentPane().add(TSv);
frame.getContentPane().add(MT);
frame.getContentPane().add(MTv);
// and so on for all the components.
You will want to read the tutorial on how to use GridLayout which you can find here: GridLayout Tutorial.
As an aside, note that this:
frame.getContentPane().add(PL);
can be shortened to this:
frame.add(PL);
Also you will want to study and learn Java naming conventions: class names begin with an upper case letter and all method and variables with lower case letters. Also avoid variable names like pl or plv, or ad or adv, and instead use names that are a little bit longer and have meaning, names that make your code self-commenting. So instead of AD, consider angularDisplacementField for the JTextfield's name.
Myself, I'd use a GridBagLayout and do something like:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.*;
public class GuiDemo extends JPanel {
// or better -- use an enum for this
public static final String[] FIELD_LABELS = {
"Pendulum Length", "Angular Displacement", "Angular Velocity",
"Time Steps", "Max Time", "Viscocity (0-1)"
};
private static final int TEXT_FIELD_COLUMNS = 10;
private static final int GAP = 3;
private static final Insets RIGHT_GAP_INSETS = new Insets(GAP, GAP, GAP, 3 * GAP);
private static final Insets BALANCED_INSETS = new Insets(GAP, GAP, GAP, GAP);
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public GuiDemo() {
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
int row = 0;
// to make sure that no focusAccelerator is re-used
Set<Character> focusAccelSet = new HashSet<>();
for (String fieldLabelLText : FIELD_LABELS) {
JLabel fieldLabel = new JLabel(fieldLabelLText);
JTextField textField = new JTextField(TEXT_FIELD_COLUMNS);
labelFieldPanel.add(fieldLabel, getGbc(row, 0));
labelFieldPanel.add(textField, getGbc(row, 1));
labelFieldMap.put(fieldLabelLText, textField);
for (char c : fieldLabelLText.toCharArray()) {
if (!focusAccelSet.contains(c)) {
textField.setFocusAccelerator(c);
fieldLabel.setDisplayedMnemonic(c);
focusAccelSet.add(c);
break;
}
}
row++;
}
JButton button = new JButton(new DrawGraphAction("Draw New Graph"));
labelFieldPanel.add(button, getGbc(row, 0, 2, 1));
setLayout(new BorderLayout(GAP, GAP));
add(labelFieldPanel, BorderLayout.CENTER);
}
private class DrawGraphAction extends AbstractAction {
public DrawGraphAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO calculation method
}
}
public static GridBagConstraints getGbc(int row, int column) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = column;
gbc.gridy = row;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
if (column == 0) {
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = RIGHT_GAP_INSETS;
} else {
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = BALANCED_INSETS;
}
return gbc;
}
public static GridBagConstraints getGbc(int row, int column, int width, int height) {
GridBagConstraints gbc = getGbc(row, column);
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.insets = BALANCED_INSETS;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Gui Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GuiDemo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Related
I have created a class SliderPanel that allows a user to use a JSlider to rotate a picture and return an int representing the selected value on the slider. This object inherits from JPanel, so when I add two or more SliderPanels to the main JPanel (creationPanel), it appears that the pictures disappear from the GUI. Is there a work around for this, I have tried changing to an absolute layout, nesting panels, and resizing.
Here is the code for the SliderPanel:
public class SliderPanel extends JPanel
{
private JSlider slider;
private JLabel[] labelsArray;
private static final GridBagConstraints gbc = new GridBagConstraints();
private int selectedValue = 5;
private boolean isImgVisible;
/**
* Constructor which creates the JPanel and manages the changing of the
* JSlider.
*
* #param headerTitle The title of the Panel.
* #param window The Window object to retrieve the images from.
*/
public SliderPanel(String headerTitle, Window window)
{
setSize(new Dimension(300, 300));
labelsArray = window.getImages();
setLayout(new GridBagLayout());
// Create a header for the label slider and add it to the panel.
JLabel headerLabel = new JLabel("<HTML><U>" + headerTitle +
"</U></HTML>");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
add(headerLabel, gbc);
Hashtable labels = new Hashtable();
for (int i = 0; i < 12; i++)
labels.put(i, new JLabel(String.valueOf(i)));
JPanel sliderAndImgPanel = new JPanel(new GridBagLayout());
JPanel imgPanel = new JPanel();
sliderAndImgPanel.setSize(new Dimension(200, 200));
slider = new JSlider(0, 10, 5);
slider.setLabelTable(labels);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.addChangeListener((ChangeEvent e) -> {
selectedValue = ((JSlider) e.getSource()).getValue();
System.out.println(selectedValue);
if (isImgVisible)
{
System.out.println("in");
sliderAndImgPanel.remove(imgPanel);
imgPanel.removeAll();
}
validate();
repaint();
JLabel pic = labelsArray[selectedValue];
pic.setPreferredSize(new Dimension(150, 150));
imgPanel.add(pic);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
sliderAndImgPanel.add(imgPanel, gbc);
isImgVisible = true;
validate();
window.validate();
});
JLabel pic = labelsArray[5];
pic.setPreferredSize(new Dimension(150, 150));
imgPanel.add(pic);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.CENTER;
sliderAndImgPanel.add(imgPanel, gbc);
sliderAndImgPanel.validate();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
sliderAndImgPanel.add(slider, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
add(sliderAndImgPanel, gbc);
}
/**
* This method returns the value selected on the JSlider.
*
* #return The selected value. [0, 10]
*/
public int getSelectedValue()
{
return selectedValue;
}
}
And here is the Window class where the panels get added to the JFrame:
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Window extends JFrame
{
private static JLabel[] imagesArray;
public static void main(String[] args)
{
new Window();
}
public Window()
{
super("Testing");
setLayout(new GridLayout(2,1,5,5));
setSize(1000, 700);
setVisible(true);
imagesArray = loadImages();
add(new SliderPanel("test 1", this));
add(new SliderPanel("test 2", this));
}
// Accessor method.
public static JLabel[] getImages()
{
return imagesArray;
}
// Loads images from project directory.
private static JLabel[] loadImages()
{
JLabel[] array = new JLabel[11];
// Load each image into the array.
for (int i = 0; i < 11; i++)
{
try
{
BufferedImage newImg = ImageIO.read(new File(i + ".png"));
array[i] = new JLabel(new ImageIcon(newImg));
} catch (IOException ex)
{
System.out.println("Exception: " + i);
}
}
return array;
}
}
Thanks in advance!
PS: Here are the links to the images I uploaded:
https://i.imgur.com/BvIehj5.png,
https://i.imgur.com/f527RdK.png,
https://i.imgur.com/98mgTHr.png,
https://i.imgur.com/Jsqm08U.png,
https://i.imgur.com/0pHTDgE.png,
https://i.imgur.com/TvtEiFm.png,
https://i.imgur.com/VeEDFfn.png,
https://i.imgur.com/3rp59Oz.png,
https://i.imgur.com/AjVf9pU.png,
https://i.imgur.com/sqEO7GL.png,
https://i.imgur.com/dXlush6.png
private static JLabel[] imagesArray;
You are creating a static array for a JLabel component.
Later it looks to me like you attempt to add a JLabel from the array to your panel:
JLabel pic = labelsArray[selectedValue];
pic.setPreferredSize(new Dimension(150, 150));
imgPanel.add(pic);
The problem is a Swing component can only have a single parent.
So by adding the JLabel to the second panel you remove it from the first panel.
Don't keep a static array of JLabels.
Instead keep a static array of ImageIcon. An Icon CAN be shared by multiple components.
Then when you want to add the label to the panel you create a new JLabel using the ImageIcon.
I need to create a simple GUI app using Swing in Eclipse. I've decided that I wanted to make a simple Car Rental service app.
I'm not too sure on how to attach prices to the car models and days that are in two separate combo boxes. I'm also not too sure on how to make the combined price of the car model and day appear in a text box once a hire button is pressed.
Below is a picture of my GUI just so you guys can see what I'm working with. I've also added my code that I have so far.
Picture of my GUI
private JLabel l0 = new JLabel(" Car Rental ");
private JLabel l1 = new JLabel("Name ");
private JTextField t1=new JTextField(" ",8);
private JLabel l2 = new JLabel("Email ");
private JTextField t2=new JTextField(" ",8);
private JLabel l3 = new JLabel("Phone Number ");
private JTextField t3=new JTextField("0",8);
private JLabel l4 = new JLabel("Car Model ");
private String [] models={"BMW","Mercedes","Audi"};
private JComboBox c1=new JComboBox(models);
private JLabel l5 = new JLabel("Days ");
private String [] days={"1","2","3","4","5","6","7"};
private JComboBox c2=new JComboBox(days);
private JButton b1=new JButton("Hire");
private JTextField t4=new JTextField("0",8);
private JButton b2=new JButton("Print Receipt");
private JButton b3=new JButton("Exit");
private JPanel p1=new JPanel();
public MyFrame2(String s){
super(s);
Container content=getContentPane();
content.setLayout(new FlowLayout());
Font f=new Font("TimesRoman", Font.BOLD,20);
p1.setLayout(new GridLayout(7,2));
l0.setFont(f); l1.setFont(f);
content.add(l0);
p1.add(l1); p1.add(t1);
p1.add(l2); p1.add(t2);
p1.add(l3); p1.add(t3);
p1.add(l4); p1.add(c1);
p1.add(l5); p1.add(c2);
p1.add(b1); p1.add(t4);
p1.add(b2); p1.add(b3);
content.add(p1);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
setSize(270,320); setVisible(true);}
public void actionPerformed(ActionEvent e){
Object target=e.getSource();
if (target==b1)
if (target==b2){
System.out.println("====Receipt====");
System.out.println("Name: " + t1.getText());
System.out.println("Phone Number: " + t3.getText());
System.out.println("Car Model: " + c1.getSelectedItem());
System.out.println("Days: " + c2.getSelectedItem());}
if (target==b3) {
System.exit(1);}
}
}
The below code should get you started. It is incomplete since I didn't find all the requirements in your question.
Explanations after the code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class CarsHire implements ActionListener, Runnable {
private JButton exitButton;
private JButton hireButton;
private JButton receiptButton;
private JComboBox<Car> carModelsCombo;
private JComboBox<Integer> daysCombo;
private JFrame frame;
private JTextField emailTextField;
private JTextField nameTextField;
private JTextField phoneTextField;
private JTextField priceTextField;
#Override // java.awt.event.ActionListener
public void actionPerformed(ActionEvent event) {
Object src = event.getSource();
if (exitButton == src) {
System.exit(0);
}
else if (hireButton == src) {
displayPrice();
}
else if (receiptButton == src) {
System.out.println("====Receipt====");
System.out.println("Name: " + t1.getText());
System.out.println("Phone Number: " + t3.getText());
System.out.println("Car Model: " + c1.getSelectedItem());
System.out.println("Days: " + c2.getSelectedItem());
}
}
#Override // java.lang.Runnable
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createHeaderPanel(), BorderLayout.PAGE_START);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
receiptButton = new JButton("Print Receipt");
receiptButton.setMnemonic(KeyEvent.VK_R);
receiptButton.addActionListener(this);
buttonsPanel.add(receiptButton);
exitButton = new JButton("Exit");
exitButton.setMnemonic(KeyEvent.VK_X);
exitButton.addActionListener(this);
buttonsPanel.add(exitButton);
exitButton.setPreferredSize(receiptButton.getPreferredSize());
return buttonsPanel;
}
private JPanel createHeaderPanel() {
JPanel headerPanel = new JPanel();
JLabel headerLabel = new JLabel("Car Rental");
Font f = new Font("TimesRoman", Font.BOLD, 20);
headerLabel.setFont(f);
headerPanel.add(headerLabel);
return headerPanel;
}
private JPanel createMainPanel() {
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.insets.top = 5;
gbc.anchor = GridBagConstraints.LINE_START;
// First row of form.
JLabel nameLabel = new JLabel("Name");
nameLabel.setDisplayedMnemonic(KeyEvent.VK_N);
mainPanel.add(nameLabel, gbc);
gbc.gridx = 1;
nameTextField = new JTextField(10);
mainPanel.add(nameTextField, gbc);
nameLabel.setLabelFor(nameTextField);
// Second row of form.
gbc.gridx = 0;
gbc.gridy = 1;
JLabel emailLabel = new JLabel("Email");
emailLabel.setDisplayedMnemonic(KeyEvent.VK_E);
mainPanel.add(emailLabel, gbc);
gbc.gridx = 1;
emailTextField = new JTextField(10);
mainPanel.add(emailTextField, gbc);
emailLabel.setLabelFor(emailTextField);
gbc.gridx = 0;
gbc.gridy = 2;
JLabel phoneLabel = new JLabel("Phone Number");
phoneLabel.setDisplayedMnemonic(KeyEvent.VK_P);
mainPanel.add(phoneLabel, gbc);
gbc.gridx = 1;
phoneTextField = new JTextField(10);
mainPanel.add(phoneTextField, gbc);
phoneLabel.setLabelFor(phoneTextField);
gbc.gridx = 0;
gbc.gridy = 3;
JLabel carModelLabel = new JLabel("Car Model");
carModelLabel.setDisplayedMnemonic(KeyEvent.VK_M);
mainPanel.add(carModelLabel, gbc);
gbc.gridx = 1;
Car[] carModels = new Car[]{new Car("BMW", new BigDecimal(36295)),
new Car("Mercedes", new BigDecimal(33795)),
new Car("Audi", new BigDecimal(34295))};
carModelsCombo = new JComboBox<>(carModels);
carModelsCombo.setSelectedIndex(-1);
mainPanel.add(carModelsCombo, gbc);
carModelLabel.setLabelFor(carModelsCombo);
gbc.gridx = 0;
gbc.gridy = 4;
JLabel daysLabel = new JLabel("Days");
daysLabel.setDisplayedMnemonic(KeyEvent.VK_D);
mainPanel.add(daysLabel, gbc);
gbc.gridx = 1;
daysCombo = new JComboBox<>(new Integer[]{1, 2, 3, 4, 5, 6, 7});
daysCombo.setSelectedIndex(-1);
mainPanel.add(daysCombo, gbc);
daysLabel.setLabelFor(daysCombo);
gbc.gridx = 0;
gbc.gridy = 5;
hireButton = new JButton("Hire");
hireButton.setMnemonic(KeyEvent.VK_H);
hireButton.addActionListener(this);
mainPanel.add(hireButton, gbc);
gbc.gridx = 1;
priceTextField = new JTextField(10);
mainPanel.add(priceTextField, gbc);
return mainPanel;
}
private void displayPrice() {
Car car = (Car) carModelsCombo.getSelectedItem();
if (car != null) {
BigDecimal price = car.getPrice();
priceTextField.setText(price.toString());
}
}
/**
* #param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new CarsHire());
}
}
class Car {
private String model;
private BigDecimal price;
public Car(String model, BigDecimal price) {
this.model = model;
this.price = price;
}
public String getModel() {
return model;
}
public BigDecimal getPrice() {
return price;
}
public String toString() {
return model;
}
}
Swing code is executed on the Event Dispatch Thread (EDT). The JFrame constructor will launch the EDT but there was a time where Oracle recommended explicitly launching the EDT via method invokeLater() of class EventQueue. That method takes a single argument which is an instance of a class that implements the Runnable interface.
Swing uses the Model-View-Controller (MVC) paradigm so each Swing component has a model that stores the data that the component displays. JComboBox model is its list of items. That list can contain objects of any class. The value displayed by the JComboBox is the value returned by the toString() method of the class. Hence I created a Car class that contains the car's model and its price. Hence what is displayed in the JComboBox is just the [car] model, but the selected item is actually an instance of class Car. So in the displayPrice() method, I know that the value returned by getSelectedItem() must be an instance of Car (or null if nothing is selected). From there it's simple to obtain the [car] price and display it in the priceTextField.
Initially, I thought the price meant the actual price of the car, that's why I used BigDecimal for the price in class Car.
As I said in my comment to your question, I use GridBagLayout since it is very suitable for laying out forms. There are other layout managers that are also suitable for laying out forms. I am just used to using GridBagLayout.
I also use mnemonics. For example if you press the keys Alt+H it will activate the Hire button and if you press Alt+N, the Name text field will become the focused field.
Refer to Using Top-Level Containers which is part of Oracle's java tutorials. The default content pane for a JFrame is a JPanel whose layout manager is BorderLayout. When you program in Swing you need to look at the source code a lot to understand what's going on and how best to utilize the framework.
I have a JTextArea that is filled with numbers with no duplicates. There is an add and remove button. I have programmed the add button, but I am struggling with programming the remove button. I know how to remove the number from the array, but I'm not sure how to remove the number from the text area.
How do I remove a line from a text area that contains a certain number?
Extra notes:
The only input is integers.
Your question may in fact be an XY Problem where you ask how to fix a specific code problem when the best solution is to use a different approach entirely. Consider using a JList and not a JTextArea. You can easily rig it up to look just like a JTextArea, but with a JList, you can much more easily remove an item such as a line by removing it from its model.
For example:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class NumberListEg extends JPanel {
private static final int VIS_ROW_COUNT = 10;
private static final int MAX_VALUE = 10000;
private DefaultListModel<Integer> listModel = new DefaultListModel<>();
private JList<Integer> numberList = new JList<>(listModel);
private JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, MAX_VALUE, 1));
private JButton addNumberButton = new JButton(new AddNumberAction());
public NumberListEg() {
JPanel spinnerPanel = new JPanel();
spinnerPanel.add(spinner);
JPanel addNumberPanel = new JPanel();
addNumberPanel.add(addNumberButton);
JPanel removeNumberPanel = new JPanel();
JButton removeNumberButton = new JButton(new RemoveNumberAction());
removeNumberPanel.add(removeNumberButton);
JPanel eastPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
// gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(3, 3, 3, 3);
eastPanel.add(spinner, gbc);
gbc.gridy = GridBagConstraints.RELATIVE;
eastPanel.add(addNumberButton, gbc);
eastPanel.add(removeNumberButton, gbc);
// eastPanel.add(Box.createVerticalGlue(), gbc);
numberList.setVisibleRowCount(VIS_ROW_COUNT);
numberList.setPrototypeCellValue(1234567);
numberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane listPane = new JScrollPane(numberList);
listPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(listPane, BorderLayout.CENTER);
add(eastPanel, BorderLayout.LINE_END);
}
private class AddNumberAction extends AbstractAction {
public AddNumberAction() {
super("Add Number");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
}
#Override
public void actionPerformed(ActionEvent arg0) {
int value = (int) spinner.getValue();
if (!listModel.contains(value)) {
listModel.addElement(value);
}
}
}
private class RemoveNumberAction extends AbstractAction {
public RemoveNumberAction() {
super("Remove Number");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
#Override
public void actionPerformed(ActionEvent e) {
Integer selection = numberList.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
}
}
}
private static void createAndShowGui() {
NumberListEg mainPanel = new NumberListEg();
JFrame frame = new JFrame("Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
can not be remove from the array,you can to make index to be empty,for example String a= Integer.toString(type for int),then a.replace("your int","");
I'm trying to make taxi booking application. Now, if I (for example) want to schedule by mobile application, then I want to enable combobox with drivers name and if someone schedule via phone call, then I want to enable combobox with dispatchers names. How? I tryied something in initActions(), but, obvious it's not working...
public class OrderWindow extends JFrame {
private JLabel lblCustomerName;
private JTextField txtCustomerName;
private JLabel lblDateOrder;
private JPanel pnlDateOrder;
private JLabel lblDepartureAdress;
private JTextField txtADepartureAdress`
private JComboBox cbDriver;
private JRadioButton rbMobileApp;
private JRadioButton rbPhoneCall;
private ButtonGroup bgOrder;
public OrderWindow(){
setTitle("Scheduling");
setSize(400, 400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
initGUI();
initActions();
}
private void initActions() {
rbMobileApp.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==rbMobileApp) {
setEnabled(rbMobilnaAplikacija.isSelected());
}
}
});
}
private void initGUI() {
MigLayout mig = new MigLayout("wrap 2", "[][]", "[]10[][]10[]");
setLayout(mig);
lblCustomerName = new JLabel("Name and Lastname");
txtCustomerName = new JTextField(20);
lblDepartureAdress = new JLabel("Adress");
txtDepartureAdress = new JTextField(20);
rbMobileApp = new JRadioButton("Application");
rbPhoneCall = new JRadioButton("Call");
bgPorudzbina = new ButtonGroup();
add(lblCustomerName);
add(txtCustomerName);
add(lblDepartureAdress);
add(txtDepartureAdress);
add(rbMobileApp);
add(rbPhoneCall);
bgOrder = new ButtonGroup();
bgOrder.add(rbMobileApp);
bgOrder.add(rbPhoneCall);
}
}
If you have just 2 JRadioButtons and 2 JComboBoxes, then the solution is simple: Give the JRadioButtons an ItemListener that checks if the radio is selected, and if so, select the corresponding JComboBox.
e.g.,
radioBtn.addItemListener(evt -> {
combo.setEnabled(evt.getStateChange() == ItemEvent.SELECTED);
});
If you have a bunch of JRadioButton / JComboBox combinations, then you need a more robust way to connect the two, and that can be achieved by either using a Map such as a HashMap, or by putting both objects into their own class, for example something like:
import java.awt.event.ItemEvent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
public class RadioCombo<T> {
private JRadioButton radioBtn;
private JComboBox<T> combo;
public RadioCombo(String text, DefaultComboBoxModel<T> model) {
radioBtn = new JRadioButton(text);
combo = new JComboBox<>(model);
combo.setEnabled(false);
radioBtn.addItemListener(evt -> {
combo.setEnabled(evt.getStateChange() == ItemEvent.SELECTED);
});
}
public JRadioButton getRadioBtn() {
return radioBtn;
}
public JComboBox<T> getCombo() {
return combo;
}
}
Then you could use it like so:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class TestRadioCombo extends JPanel {
private static final String[] DATA = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private static final String[] INNER_DATA = {"One", "Two", "Three", "Four", "Five"};
private static final int GAP = 3;
public TestRadioCombo() {
ButtonGroup buttonGroup = new ButtonGroup();
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new GridBagLayout());
for (String datum : DATA) {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
for (String innerDatum : INNER_DATA) {
String item = datum + " - " + innerDatum;
model.addElement(item);
}
RadioCombo<String> radioCombo = new RadioCombo<>(datum, model);
buttonGroup.add(radioCombo.getRadioBtn());
addRadioCombo(radioCombo);
}
}
private void addRadioCombo(RadioCombo<String> radioCombo) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, 2 * GAP);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(radioCombo.getRadioBtn(), gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
add(radioCombo.getCombo(), gbc);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestRadioCombo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Another option is to have a bunch of JRadioButtons and only one JComboBox, and then in your radio button item listener, swap the JComboBox's model depending on which JRadioButton was selected.
I want the various components to spread out and fill the entire window.
Have you tried anything else? Yes, I tried GridLayout but then the buttons look huge. I also tried pack() which made the window small instead. The window should be 750x750 :)
What I was trying is this:
These 4 buttons on the top as a thin strip
The scroll pane with JPanels inside which will contain all the video conversion tasks. This takes up the maximum space
A JPanel at the bottom containing a JProgressBar as a thin strip.
But something seems to have messed up somewhere. Please help me solve this
SSCCE
import java.awt.*;
import javax.swing.*;
import com.explodingpixels.macwidgets.*;
public class HudTest {
public static void main(String[] args) {
HudWindow hud = new HudWindow("Window");
hud.getJDialog().setSize(750, 750);
hud.getJDialog().setLocationRelativeTo(null);
hud.getJDialog().setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addVideo = HudWidgetFactory.createHudButton("Add New Video");
JButton removeVideo = HudWidgetFactory.createHudButton("Remove Video");
JButton startAll = HudWidgetFactory.createHudButton("Start All Tasks");
JButton stopAll = HudWidgetFactory.createHudButton("Stop All Tasks");
buttonPanel.add(addVideo);
buttonPanel.add(startAll);
buttonPanel.add(removeVideo);
buttonPanel.add(stopAll);
JPanel taskPanel = new JPanel(new GridLayout(0,1));
JScrollPane taskScrollPane = new JScrollPane(taskPanel);
IAppWidgetFactory.makeIAppScrollPane(taskScrollPane);
for(int i=0;i<10;i++){
ColorPanel c = new ColorPanel();
c.setPreferredSize(new Dimension(750,100));
taskPanel.add(c);
}
JPanel progressBarPanel = new JPanel();
JComponent component = (JComponent) hud.getContentPane();
component.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
Insets in = new Insets(2,2,2,2);
gbc.insets = in;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 10;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
component.add(buttonPanel,gbc);
gbc.gridy += 1;
gbc.gridheight = 17;
component.add(taskScrollPane,gbc);
gbc.gridy += 17;
gbc.gridheight = 2;
component.add(progressBarPanel,gbc);
hud.getJDialog().setVisible(true);
}
}
Use this
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridbagConstraints.BOTH
Why not simply place three JPanels on top of one JPanel with BorderLayout as Layout Manager, where the middle JPanel with all custom panels with their respective sizes can be accommodated inside a JScrollPane, as shown in the below example :
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 5/17/13
* Time: 6:09 PM
* To change this template use File | Settings | File Templates.
*/
public class PlayerBase
{
private JPanel contentPane;
private JPanel buttonPanel;
private JPanel centerPanel;
private CustomPanel[] colourPanel;
private JPanel progressPanel;
private JButton addVideoButton;
private JButton removeVideoButton;
private JButton startAllButton;
private JButton stopAllButton;
private JProgressBar progressBar;
private Random random;
public PlayerBase()
{
colourPanel = new CustomPanel[10];
random = new Random();
}
private void displayGUI()
{
JFrame playerWindow = new JFrame("Player Window");
playerWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
addVideoButton = new JButton("Add New Video");
removeVideoButton = new JButton("Remove Video");
startAllButton = new JButton("Start all tasks");
stopAllButton = new JButton("Stop all tasks");
buttonPanel.add(addVideoButton);
buttonPanel.add(removeVideoButton);
buttonPanel.add(startAllButton);
buttonPanel.add(stopAllButton);
contentPane.add(buttonPanel, BorderLayout.PAGE_START);
JScrollPane scroller = new JScrollPane();
centerPanel = new JPanel(new GridLayout(0, 1, 2, 2));
for (int i = 0; i < colourPanel.length; i++)
{
colourPanel[i] = new CustomPanel(new Color(
random.nextInt(255), random.nextInt(255)
, random.nextInt(255)));
centerPanel.add(colourPanel[i]);
}
scroller.setViewportView(centerPanel);
contentPane.add(scroller, BorderLayout.CENTER);
progressPanel = new JPanel(new BorderLayout(5, 5));
progressBar = new JProgressBar(SwingConstants.HORIZONTAL);
progressPanel.add(progressBar);
contentPane.add(progressPanel, BorderLayout.PAGE_END);
playerWindow.setContentPane(contentPane);
playerWindow.pack();
//playerWindow.setSize(750, 750);
playerWindow.setLocationByPlatform(true);
playerWindow.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new PlayerBase().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
public CustomPanel(Color backGroundColour)
{
setOpaque(true);
setBackground(backGroundColour);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(750, 100));
}
}
OUTPUT :