Elements Alignment in Java Applet - java

I am trying to align several elements in a Java Applet, I am not able to do it. Please help me. Here is my code:
public class User extends JApplet implements ActionListener,ItemListener {
public int sentp,recievedp,corruptedp;
public String stetus;
public double energi,nodeid,en;
TextField name,time,initene,ampco,acttran;
Button rsbt,vlbt,insd ;
Choice ch,ch2;
public String patrn;
public void init() {
this.setSize(800,600);
Label namep= new Label("\n\nEnter the No. of Nodes: ", Label.CENTER);
name = new TextField(5);
Label timep = new Label("\n\nEnter time of Simulation: ",Label.CENTER);
time = new TextField(5);
Label initen = new Label("\n\nInitial Energy Of Each Sensor Node:");
initene = new TextField("10^-4 Joules");
initene.setEditable(false);
Label ampcon = new Label("\n\nAmplifier Constant:");
ampco = new TextField("10^-12 Joules");
ampco.setEditable(false);
Label acttrans = new Label("\n\nEnergy Required To Activate Transmitter/Reciever:");
acttran = new TextField("50 ^ -9 Joules");
acttran.setEditable(false);
Label chp = new Label("\n\nSelect Radio Model:",Label.CENTER);
rsbt = new Button("Run The Simulation");
ch= new Choice();
ch.add("");
ch.add("Gaussian RadioModel");
ch.add("Rayleigh RadioModel");
Label pat= new Label("\n\nDistribution Pattern");
ch2= new Choice();
ch2.add("");
ch2.add("Rectangular Pattern");
ch2.add("Linear Pattern");
ch2.add("Random Pattern");
vlbt=new Button("ViewLog");
insd=new Button("Details of node");
JPanel cp = new JPanel();
this.add(cp);
GridBagLayout gridb = new GridBagLayout();
Container cont = getContentPane();
cont.setLayout(gridb);
add(cp);
GroupLayout layout = new GroupLayout(cp);
cp.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(namep)
.addComponent(name)
.addComponent(rsbt))
.addGroup(layout.createSequentialGroup()
.addComponent(timep)
.addComponent(time)
.addComponent(vlbt))
.addGroup(layout.createSequentialGroup()
.addComponent(chp)
.addComponent(ch))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(pat)
.addComponent(ch2))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(initen)
.addComponent(initene))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(ampcon)
.addComponent(ampco))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(acttrans)
.addComponent(acttran))
);
rsbt.addActionListener(this);
vlbt.addActionListener(this);
insd.addActionListener(this);
ch.addItemListener(this);
ch2.addItemListener(this);
}

Try this, is this good for you :
import java.awt.*;
import javax.swing.*;
public class AppletLayout extends JApplet
{
private JTextField noNodeField;
private JTextField timeSimField;
private JTextField iniEngField;
private JTextField ampConsField;
private JTextField engReqField;
private JComboBox selModeCombo;
private JComboBox distPattCombo;
private JButton runSimButton;
private JButton logButton;
private JButton detailNodeButton;
private String[] selectionModelString = {"", "Gaussian RadioModel"
, "Rayleigh RadioModel"};
private String[] distPatternString = {"", "Rectangular Pattern"
, "Linear Pattern"
, "Random Pattern"};
public void init()
{
try
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndDisplayGUI();
}
});
}
catch(Exception e)
{
System.err.println("Unable to Create and Display GUI : " + e.getMessage());
e.printStackTrace();
}
}
private void createAndDisplayGUI()
{
JLabel noNodeLabel = new JLabel("Enter the No. of Nodes :", JLabel.LEFT);
noNodeField = new JTextField(5);
JLabel timeSimLabel = new JLabel("Enter time of Simulation :", JLabel.LEFT);
timeSimField = new JTextField(5);
JLabel iniEngLabel = new JLabel("Initial Energy Of Each Sensor Node :", JLabel.LEFT);
iniEngField = new JTextField("10^-4 Joules");
JLabel ampConsLabel = new JLabel("Amplifier Constant :", JLabel.LEFT);
ampConsField = new JTextField("10^-12 Joules");
JLabel engReqLabel = new JLabel("Energy Required To Activate Transmitter/Reciever :", JLabel.LEFT);
engReqField = new JTextField("50 ^ -9 Joules");
JLabel selModeLabel = new JLabel("Select Radio Model :", JLabel.LEFT);
selModeCombo = new JComboBox(selectionModelString);
JLabel distPattLabel = new JLabel("Distribution Pattern :", JLabel.LEFT);
distPattCombo = new JComboBox(selectionModelString);
runSimButton = new JButton("Run Simulation");
logButton = new JButton("View Log");
detailNodeButton = new JButton("Details of Node");
JComponent contentPane = (JComponent) getContentPane();
JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
topPanel.setLayout(new GridLayout(0, 2));
topPanel.add(noNodeLabel);
topPanel.add(noNodeField);
topPanel.add(timeSimLabel);
topPanel.add(timeSimField);
topPanel.add(iniEngLabel);
topPanel.add(iniEngField);
topPanel.add(ampConsLabel);
topPanel.add(ampConsField);
topPanel.add(engReqLabel);
topPanel.add(engReqField);
topPanel.add(selModeLabel);
topPanel.add(selModeCombo);
topPanel.add(distPattLabel);
topPanel.add(distPattCombo);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
//buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.setLayout(new GridLayout(0, 1, 5, 5));
buttonPanel.add(runSimButton);
buttonPanel.add(logButton);
buttonPanel.add(detailNodeButton);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout(5, 5));
mainPanel.add(topPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.LINE_END);
contentPane.add(mainPanel, BorderLayout.PAGE_START);
setSize(1000, 600);
}
}
Here is the output :

