import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Games {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public Games() {
prepareGUI();
}
public static void main(String[] args) {
Games games = new Games();
games.showTextFieldDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("The Game Database");
mainFrame.setSize(1100, 800);
mainFrame.setLayout(new GridLayout(6, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new GridBagLayout());
mainFrame.add(controlPanel);
mainFrame.setVisible(true);
}
private void showTextFieldDemo() {
String[] searchBasis = new String[] { "--Select--", "Genre", "Name of the Game", "Release Year" };
JLabel lblGenre = new JLabel("Genre", JLabel.RIGHT);
JLabel lblName = new JLabel("Name", JLabel.CENTER);
JLabel lblReleaseYear = new JLabel("Release Year", JLabel.CENTER);
JLabel lblSearchBasis = new JLabel("Search Basis", JLabel.CENTER);
JButton btnSearch = new JButton("Search");
JComboBox cmbBasis = new JComboBox<>(searchBasis);
final JTextField txtGenre = new JTextField(12);
final JTextField txtName = new JTextField(12);
final JTextField txtReleaseYear = new JTextField(12);
JTextArea txtContentArea = new JTextArea("hello");
txtContentArea.setSize(400, 400);
lblGenre.setEnabled(false);
txtGenre.setEnabled(false);
lblName.setEnabled(false);
txtName.setEnabled(false);
lblReleaseYear.setEnabled(false);
txtReleaseYear.setEnabled(false);
cmbBasis.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (cmbBasis.getSelectedItem().toString().equalsIgnoreCase("Genre")) {
lblGenre.setEnabled(true);
txtGenre.setEnabled(true);
lblName.setEnabled(false);
txtName.setEnabled(false);
lblReleaseYear.setEnabled(false);
txtReleaseYear.setEnabled(false);
} else if (cmbBasis.getSelectedItem().toString().equalsIgnoreCase("Name of the game")) {
lblGenre.setEnabled(false);
txtGenre.setEnabled(false);
lblName.setEnabled(true);
txtName.setEnabled(true);
lblReleaseYear.setEnabled(false);
txtReleaseYear.setEnabled(false);
} else if (cmbBasis.getSelectedItem().toString().equalsIgnoreCase("Release Year")) {
lblGenre.setEnabled(false);
txtGenre.setEnabled(false);
lblName.setEnabled(false);
txtName.setEnabled(false);
lblReleaseYear.setEnabled(true);
txtReleaseYear.setEnabled(true);
} else if (cmbBasis.getSelectedItem().toString().equalsIgnoreCase("--Select--")) {
lblGenre.setEnabled(false);
txtGenre.setEnabled(false);
lblName.setEnabled(false);
txtName.setEnabled(false);
lblReleaseYear.setEnabled(false);
txtReleaseYear.setEnabled(false);
}
}
});
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Genre " + txtGenre.getText();
data += ", Name: " + new String(txtName.getText());
statusLabel.setText(data);
}
});
GridBagConstraints constraint = new GridBagConstraints();
constraint.gridx = 0;
constraint.gridy = 0;
constraint.insets = new Insets(3, 5, 3, 5);
controlPanel.add(lblSearchBasis, constraint);
constraint.gridx++;
controlPanel.add(cmbBasis, constraint);
constraint.gridy++;
constraint.gridx = 0;
constraint.insets = new Insets(3, 5, 3, 5);
controlPanel.add(lblGenre, constraint);
constraint.gridx++;
controlPanel.add(txtGenre, constraint);
constraint.gridx++;
controlPanel.add(lblName, constraint);
constraint.gridx++;
controlPanel.add(txtName, constraint);
constraint.gridx++;
controlPanel.add(lblReleaseYear, constraint);
constraint.gridx++;
controlPanel.add(txtReleaseYear, constraint);
constraint.gridx++;
controlPanel.add(btnSearch, constraint);
constraint.gridy++;
constraint.gridy++;
constraint.gridx = 0;
constraint.insets = new Insets(3, 5, 3, 5);
controlPanel.add(txtContentArea, constraint);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setVisible(true);
}
}
I have the above code, all I need is a custom sized 3 column JTable below these 3 textfields so I can populate my data there. I have tried many ways but didn't get much from that... they all are static in size.. kindly help me out. Thanks.
all I need is a custom sized 3 column JTable
Read the section from the Swing tutorial on Setting and Changing Column Widths for information on this.
Once you have set the column widths you can then use:
table.setPreferredScrollableViewportSize(table.getPreferredSize());
To set the preferred size of the JTable and its scroll pane.
mainFrame.addWindowListener(new WindowAdapter() {
Don't use a WindowListener to close the frame.
Instead you can just set a property of the JFrame when you create the frame:
mainFrame.addWindowListener(new WindowAdapter() {
Related
I've tried looking for an answer to my question, but couldn't find anything similar. If it's already been asked, please link. Thanks in advance.
The layout of the main panel, mainPanel, is GridBagLayout. It has three buttons. Two of them are duds (for the purpose of this question). The middle button, butt2, creates a JPanel with other components in it every time butt2 is pressed.
Because butt2 is in the middle, and butt3 is directly below it, I have an int variable, tracker2, that tracks the gridy of butt2. Every time butt2 is pressed, I create a new JPanel that goes under butt2, increment tracker2, and then remove butt3 and add it below the newer component.
import java.util.List;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Demo implements ActionListener
public static void main(String[] args) {
Demo demo = new Demo();
}
private JFrame frame;
private JPanel mainPanel;
private JButton butt1, butt2, butt3;
private GridBagConstraints gb;
private List<JTextField> list;
private int count, tracker2;
public Demo() {
frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setBounds(0, 0, 800, 800);
list = new ArrayList<JTextField>();
count = 0;
tracker2 = 0;
commence();
}
private void commence() {
gb = new GridBagConstraints();
gb.anchor = GridBagConstraints.FIRST_LINE_START;
gb.weightx = 1;
gb.insets = new Insets(50, 5, 0, 20);
mainPanel = new JPanel();
mainPanel.setBackground(Color.white);
mainPanel.setLayout( new GridBagLayout() );
butt1 = new JButton("One");
butt1.setPreferredSize( new Dimension(100, 50) );
// Add to panel
gb.gridx = 0;
gb.gridy = 0;
mainPanel.add( butt1, gb);
butt2 = new JButton("Two");
butt2.setPreferredSize( new Dimension(100, 50) );
butt2.addActionListener(this);
// Add to panel
gb.gridy++;
tracker2 = gb.gridy;
mainPanel.add( butt2, gb );
butt3 = new JButton("Three");
butt3.setPreferredSize( new Dimension(100, 50) );
// Add to panel
gb.gridy++;
mainPanel.add( butt3, gb );
frame.add(mainPanel);
frame.setVisible(true);
frame.repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals( butt2 )) {
commence2();
}
}
private void commence2() {
gb.insets = new Insets( 0, 0, 0, 0 );
list.add( new JTextField(30) );
JLabel label = new JLabel("LABEL 2 ");
label.setDisplayedMnemonic( KeyEvent.VK_N );
label.setLabelFor( list.get(count) );
JPanel panel = new JPanel( new FlowLayout(FlowLayout.LEFT, 10, 3));
panel.setBackground( Color.white );
panel.add(label);
panel.add(list.get( count ));
// Add to mainPanel
tracker2++;
gb.gridy = tracker2;
mainPanel.add( panel, gb );
updateFrame();
// Increment count
count++;
frame.revalidate();
frame.repaint();
}
private void updateFrame() {
mainPanel.remove( butt3 );
gb.insets = new Insets(50, 5, 0, 20);
gb.gridy = tracker2 + 1;
mainPanel.add( butt3, gb );
}
}
Is there an easier way to do this or a Layout that automatically does this for me?
Yes, there is an easier way. Instead of adding the new text fields to your mainPanel use an additional Container. E.g.
public class Demo2 implements ActionListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Demo2();
}
});
}
private JFrame frame;
private JPanel textPanel;
private JButton butt1, butt2, butt3;
public Demo2() {
frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.setBounds(0, 0, 800, 800);
commence();
}
private void commence() {
GridBagConstraints gb = new GridBagConstraints();
gb.anchor = GridBagConstraints.FIRST_LINE_START;
gb.weightx = 1;
gb.insets = new Insets(50, 5, 0, 20);
JPanel mainPanel = new JPanel();
mainPanel.setBackground(Color.white);
mainPanel.setLayout( new GridBagLayout() );
butt1 = new JButton("One");
butt1.setPreferredSize( new Dimension(100, 50) );
// Add to panel
gb.gridx = 0;
gb.gridy = 0;
mainPanel.add( butt1, gb);
butt2 = new JButton("Two");
butt2.setPreferredSize( new Dimension(100, 50) );
butt2.addActionListener(this);
// Add to panel
gb.gridy++;
gb.insets = new Insets(50, 5, 0, 0);
mainPanel.add( butt2, gb );
textPanel = new JPanel(new GridLayout(0, 1));
// Add to panel
gb.gridy++;
gb.insets = new Insets(0, 5, 0, 20);
mainPanel.add( textPanel, gb );
butt3 = new JButton("Three");
butt3.setPreferredSize( new Dimension(100, 50) );
// Add to panel
gb.gridy++;
gb.insets = new Insets(50, 5, 0, 20);
mainPanel.add( butt3, gb );
frame.add(mainPanel);
frame.setVisible(true);
frame.repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals( butt2 )) {
commence2();
}
}
private void commence2() {
JTextField jtf = new JTextField(30);
JLabel label = new JLabel("LABEL 2 ");
label.setDisplayedMnemonic(KeyEvent.VK_N );
label.setLabelFor( jtf );
JPanel panel = new JPanel( new FlowLayout(FlowLayout.LEFT, 10, 3));
panel.setBackground( Color.white );
panel.add(label);
panel.add( jtf );
// Add to mainPanel
textPanel.add( panel );
textPanel.revalidate();
frame.revalidate();
frame.repaint();
}
}
In the above code, textPanel serves as container for the new text fields.
I had created this view by using null layout:
This is the Code i had used to create above layout
public class Page1311 extends JPanel {
// private JTable table;
// public JScrollPane pane=null;
public JPanel panel=null;
public JButton back=null;
/**
* Create the panel.
*/
public Page1311() {
setLayout(null);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
List<List<String>> list=new ArrayList<List<String>>();
for(int j=0;j<=5;j++)
{
List<String> list1=new ArrayList<>();
list1.add("Honda Showroom"+j);
list1.add("Mandsaur");
list1.add("25 Chakrawati Colony Railway Station Road");
list1.add("Activa");
list1.add("2017");
list1.add("Honda");
list.add(list1);
}
getLayout(list,this);
back = new JButton("back");
back.setFont(new Font("Arial", Font.PLAIN, 20));
back.setBounds(10,10, 150, 27);
add(back);
}
public static void getLayout(List<List<String>> list,JPanel pane)
{
int i=0;
int x=100;
int y=100;
int height=20;
int width=200;
int size=list.size();
JLabel[] lblSName=new JLabel[size];
JLabel[] lblSAddress=new JLabel[size];
JLabel[] lblSCity=new JLabel[size];
JLabel[] lblVName=new JLabel[size];
JLabel[] lblVVersion=new JLabel[size];
JLabel[] lblVCompanies=new JLabel[size];
JButton[] lblGo=new JButton[size];
Iterator<List<String>> it=list.iterator();
while(it.hasNext())
{
System.out.println(x+" "+y+" "+width+" "+height+" "+i);
Iterator iit=it.next().iterator();
lblSName[i]= new JLabel();
lblSName[i].setText("Name:"+iit.next());
lblSName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
lblSName[i].setBounds(x,y,width,height);
pane.add(lblSName[i]);
lblSCity[i] = new JLabel();
lblSCity[i].setText("City:"+iit.next());
lblSCity[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+" "+width+" "+height+" "+i);
lblSCity[i].setBounds(x+240,y,width,height);
pane.add(lblSCity[i]);
lblSAddress[i]= new JLabel();
lblSAddress[i].setText("Address:"+iit.next());
lblSAddress[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+y+" "+(width+256)+" "+height+" "+i);
lblSAddress[i].setBounds(x+470,y, width+256, height);
pane.add(lblSAddress[i]);
lblVName[i]= new JLabel();
lblVName[i].setText("Vehicle Name:"+iit.next());
lblVName[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println(x+" "+(y+35)+" "+width+" "+height+" "+i);
lblVName[i].setBounds(x,y+35,width, height);
pane.add(lblVName[i]);
lblVVersion[i] = new JLabel();
lblVVersion[i].setText("Vehicle Version:"+iit.next());
lblVVersion[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+240)+" "+y+35+" "+width+" "+height+" "+i);
lblVVersion[i].setBounds(x+240,y+35, width, height);
pane.add(lblVVersion[i]);
lblVCompanies[i]= new JLabel();
lblVCompanies[i].setText("Vehicle Companies:"+iit.next());
lblVCompanies[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 20));
System.out.println((x+470)+" "+(y+35)+" "+(width+256)+" "+height+" "+i);
lblVCompanies[i].setBounds(x+470,y+35, width+256,height);
pane.add(lblVCompanies[i]);
lblGo[i]= new JButton("Go ");
lblGo[i].setFont(new Font("Monotype Corsiva", Font.ITALIC, 15));
System.out.println(x+" "+(y+70)+" "+(width-130)+" "+height+" "+i);
lblGo[i].setBounds(x,y+70,width-130, height);
pane.add(lblGo[i]);
i++;
y=y+160;
System.out.println("new height"+y);
}
}
public static void main(String[] args) {
JFrame frame=new JFrame();
frame.add(new Page1311());
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.setLocation(0, 0);
frame.setVisible(true);
}
}
But now i found that i cant use jscrollpane with null layout manager.So i want to create same layout by using any other layout manager.Can any one please help with with this or you can provide me any other way to use jscrollpane with null layout manager.
Thanks in advance
I'd use a combination of a GridBagLayout for each 'show room' panel, then a single column GridLayout panel to stack the collection of show room panels in a single container. The second panel would go in the scroll pane.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class ShowRoomLayout {
private JComponent ui = null;
ShowRoomLayout() {
initUI();
}
private JPanel getShowRoomPanel(int num) {
JPanel p = new JPanel(new GridBagLayout());
p.setBorder(new TitledBorder("GridBagLayout"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
p.add(new JLabel("Name:Honda Showroom" + num), gbc);
gbc.gridx = 1;
p.add(new JLabel("City:Mandsaur"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Address:25 Chakrawati Colony Railway Station Road"), gbc);
gbc.gridy = 1;
gbc.gridx = 0;
p.add(new JLabel("Vehicle Name:Activa"), gbc);
gbc.gridx = 1;
p.add(new JLabel("Vehicle Version:2017"), gbc);
gbc.gridx = 2;
p.add(new JLabel("Vehicle Companies:Honda"), gbc);
gbc.gridy = 2;
gbc.gridx = 0;
p.add(new JButton("Go"), gbc);
return p;
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel pList = new JPanel(new GridLayout(0, 1, 3, 3));
pList.setBorder(new TitledBorder("GridLayout"));
for (int ii = 1; ii < 21; ii++) {
pList.add(getShowRoomPanel(ii));
}
JScrollPane scrollPane = new JScrollPane(pList,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ui.add(scrollPane);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ShowRoomLayout o = new ShowRoomLayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
Dimension d = f.getSize();
f.setSize(new Dimension(d.width, 400));
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
JScrollPane has its own layout: ScrollPaneLayout. If you want to use any other, you don't set it on the scroll pane itself, you put a JPanel inside it and set the layout on that panel.
Another way without the need to set any layout manager for the JScrollPane is the method
JScrollPane.setViewportView(Component);
This is my preferred way. No size or layout handling on the fly.
If you want to place several Components to the same JScrollPane, just put a JPanel in between. The JPanel can have your preferred Layout.
If your layout uses a null layout manager, you need to tell the scroll pane the size of your component
JPanel pane = new JPanel(){
Dimension d = new Dimension(400, 400);
#Override
public Dimension getMinimumSize(){
return d;
}
#Override
public Dimension getPreferredSize(){
return d;
}
#Override
public Dimension getMaximumSize(){
return d;
}
#Override
public void paintComponent(Graphics g){
g.setColor(Color.RED);
g.fill3DRect(25, 25, 350, 350, true);
}
};
pane.setLayout(null);
JFrame frame = new JFrame("check");
frame.setSize(200, 200);
frame.add(new JScrollPane(pane));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
For this, I set the size of the pane to be 400, 400. The scroll pane will respect this. If you comment out the overriden methods, you'll see the scroll doesn't work anymore.
For OP to apply this technique they would just have to change the line where they add the panel to the JFrame.
frame.add(new JScrollPane(new Page1311()));
Since Page1311 doesn't use a layout manager then they need to override, getMin/Max/Preferred. as I did in my example. That would wrap the custom JPanel with a scroll pane, and the content would be scrollable.
I am using JCombobox and just below that there is a panel which contains JTextFields. Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself. I don't know what to do. I am unable to post a pic of the problem here because i am a new user and my reputation is below 10.
public class MainClass {
public static void main(String args[]){
Form form = new Form();
int width = 400;
int height = 400;
form.setSize(width, height);
form.setVisible(true);
form.setTitle("Create Network");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
form.setLocation((screenSize.width-width)/2, (screenSize.height-height)/2);
}
}
This is the form class
public class Form extends JFrame {
private JLabel ipAddress, networkTopo, numNodes;
private JTextField nodes;
private JButton addIp;
private JButton removeIp;
private JButton next, back;
private JPanel jPanel, jPanel1, jPanel2, commonPanel;
private JComboBox<String> dropDown;
private String[] topologies = { "Grid", "Diagnol Grid", "Bus", "Ring",
"Star" };
public Form() {
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
setResizable(false);
this.getContentPane().setBackground(Color.WHITE);
// add(Box.createRigidArea(new Dimension(0,10)));
GridLayout commonPanelLayout = new GridLayout(0, 2);
commonPanelLayout.setVgap(10);
commonPanel = new JPanel(commonPanelLayout);
commonPanel.setVisible(true);
commonPanel.setAlignmentX(commonPanel.LEFT_ALIGNMENT);
commonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
commonPanel.setBackground(Color.white);
numNodes = new JLabel("Number of Nodes");
commonPanel.add(numNodes);
nodes = new JTextField(20);
commonPanel.add(nodes);
networkTopo = new JLabel("Network Topology");
commonPanel.add(networkTopo);
dropDown = new JComboBox<String>(topologies);
dropDown.setBackground(Color.WHITE);
commonPanel.add(dropDown);
add(commonPanel);
add(Box.createRigidArea(new Dimension(0, 10)));
ipAddress = new JLabel("IP Addresses");
ipAddress.setAlignmentX(ipAddress.LEFT_ALIGNMENT);
ipAddress.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
add(ipAddress);
add(Box.createRigidArea(new Dimension(0, 10)));
jPanel = new JPanel(new FlowLayout());
jPanel.setVisible(true);
jPanel.setAlignmentX(jPanel.LEFT_ALIGNMENT);
jPanel.setBackground(Color.WHITE);
// jPanel1.setAutoscrolls(true);
add(jPanel);
GridLayout layout = new GridLayout(0, 1);
jPanel1 = new JPanel();
layout.setVgap(10);
// jPanel1.setBackground(Color.WHITE);
jPanel1.setVisible(true);
JScrollPane scroll = new JScrollPane();
scroll.setViewportView(jPanel1);
scroll.setAutoscrolls(true);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setPreferredSize(new Dimension(300, 150));
jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width,
Integer.MAX_VALUE));
jPanel.add(scroll);
jPanel2 = new JPanel(new GridLayout(0, 1, 10, 10));
jPanel2.setBackground(Color.WHITE);
jPanel2.setVisible(true);
jPanel.add(jPanel2);
addIp = new JButton("Add");
jPanel2.add(addIp);
removeIp = new JButton("Remove");
jPanel2.add(removeIp);
JPanel savePanel = new JPanel(new FlowLayout());
savePanel.setVisible(true);
savePanel.setAlignmentX(savePanel.LEFT_ALIGNMENT);
savePanel.setBackground(Color.white);
back = new JButton("Back");
back.setAlignmentX(next.LEFT_ALIGNMENT);
back.setEnabled(false);
savePanel.add(back);
next = new JButton("Next");
next.setAlignmentX(next.LEFT_ALIGNMENT);
savePanel.add(next);
add(savePanel);
AddIPEvent addIPEvent = new AddIPEvent();
addIp.addActionListener(addIPEvent);
RemoveIPEvent removeIPEvent = new RemoveIPEvent();
removeIp.addActionListener(removeIPEvent);
}
public class AddIPEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel subPanel = new JPanel(new FlowLayout());
// subPanel.setBackground(Color.WHITE);
subPanel.setVisible(true);
JCheckBox jCheckBox = new JCheckBox();
// jCheckBox.setBackground(Color.WHITE);
subPanel.add(jCheckBox);
JTextField ip = new JTextField(12);
subPanel.add(ip);
JTextField nodesInIp = new JTextField(6);
nodesInIp.setVisible(false);
subPanel.add(nodesInIp);
jPanel1.add(subPanel);
jPanel1.repaint();
jPanel1.revalidate();
}
}
public class RemoveIPEvent implements ActionListener {
public void removeIP(Container container) {
for (Component c : container.getComponents()) {
if (c instanceof JCheckBox) {
if (((JCheckBox) c).isSelected()) {
jPanel1.remove(container);
jPanel.revalidate();
jPanel1.repaint();
}
} else if (c instanceof Container) {
removeIP((Container) c);
}
}
}
public void actionPerformed(ActionEvent e) {
removeIP(jPanel1);
}
}
}
After Clicking on the Add button and then clicking on the JComboBox will make portion of JTextField dissapear. Could someone pls point out the mistake?
Whenever i click on the dropdown (JCombobox) some portion of JTextField disappears itself.
//jPanel1.setPreferredSize(new Dimension(scroll.getPreferredSize().width, Integer.MAX_VALUE));
Don't set the preferred size of components. The layout manager will determine the preferred size as components are added/removed. Then scrollbars will appear as required.
jPanel1.repaint();
jPanel1.revalidate();
The order should be:
jPanel1.revalidate();
jPanel1.repaint();
The revalidate() first invokes the layout manager before it is repainted.
//form.setSize(width, height);
form.pack();
Again, don't try to set the size. Let the layout managers do their jobs. The pack() will size the frame based on the sizes of the components added to the frame.
The first column in my grid always comes out right but then the rest begin replacing the other cells. Also the border layout does not seem to be functioning. I do not know what the problem is. It should have the title on top, a 7x3 grid in the center and the buttons on the bottom. Please help! Thank you!
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GUI extends JFrame{
private JPanel mainPanel,titlePanel, fieldPanel, buttonPanel;
private JLabel title, teams, totalP, wlt;
private JTextField team1, team2, team3, team4, team5, team6, total1, total2, total3, total4, total5, total6, wlt1, wlt2, wlt3, wlt4, wlt5, wlt6;
private JButton read, calc, champWin, earthCW, exit;
final private int WINDOW_HEIGHT = 400;
final private int WINDOW_WIDTH = 900;
public GUI(){
buildtitlePanel();
buildfieldPanel();
buildbuttonPanel();
buildmainPanel();
setTitle("Desert Soccer League");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buildmainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void buildtitlePanel() {
titlePanel = new JPanel();
title = new JLabel();
title.setText("2014 Desert Soccer League Totals");
titlePanel.add(title);
}
private void buildfieldPanel() {
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(7, 3));
teams = new JLabel();
teams.setText("Teams");
totalP = new JLabel();
totalP.setText("Total Points");
wlt = new JLabel();
wlt.setText("Win-Loss-Tie");
team1 = new JTextField(10);
team2 = new JTextField(10);
team3 = new JTextField(10);
team4 = new JTextField(10);
team5 = new JTextField(10);
team6 = new JTextField(10);
total1 = new JTextField(10);
total2 = new JTextField(10);
total3 = new JTextField(10);
total4 = new JTextField(10);
total5 = new JTextField(10);
total6 = new JTextField(10);
wlt1 = new JTextField(10);
wlt2 = new JTextField(10);
wlt3 = new JTextField(10);
wlt4 = new JTextField(10);
wlt5 = new JTextField(10);
wlt6 = new JTextField(10);
team1.setEditable(false);
team2.setEditable(false);
team3.setEditable(false);
team4.setEditable(false);
team5.setEditable(false);
team6.setEditable(false);
total1.setEditable(false);
total2.setEditable(false);
total3.setEditable(false);
total4.setEditable(false);
total5.setEditable(false);
total6.setEditable(false);
wlt1.setEditable(false);
wlt2.setEditable(false);
wlt3.setEditable(false);
wlt4.setEditable(false);
wlt5.setEditable(false);
wlt6.setEditable(false);
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
fieldPanel.add(totalP);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
fieldPanel.add(wlt);
fieldPanel.add(wlt1);
fieldPanel.add(wlt2);
fieldPanel.add(wlt3);
fieldPanel.add(wlt4);
fieldPanel.add(wlt5);
fieldPanel.add(wlt6);
}
private void buildbuttonPanel() {
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 5));
read = new JButton();
calc = new JButton();
champWin = new JButton();
earthCW = new JButton();
exit = new JButton();
read.setText("Read Input File");
read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
calc.setText("Calculate Points");
calc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
champWin.setText("Championship Winner");
champWin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
earthCW.setText("Earth Cup Winner");
earthCW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exit.setText("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
buttonPanel.add(read);
buttonPanel.add(calc);
buttonPanel.add(champWin);
buttonPanel.add(earthCW);
buttonPanel.add(exit);
}
}
mainPanel = new JPanel();
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
By default a JPanel uses a FlowLayout. If you want to use a BorderLayout, then you need to set the layout on the panel:
mainPanel = new JPanel( new BorderLayout() );
The GridLayout fills out the rows first so the code should be:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
...
Also note that in your code you are adding the total? fields twice (which won't do anything), instead of the team? fields.
Another way to specify the grid is to just use:
fieldPanel.setLayout(new GridLayout(0, 3));
This tells the grid to add 3 components to each row then move on to the next row. This way you don't have to worry about the exact number of rows.
To add to camickr answer you're also adding the same total fields multiple times, so change this:
fieldPanel.add(teams);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
to
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
This is what is causing your display issue.
Your code should look like:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
fieldPanel.add(team2);
fieldPanel.add(total2);
fieldPanel.add(wlt2);
// etc.
I've been working at this problem for hours now, with no results. I cannot seem to get the applet to display properly when viewing the HTML page OR when running the applet through Eclipse. It is always blank. I've been searching for a long time now and decided just to ask.
Here's the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet{
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public JPanel createContentPane(){
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
//posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
topicGUI.add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150,25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
postPanel.add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70,15);
username.setHorizontalAlignment(0);
postPanel.add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40,15);
topic.setHorizontalAlignment(0);
postPanel.add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70,15);
paragraph.setHorizontalAlignment(0);
postPanel.add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
postPanel.add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
postPanel.add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane (paragraphArea);
scrollParagraph.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
postPanel.add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal + "/n" + paragraphArea + "/n";
}
});
postPanel.add(submitButton);
setVisible(true);
return topicGUI;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("");
Topics display = new Topics();
frame.setContentPane(display.createContentPane());
frame.setSize(500, 270);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
In order to run as an applet, you need to override the init method. You don't need a main method. Just add all you components inside the init method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet {
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public void init() {
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
// posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150, 25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70, 15);
username.setHorizontalAlignment(0);
add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40, 15);
topic.setHorizontalAlignment(0);
add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70, 15);
paragraph.setHorizontalAlignment(0);
add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane(paragraphArea);
scrollParagraph
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal
+ "/n" + paragraphArea + "/n";
}
});
add(submitButton);
}
}