Your current code looks pretty much like you are using some sort of GUI builder tool to generate the final layout.
For maximum control, build the component and add them to the panel. If you are looking to use GridBagLayout as shown in your code then follow the sequence construct as shown below
JPanel p1 = new JPanel(new GridBagLayout());
GridBagConstraints cs = new GridBagConstraints();
cs.fill = GridBagConstraints.HORIZONTAL;
lblUsername = new JLabel("Name: ");
cs.gridx = 0;
cs.gridy = 0;
cs.gridwidth = 1;
p1.add(lblUsername, cs);
txtUsername = new JTextField("", 20);
cs.gridx = 1;
cs.gridy = 0;
cs.gridwidth = 2;
p1.add(txtUsername, cs);
...
add(cp);
Or alternatively use BorderLayout or FlowLayout to hold the components on your panel:
JPanel p1 = new JPanel(new BorderLayout());
p1.add(lblUsername, BorderLaout.EAST);
...

When you say this
JPanel cp = new JPanel();
it means you're going to get a FlowLayout automatically. You probably want a different one.
Edit: OK, I can see where you're giving cp a GroupLayout, but I don't see where you pack() the window that cp is in or call setVisible().
Edit: But that doesn't matter for an applet.

Related

GUI objects disappearing when adding center panel to my content pane

I'm creating a simple UI using GUI objects to input data but whenever I add the center panel to the contentPane, my JLabels disappear. Additionally, the JTextFields, JComboBoxs and JButtons don't respond to clicking or entering keystrokes. If I don't add the centerPanel, or add it and start the applet with width and height parameters of 1 and 1, everything works perfectly.
When I stretch out the screen, after adding the center panel to a normal run configuration, the objects will appear outside of the initial window. I've defined all of the objects as private instance variables before the listed code, so that isn't the issue. Please help, I'm baffled!
Here's my code:
public void begin() {
// creates the GUI Objects for the northPanel
northPanel = new JPanel();
northPanel.setLayout(new GridLayout(1, 4));
searchBox = new JTextField();
searchBoxLabel = new JLabel("Search ID #:");
search = new JButton("Search");
search.addActionListener(this);
northPanel.add(searchBoxLabel);
northPanel.add(searchBox);
northPanel.add(search);
// creates the GUI OBjects for the southPanel
southDivider = new JPanel();
southDivider.setLayout(new GridLayout(2, 1));
southPanel = new JPanel();
southPanel.setLayout(new GridLayout(1, 3));
enter = new JButton("Enter");
incrementInfo = new JButton("Increment ID");
setCurrentTimeDate = new JButton("Current Time/Date");
findRate = new JButton("Find Yield Rate");
findRate.addActionListener(this);
enter.addActionListener(this);
incrementInfo.addActionListener(this);
setCurrentTimeDate.addActionListener(this);
southPanel.add(findRate);
southPanel.add(setCurrentTimeDate);
southPanel.add(incrementInfo);
southPanel.add(enter);
messageLabel = new JLabel("Welcome to the Stringer Application");
southDivider.add(southPanel);
southDivider.add(messageLabel);
// create the GUI objects on the eastPanel
eastPanel = new JPanel();
eastPanel.setLayout(new GridLayout(5, 2));
cellType = new JComboBox();
cellType.addItem("Rect");
cellType.addItem("Cham");
cellTypeLabel = new JLabel("Cell Type:");
ecaCode = new JComboBox();
ecaCode.addItem("A");
ecaCode.addItem("B");
ecaCodeLabel = new JLabel("ECA Code:");
ecaSyringeNum = new JTextField();
ecaSyringeNumLabel = new JLabel("Eca Syringe #:");
passFail = new JComboBox();
passFail.addItem("Pass");
passFail.addItem("Fail");
passFailLabel = new JLabel("Pass/Fail:");
operator = new JTextField();
operatorLabel = new JLabel("Operator:");
cellType.addActionListener(this);
ecaCode.addActionListener(this);
passFail.addActionListener(this);
eastPanel.add(operatorLabel);
eastPanel.add(operator);
eastPanel.add(cellTypeLabel);
eastPanel.add(cellType);
eastPanel.add(ecaCodeLabel);
eastPanel.add(ecaCode);
eastPanel.add(ecaSyringeNumLabel);
eastPanel.add(ecaSyringeNum);
eastPanel.add(passFailLabel);
eastPanel.add(passFail);
// create the GUI objects on the westPanel
westPanel = new JPanel();
westPanel.setLayout(new GridLayout(6, 2));
yieldLabel = new JLabel("Current Yield:");
yieldValueLabel = new JLabel("Select Date/Times");
yieldAfterDate = new JTextField();
yieldAfterTime = new JTextField();
yieldBeforeDate = new JTextField();
yieldBeforeTime = new JTextField();
yieldAfterDateLabel = new JLabel("After Date:");
yieldAfterTimeLabel = new JLabel("After Time:");
yieldBeforeDateLabel = new JLabel("Before Date:");
yieldBeforeTimeLabel = new JLabel("Before Time:");
setBeforeToCurrentLabel = new JLabel("<html>'Set to Current' for <br> Current Date/Time</html>");
fillBeforeWithCurrent = new JButton("Set to Current");
fillBeforeWithCurrent.addActionListener(this);
westPanel.add(yieldLabel);
westPanel.add(yieldValueLabel);
westPanel.add(yieldAfterDateLabel);
westPanel.add(yieldAfterDate);
westPanel.add(yieldAfterTimeLabel);
westPanel.add(yieldAfterTime);
westPanel.add(yieldBeforeDateLabel);
westPanel.add(yieldBeforeDate);
westPanel.add(yieldBeforeTimeLabel);
westPanel.add(yieldBeforeTime);
westPanel.add(setBeforeToCurrentLabel);
westPanel.add(fillBeforeWithCurrent);
// create the GUI objects for the centerPanel
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 4));
date = new JTextField(getCurrentDate());
dateLabel = new JLabel("Date:");
time = new JTextField(getCurrentTime());
timeLabel = new JLabel("Time:");
stringID = new JTextField();
stringIDLabel = new JLabel("String ID:");
cellLot = new JTextField();
cellLotLabel = new JLabel("Cell Lot #:");
cellEff = new JTextField();
cellEffLabel = new JLabel("Cell Eff:");
comments = new JTextField();
commentsLabel = new JLabel("Comments:");
centerPanel.add(dateLabel);
centerPanel.add(date);
centerPanel.add(timeLabel);
centerPanel.add(time);
centerPanel.add(stringIDLabel);
centerPanel.add(stringID);
centerPanel.add(cellLotLabel);
centerPanel.add(cellLot);
centerPanel.add(cellEffLabel);
centerPanel.add(cellEff);
centerPanel.add(commentsLabel);
centerPanel.add(comments);
// add the panel's to the contentPane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(northPanel, BorderLayout.NORTH);
contentPane.add(southDivider, BorderLayout.SOUTH);
contentPane.add(eastPanel, BorderLayout.EAST);
contentPane.add(westPanel, BorderLayout.WEST);
contentPane.validate();
}
I have tested your code and it is working with no problems.
Most likely you are adding components some where else to the container, and by default any added components goes to center, which cause the old center panel to be removed , and the the swing frame to draw dirty area.
EDIT:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test2 extends JFrame {
public Test2() {
begin();
}
public void begin() {
// creates the GUI Objects for the northPanel
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(1, 4));
JTextField searchBox = new JTextField();
JLabel searchBoxLabel = new JLabel("Search ID #:");
JButton search = new JButton("Search");
northPanel.add(searchBoxLabel);
northPanel.add(searchBox);
northPanel.add(search);
// creates the GUI OBjects for the southPanel
JPanel southDivider = new JPanel();
southDivider.setLayout(new GridLayout(2, 1));
JPanel southPanel = new JPanel();
southPanel.setLayout(new GridLayout(1, 3));
JButton enter = new JButton("Enter");
JButton incrementInfo = new JButton("Increment ID");
JButton setCurrentTimeDate = new JButton("Current Time/Date");
JButton findRate = new JButton("Find Yield Rate");
southPanel.add(findRate);
southPanel.add(setCurrentTimeDate);
southPanel.add(incrementInfo);
southPanel.add(enter);
JLabel messageLabel = new JLabel("Welcome to the Stringer Application");
southDivider.add(southPanel);
southDivider.add(messageLabel);
// create the GUI objects on the eastPanel
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new GridLayout(5, 2));
JComboBox cellType = new JComboBox();
cellType.addItem("Rect");
cellType.addItem("Cham");
JLabel cellTypeLabel = new JLabel("Cell Type:");
JComboBox ecaCode = new JComboBox();
ecaCode.addItem("A");
ecaCode.addItem("B");
JLabel ecaCodeLabel = new JLabel("ECA Code:");
JTextField ecaSyringeNum = new JTextField();
JLabel ecaSyringeNumLabel = new JLabel("Eca Syringe #:");
JComboBox passFail = new JComboBox();
passFail.addItem("Pass");
passFail.addItem("Fail");
JLabel passFailLabel = new JLabel("Pass/Fail:");
JTextField operator = new JTextField();
JLabel operatorLabel = new JLabel("Operator:");
eastPanel.add(operatorLabel);
eastPanel.add(operator);
eastPanel.add(cellTypeLabel);
eastPanel.add(cellType);
eastPanel.add(ecaCodeLabel);
eastPanel.add(ecaCode);
eastPanel.add(ecaSyringeNumLabel);
eastPanel.add(ecaSyringeNum);
eastPanel.add(passFailLabel);
eastPanel.add(passFail);
// create the GUI objects on the westPanel
JPanel westPanel = new JPanel();
westPanel.setLayout(new GridLayout(6, 2));
JLabel yieldLabel = new JLabel("Current Yield:");
JLabel yieldValueLabel = new JLabel("Select Date/Times");
JTextField yieldAfterDate = new JTextField();
JTextField yieldAfterTime = new JTextField();
JTextField yieldBeforeDate = new JTextField();
JTextField yieldBeforeTime = new JTextField();
JLabel yieldAfterDateLabel = new JLabel("After Date:");
JLabel yieldAfterTimeLabel = new JLabel("After Time:");
JLabel yieldBeforeDateLabel = new JLabel("Before Date:");
JLabel yieldBeforeTimeLabel = new JLabel("Before Time:");
JLabel setBeforeToCurrentLabel = new JLabel("<html>'Set to Current' for <br> Current Date/Time</html>");
JButton fillBeforeWithCurrent = new JButton("Set to Current");
westPanel.add(yieldLabel);
westPanel.add(yieldValueLabel);
westPanel.add(yieldAfterDateLabel);
westPanel.add(yieldAfterDate);
westPanel.add(yieldAfterTimeLabel);
westPanel.add(yieldAfterTime);
westPanel.add(yieldBeforeDateLabel);
westPanel.add(yieldBeforeDate);
westPanel.add(yieldBeforeTimeLabel);
westPanel.add(yieldBeforeTime);
westPanel.add(setBeforeToCurrentLabel);
westPanel.add(fillBeforeWithCurrent);
// create the GUI objects for the centerPanel
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(3, 4));
JTextField date = new JTextField();
JLabel dateLabel = new JLabel("Date:");
JTextField time = new JTextField();
JLabel timeLabel = new JLabel("Time:");
JTextField stringID = new JTextField();
JLabel stringIDLabel = new JLabel("String ID:");
JTextField cellLot = new JTextField();
JLabel cellLotLabel = new JLabel("Cell Lot #:");
JTextField cellEff = new JTextField();
JLabel cellEffLabel = new JLabel("Cell Eff:");
JTextField comments = new JTextField();
JLabel commentsLabel = new JLabel("Comments:");
centerPanel.add(dateLabel);
centerPanel.add(date);
centerPanel.add(timeLabel);
centerPanel.add(time);
centerPanel.add(stringIDLabel);
centerPanel.add(stringID);
centerPanel.add(cellLotLabel);
centerPanel.add(cellLot);
centerPanel.add(cellEffLabel);
centerPanel.add(cellEff);
centerPanel.add(commentsLabel);
centerPanel.add(comments);
// add the panel's to the contentPane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(centerPanel, BorderLayout.CENTER);
contentPane.add(northPanel, BorderLayout.NORTH);
contentPane.add(southDivider, BorderLayout.SOUTH);
contentPane.add(eastPanel, BorderLayout.EAST);
contentPane.add(westPanel, BorderLayout.WEST);
// contentPane.validate();
setSize(812, 514);
}
public static void main(String[] args) {
Test2 t=new Test2();
// t.begin();
t.setVisible(true);
}
}

Java: Make JTextArea scrollable

This is my first post so please forgive me if I am not following the rules correctly.
I am trying to do something relatively simple in Java. I want to make a JTextArea scrollable. I am aware this has been asked before (Java :Add scroll into text area). However, when I follow this example by adding JTextArea to JScrollPane my JTextArea does not become scrollable. What is it that I am missing?
Here is my code:
import ...;
public class MyControlPanel extends JPanel {
//Declare variables
private JComboBox accountsBox;
private String[] accType = {"Current Account", "Savings Account"};
private JLabel selAccType, initDeposit, logLabel, simLabel;
private JTextField depositText;
private JTextArea log;
private JScrollPane scroll;
private JButton createAccount, start, stop;
private JPanel panel1, panel2, panel3, panel4, panel5, panel6;
private Timer timer;
private MyAccount theAccount;
private Random randNum1, randNum2;
private DecimalFormat df;
//Constructor
public MyControlPanel() {
//Create instances:
selAccType = new JLabel("Please select account type: "); //JLabel
initDeposit = new JLabel("Input initial deposit: ");
logLabel = new JLabel("Log:");
simLabel = new JLabel();
accountsBox = new JComboBox(accType); //JComboBox
depositText = new JTextField("0"); // JTextField
log = new JTextArea(); //JTextArea
scroll = new JScrollPane(log); //JScrollPane
createAccount = new JButton("Create Account"); //JButton
start = new JButton("Start");
stop = new JButton("Stop");
panel1 = new JPanel(); //JPanel
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();
panel5 = new JPanel();
panel6 = new JPanel();
timer = new Timer(); //Timer
df = new DecimalFormat("#.00");
//Add ActionListeners
createAccount.addActionListener(new ActionListener() {...});
start.addActionListener(new ActionListener() {...});
stop.addActionListener(new ActionListener() {...});
//Set JTextField size
depositText.setColumns(5);
//Set JTextArea size
log.setPreferredSize(new Dimension(780, 150));
//Set panel size
panel1.setPreferredSize(new Dimension(500, 500));
panel2.setPreferredSize(new Dimension(800, 50));
panel3.setPreferredSize(new Dimension(500, 50));
panel4.setPreferredSize(new Dimension(500, 50));
panel5.setPreferredSize(new Dimension(800, 25));
panel6.setPreferredSize(new Dimension(800, 200));
//Set layout in panel5 to align left
panel6.setLayout(new FlowLayout(FlowLayout.LEFT));
//Add components to each panel
addPanels();
//Place objects in the framed window
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.add(panel4);
this.add(panel5);
this.add(panel6);
}
public void addPanels() {...}
public void removePanels() {...}
}
You need to change:
log.setPreferredSize(new Dimension(780, 150));
to:
scroll.setPreferredSize(new Dimension(780, 150));

About the layout of a GUI

I'm in the middle of working on a program. It's GUI has two main parts, the left of the JFrame and the right of the JFrame. (Currently the right half is blank because I havn't started working on it yet).
The left part doesn't look good. All the buttons and textfields are stretched. I want them to have the height of standard buttons, similiar to the ones on this site. (You know, standard windows buttons).
How do I do that?
(I wouldn't want to simply pack() the whole thing, since the right half of the window is going to have a big square JPanel, and so pack()ing would mean that the window will still be square and the buttons on the left half would still be streched up and down).
Here's a picture:
And here's the code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(rect);
optionsPanel.add(oval);
optionsPanel.add(tri);
optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Try this
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class GUI extends JFrame {
JButton rect,oval,tri,free,addPoint;
JLabel xLabel,yLabel;
JTextField xTextField,yTextField;
JPanel leftPanel,rightPanel,optionsPanel,pointsPanel;
public GUI(){
initUI();
}
private void initUI(){
setLayout(new GridLayout(1,2,5,5));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setSize(500,500);
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
JPnel p=new JPanel();
p.add(rect);
p.add(oval);
p.add(tri);
p.add(free);
p.add(addPoint);
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
rightPanel = new JPanel();
optionsPanel = new JPanel();
pointsPanel = new JPanel();
add(leftPanel);
add(rightPanel);
leftPanel.setLayout(new GridLayout(2,1,5,5));
leftPanel.add(optionsPanel);
optionsPanel.setLayout(new GridLayout(1,4,2,2));
optionsPanel.add(p);
//optionsPanel.add(oval);
//optionsPanel.add(tri);
//optionsPanel.add(free);
leftPanel.add(pointsPanel);
pointsPanel.setLayout(new GridLayout(1,5,2,2));
pointsPanel.add(xLabel);
pointsPanel.add(xTextField);
pointsPanel.add(yLabel);
pointsPanel.add(yTextField);
pointsPanel.add(addPoint);
setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}
Like this for JLabels and JTextFields
Please go through following link for more information about Grid layout
How to Use GridLayout
Also try with different layouts in java swing
A Visual Guide to Layout Managers
Please try FlowLayout it is suitable for your requirement.
Just change setLayout(new FlowLayout());
Output :
You have that effect, because you use GridLayout, which resize component to whole cell(vertically/horizontally). You need to use another LayoutManager, or combinations of layouts.
For example I've changed your code with GridBagLayout:
private void initUI(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Graphics Generator");
setLayout(new GridBagLayout());
rect = new JButton("Rectangle");
oval = new JButton("Oval");
tri = new JButton("Triangle");
free = new JButton("Free Shape");
addPoint = new JButton("Add point");
xLabel = new JLabel("X: ");
yLabel = new JLabel("Y: ");
xTextField = new JTextField(2);
yTextField = new JTextField(2);
leftPanel = new JPanel();
leftPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
rightPanel = new JPanel();
rightPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
optionsPanel = new JPanel(new GridBagLayout());
pointsPanel = new JPanel(new GridBagLayout());
GridBagConstraints cMain = new GridBagConstraints();
cMain.insets = new Insets(5, 5, 5, 5);
cMain.gridx = 0;
cMain.gridy = 0;
cMain.anchor = GridBagConstraints.NORTHWEST;
add(leftPanel,cMain);
cMain.fill = GridBagConstraints.BOTH;
cMain.gridx++;
cMain.weighty = 1;
cMain.weightx = 1;
add(rightPanel,cMain);
leftPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(5, 5, 5, 5);
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.WEST;
leftPanel.add(optionsPanel,c);
c.gridy++;
leftPanel.add(pointsPanel,c);
c.gridy = 0;
optionsPanel.add(rect,c);
c.gridx++;
optionsPanel.add(oval,c);
c.gridx++;
optionsPanel.add(tri,c);
c.gridx++;
optionsPanel.add(free,c);
c.gridx = 0;
c.gridy = 1;
pointsPanel.add(xLabel,c);
c.gridx++;
pointsPanel.add(xTextField,c);
c.gridx++;
pointsPanel.add(yLabel,c);
c.gridx++;
pointsPanel.add(yTextField,c);
c.gridx++;
pointsPanel.add(addPoint,c);
setSize(500,500);
setVisible(true);
}

Set icon to JLabel - not display icon

My code:
public class UserDialog extends JDialog {
public UserDialog() {
add(createForm(), BorderLayout.CENTER);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocation(400, 100);
pack();
setVisible(true);
}
public JPanel createForm() {
JPanel panel = new JPanel();
ImageIcon image = new ImageIcon("Check.png");
okBtn = new JButton("Ok");
cancelBtn = new JButton("Cancel");
tempBtn = new JLabel();
fNameLbl = new JLabel("First Name");
fNamePicLbl = new JLabel(image); // add icon to jlable
lNameLbl = new JLabel("Last Name");
lNamePicLbl = new JLabel();
genderLbl = new JLabel("Gender");
maleRb = new JRadioButton("Male");
femaleRb = new JRadioButton("Female");
temp3 = new JLabel();
group = new ButtonGroup();
group.add(maleRb);
group.add(femaleRb);
fNameTf = new JTextField(10);
lNameTf = new JTextField(10);
panel.add(fNameLbl);
panel.add(fNameTf);
panel.add(fNamePicLbl);
panel.add(lNameLbl);
panel.add(lNameTf);
panel.add(lNamePicLbl);
panel.add(genderLbl);
JPanel radioPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
radioPanel.add(maleRb);
radioPanel.add(femaleRb);
panel.add(radioPanel);
panel.add(temp3);
panel.add(okBtn);
okBtn.addActionListener(this);
panel.add(cancelBtn);
cancelBtn.addActionListener(this);
panel.add(tempBtn);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 10, 80, 60);
return panel;
}
When i run program, icon not display.
It seems an issue with path of Check.png. Correct the path and icon shall appear.
If icon is stored under resource folder icons then path should be like below.
ImageIcon image = new ImageIcon("icons/Check.png");

Unwanted line between labels and radio group in Java

In my project, I use Swing controls. I had used a label together with a button group, but there is an unwanted line. Please help. There is a label associated with each radio button group. The unwanted line is there.how to add the labels and corresponding radio button group to the same panel
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import java.util.Arrays;
public class Online extends JFrame {
static JRadioButton[] choice = new JRadioButton[6];
JFrame jtfMainFrame, jtfMainFrame1;
public void createWindow() {
jtfMainFrame = new JFrame("Online Examination");
jtfMainFrame.setSize(800, 500);
jtfMainFrame.setLocation(200, 150);
jtfMainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel pa = new JPanel();
JPanel panlabels = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel pancontrols = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel panEast = new JPanel();
JPanel pan = new JPanel(new FlowLayout());
JLabel qLabel = new JLabel("Question.");
qLabel.setOpaque(true);
qLabel.setForeground(Color.blue);
qLabel.setBackground(Color.lightGray);
JLabel aLabel = new JLabel("Question.");
aLabel.setOpaque(true);
aLabel.setForeground(Color.blue);
aLabel.setBackground(Color.lightGray);
JLabel bLabel = new JLabel("a.");
bLabel.setOpaque(true);
bLabel.setForeground(Color.blue);
bLabel.setBackground(Color.lightGray);
JLabel cLabel = new JLabel("b.");
cLabel.setOpaque(true);
cLabel.setForeground(Color.blue);
cLabel.setBackground(Color.lightGray);
JLabel dLabel = new JLabel("c.");
dLabel.setOpaque(true);
dLabel.setForeground(Color.blue);
dLabel.setBackground(Color.lightGray);
JLabel eLabel = new JLabel("d.");
eLabel.setOpaque(true);
eLabel.setForeground(Color.blue);
eLabel.setBackground(Color.lightGray);
panlabels.add(aLabel, BorderLayout.WEST);
panlabels.add(bLabel, BorderLayout.CENTER);
panlabels.add(cLabel, BorderLayout.CENTER);
panlabels.add(dLabel, BorderLayout.CENTER);
panlabels.add(eLabel, BorderLayout.CENTER);
//panlabels.add(fLabel, BorderLayout.WEST);
//fLabel.setVisible(false);
JLabel ques = new JLabel("q");
ques.setBackground(Color.red);
choice[1] = new JRadioButton("a");
choice[1].setBackground(Color.red);
choice[2] = new JRadioButton("b");
choice[2].setBackground(Color.red);
choice[3] = new JRadioButton("c");
choice[3].setBackground(Color.red);
choice[4] = new JRadioButton("d");
choice[4].setBackground(Color.red);
ButtonGroup bGroup = new ButtonGroup();
pancontrols.add(ques, BorderLayout.WEST);
for (int i = 1; i < 5; i++) {
// pancontrols.add(aLabel,BorderLayout.WEST);
bGroup.add(choice[i]);
pancontrols.add(choice[i], BorderLayout.WEST);
}
choice[4].setVisible(true);
panEast.add("West", panlabels);
panEast.add("West", pancontrols);
pa.add("Center", panEast);
pa.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Select your answer"));
//getContentPane().add(label);
//to be deleted pa.add("South", pan);
pa.setBackground(Color.pink);
jtfMainFrame.add(pa);
jtfMainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
Online r = new Online();
r.createWindow();
}
}
First, your naming convention for the choice labels is off. qLabel="questions", aLabel="questions", bLabel="a", cLabel="b", etc. I would suggest you fix that to eliminate confusion and make your code more readable (ie only have one label that is a question).
Second, your use of panEast.add("West",panlabels); and the other two statements is generally not suggested. Read up on BorderLayout to find the more accepted method of doing this:
http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
As for your problem, I have rewritten your code so things do line up, I will try to point out what I commented out to help:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//import java.util.Arrays;
public class Online extends JFrame {
static JRadioButton[] choice = new JRadioButton[6];
JFrame jtfMainFrame, jtfMainFrame1;
public void createWindow() {
jtfMainFrame = new JFrame("Online Examination");
jtfMainFrame.setSize(800, 500);
jtfMainFrame.setLocation(200, 150);
jtfMainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel pa = new JPanel();
//JPanel panlabels = new JPanel(new GridLayout(0, 1, 0, 60));
JPanel pancontrols = new JPanel(new GridLayout(0, 2, 0, 60));
JPanel panEast = new JPanel();
JPanel pan = new JPanel(new BorderLayout());
JLabel qLabel = new JLabel("Question.");
qLabel.setOpaque(true);
qLabel.setForeground(Color.blue);
qLabel.setBackground(Color.lightGray);
JLabel aLabel = new JLabel("Question.");
aLabel.setOpaque(true);
aLabel.setForeground(Color.blue);
aLabel.setBackground(Color.lightGray);
JLabel bLabel = new JLabel("a.");
bLabel.setOpaque(true);
bLabel.setForeground(Color.blue);
bLabel.setBackground(Color.lightGray);
JLabel cLabel = new JLabel("b.");
cLabel.setOpaque(true);
cLabel.setForeground(Color.blue);
cLabel.setBackground(Color.lightGray);
JLabel dLabel = new JLabel("c.");
dLabel.setOpaque(true);
dLabel.setForeground(Color.blue);
dLabel.setBackground(Color.lightGray);
JLabel eLabel = new JLabel("d.");
eLabel.setOpaque(true);
eLabel.setForeground(Color.blue);
eLabel.setBackground(Color.lightGray);
//panlabels.add(fLabel, BorderLayout.WEST);
//fLabel.setVisible(false);
JLabel ques = new JLabel("q");
ques.setBackground(Color.red);
choice[1] = new JRadioButton("a");
choice[1].setBackground(Color.red);
choice[2] = new JRadioButton("b");
choice[2].setBackground(Color.red);
choice[3] = new JRadioButton("c");
choice[3].setBackground(Color.red);
choice[4] = new JRadioButton("d");
choice[4].setBackground(Color.red);
ButtonGroup bGroup = new ButtonGroup();
//pancontrols.add(new JLabel(""));
pancontrols.add(ques, BorderLayout.WEST);
for (int i = 1; i < 5; i++) {
// pancontrols.add(aLabel,BorderLayout.WEST);
bGroup.add(choice[i]);
}
pancontrols.add(qLabel);
pancontrols.add(ques);
pancontrols.add(bLabel);
pancontrols.add(choice[1]);
pancontrols.add(cLabel);
pancontrols.add(choice[2]);
pancontrols.add(dLabel);
pancontrols.add(choice[3]);
pancontrols.add(eLabel);
pancontrols.add(choice[4]);
pancontrols.setSize(400,200);
choice[4].setVisible(true);
pa.add(pancontrols);
pa.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Select your answer"));
//getContentPane().add(label);
//to be deleted pa.add("South", pan);
pa.setBackground(Color.pink);
jtfMainFrame.add(pa);
jtfMainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
jtfMainFrame.setVisible(true);
}
public static void main(String[] args) {
Online r = new Online();
r.createWindow();
}
}
Basically, I removed your unnecessary panels. the only panel you add stuff to now is the pancontrols panel. I changed it to new JPanel(new Gridlayout(0,2,0,60)). With the two column GridLayout you will always have things line up bound wise, due to GridLayout making everything the same size.
Lastly I pulled the adding of choices[] from the loop and did that along with the labels to make sure things line up. I removed all the panels being added except the pancontrols being added to pa, which I assume you want to add more question panels to pa in that case. That covers your question in particular, but there is quite a lot of stuff you should do (ie use choice[0] for example, eliminate unused labels and panels, etc.)

Categories

Resources