I don't know why my scroll bar in text area doesn't work. I found many solutions in internet, but no 1 helped for me.
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
I found that can't be Panel's layout Absolute, if I change It to Group layout the same.
What's wrong? Could you help me? Thank you.
UPDATED:
package lt.kvk.i3_2.kalasnikovas_stanislovas;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JTextPane;
import javax.swing.DropMode;
import javax.swing.JFormattedTextField;
import java.awt.Component;
import javax.swing.Box;
import java.awt.Dimension;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JMenuItem;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import java.awt.SystemColor;
import java.awt.Font;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.JScrollBar;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JToolBar;
public class KDVizualizuotas {
private JFrame frmInformacijaApieMuzikos;
private JTextField txtStilius;
private JTextArea textArea1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KDVizualizuotas window = new KDVizualizuotas();
window.frmInformacijaApieMuzikos.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public KDVizualizuotas() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmInformacijaApieMuzikos = new JFrame();
frmInformacijaApieMuzikos.setResizable(false);
frmInformacijaApieMuzikos.setIconImage(Toolkit.getDefaultToolkit().getImage(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/Sidebar-Music-Blue-icon.png")));
frmInformacijaApieMuzikos.setTitle("Muzikos stiliai");
frmInformacijaApieMuzikos.setBounds(100, 100, 262, 368);
frmInformacijaApieMuzikos.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtStilius = new JTextField();
txtStilius.setBounds(10, 34, 128, 20);
txtStilius.setColumns(10);
JButton btnIekoti = new JButton("Ie\u0161koti");
btnIekoti.setBounds(146, 36, 89, 19);
btnIekoti.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// textArea1.append(txtStilius.getText()+"\n");
// txtStilius.getText();
Scanner input = new Scanner(System.in);
try {
FileReader fr = new FileReader("src/lt/kvk/i3_2/kalasnikovas_stanislovas/Stiliai.txt");
BufferedReader br = new BufferedReader(fr);
String stiliuSarasas;
while((stiliuSarasas = br.readLine()) != null) {
System.out.println(stiliuSarasas);
textArea1.append(stiliuSarasas+"\n");
}
fr.close();
}
catch (IOException e) {
System.out.println("Error:" + e.toString());
}
}
});
JPanel panel = new JPanel();
panel.setBounds(10, 65, 224, 243);
panel.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
panel.setBackground(SystemColor.text);
JLabel lblveskiteMuzikosStili = new JLabel("\u012Eveskite muzikos stili\u0173:");
lblveskiteMuzikosStili.setBounds(10, 14, 222, 14);
frmInformacijaApieMuzikos.getContentPane().setLayout(null);
panel.setLayout(null);
frmInformacijaApieMuzikos.getContentPane().add(panel);
JLabel lblInformacijaApieMuzikos = new JLabel("Informacija apie muzikos stili\u0173:");
lblInformacijaApieMuzikos.setBounds(12, 3, 190, 14);
panel.add(lblInformacijaApieMuzikos);
textArea1 = new JTextArea();
textArea1.setBounds(13, 28, 182, 199);
panel.add(textArea1);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(205, 1, 17, 242);
panel.add(scrollBar);
frmInformacijaApieMuzikos.getContentPane().add(txtStilius);
frmInformacijaApieMuzikos.getContentPane().add(btnIekoti);
frmInformacijaApieMuzikos.getContentPane().add(lblveskiteMuzikosStili);
JMenuBar menuBar = new JMenuBar();
frmInformacijaApieMuzikos.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
mntmExit.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/exitas.png")));
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmHelp = new JMenuItem("Help");
mnHelp.add(mntmHelp);
JMenu mnAbout = new JMenu("About");
menuBar.add(mnAbout);
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.setIcon(new ImageIcon(KDVizualizuotas.class.getResource("/lt/kvk/i3_2/kalasnikovas_stanislovas/resources/questionmark.png")));
mnAbout.add(mntmAbout);
}
}
You need to add the component you want to be contained within the scroll pane to it.
You can do this via the JScrollPane's constructor or JScrollPane#setViewportView method
public class ScrollPaneTest {
public static void main(String[] args) {
new ScrollPaneTest();
}
public ScrollPaneTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JPanel bigPane = new JPanel();
bigPane.setBackground(Color.BLUE);
// This is not recommended, but is used for demonstration purposes
bigPane.setPreferredSize(new Dimension(1024, 768));
JScrollPane scrollPane = new JScrollPane(bigPane);
scrollPane.setPreferredSize(new Dimension(400, 400));
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Updated with proper layout
You should avoid null or absolute layouts, they will only hurt you in the long wrong.
You may also find How to use Scroll Panes of use
public class BadLayout {
public static void main(String[] args) {
new BadLayout();
}
public BadLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField searchField;
private JButton searchButton;
private JTextArea searchResults;
public TestPane() {
setLayout(new BorderLayout());
searchResults = new JTextArea();
searchResults.setLineWrap(true);
searchResults.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(searchResults);
JPanel results = new JPanel(new BorderLayout());
results.setBorder(new EmptyBorder(4, 8, 8, 8));
results.add(scrollPane);
add(results);
JPanel search = new JPanel(new GridBagLayout());
search.setBorder(new EmptyBorder(8, 8, 4, 8));
searchField = new JTextField(12);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.insets = new Insets(0, 0, 0, 4);
search.add(searchField, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridx++;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
search.add(searchButton, gbc);
add(search, BorderLayout.NORTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 400);
}
}
}
Related
Hello I found a Projekt on yt where you can search for a keyword and it will show all the websites it found on google. And right now I am trying to revive the keyword the user put in the textfield but it isn't working. It does not find the textfield (tf1) I made, but I don't know what I did wrong. Thanks in advance!
here's my code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Main implements ActionListener {
public static void main(String[] args) {
int frameWidth = 600;
int frameHeight = 600;
JFrame f = new JFrame();
JLabel l1 = new JLabel();
JTextField tf1 = new JTextField();
JButton b1 = new JButton();
f.getContentPane().setBackground(Color.PINK);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setSize(frameWidth, frameHeight);
f.setTitle("Search");
f.setLocationRelativeTo(null);
f.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
f.add(l1);
f.add(tf1);
f.add(b1);
l1.setText("Enter Keywords");
tf1.setPreferredSize(new Dimension(200, 20));
tf1.revalidate();
b1.setText("Search");
b1.addActionListener(new Main());
f.setVisible(true);
// ArrayList<WebCrawler> bots = new ArrayList<>();
// bots.add(new WebCrawler("", 1));
// bots.add(new WebCrawler("", 2));
// bots.add(new WebCrawler("", 3));
// for(WebCrawler w : bots) {
// try {
// w.getThread().join();
//
// }catch(InterruptedException e) {
// e.printStackTrace();
// }
// }
}
#Override
public void actionPerformed(ActionEvent e) {
String keyword = tf1.getText(); //Here it does not find the tf I made
System.out.println(keyword); //just for confirmation
}
}
You have a reference issue.
tf1 is declared as a local variable within main, which makes it inaccessible to any other method/context. Add into the fact that main is static and you run into another problem area.
The simple solution would be to make tf1 a instance field. This would be further simplified if you grouped your UI logic into a class, for example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
private JTextField textField;
private JButton searchButton;
public TestPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(Color.PINK);
setLayout(new GridBagLayout());
label = new JLabel("Enter Keywords: ");
textField = new JTextField(20);
searchButton = new JButton("Search");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(8, 8, 8, 8);
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridx++;
add(textField, gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(searchButton, gbc);
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
JOptionPane.showMessageDialog(TestPane.this, "You want to search for: " + text);
}
};
textField.addActionListener(listener);
searchButton.addActionListener(listener);
}
}
}
This is basic Java 101. You might find something like What is the difference between a local variable, an instance field, an input parameter, and a class field? of help
I'm trying to code an app using JFrame. But I have encountered an issue when trying to check if the window is full screen or not. I want my button to be in the same position when it's full and half screen. Here's my code.
package App.Gui;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import App.Gui.Event.ExitEvent;
public class WindowSettings {
private final static ImageIcon imageIcon = new ImageIcon("C:\\Users\\zeesh\\FirstApp\\src\\image\\Untitled.png");
public static void setWindow() {
JFrame frame = new JFrame("Debug Configurations");
JPanel panel = new JPanel();
frame.getContentPane();
JButton button = new JButton("X");
Dimension size = button.getPreferredSize();
button.setBounds(1125, 20, 50, 50);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ExitEvent.exit();
}
});
panel.setLayout(null);
panel.add(button);
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel);
frame.setIconImage(imageIcon.getImage());
frame.setSize(1200, 750);
frame.setVisible(true);
}
}
Make use of appropriate layouts, for example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
JButton button = new SquareButton("X");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
JPanel topPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
topPane.add(button, gbc);
add(topPane, BorderLayout.NORTH);
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.add(new JLabel("Stuff goes here"));
add(contentPane);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
}
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int stringWidth = fm.stringWidth(getText());
int stringHeight = fm.getHeight();
int size = Math.max(stringHeight, stringWidth);
return new Dimension(size + 22, size + 22);
}
}
}
See Laying Out Components Within a Container for more details
But, wait, you want to overlap the button over the top of the content? Well, that's not that hard...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton button = new SquareButton("X");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello");
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.insets = new Insets(20, 50, 20, 50);
add(button, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JPanel contentPane = new JPanel(new GridBagLayout());
contentPane.setBackground(Color.MAGENTA);
contentPane.add(new JLabel("Stuff goes here"));
add(contentPane, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1200, 750);
}
}
class SquareButton extends JButton {
SquareButton(String s) {
super(s);
}
#Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int stringWidth = fm.stringWidth(getText());
int stringHeight = fm.getHeight();
int size = Math.max(stringHeight, stringWidth);
return new Dimension(size + 22, size + 22);
}
}
}
I have this code that creates a Jframe where I add a JLabel with a picture and a JpasswordField. I want the JpasswordField to be on top of the image but only depending on where I do the f.add I get one of them showed or not... I want the JpasswordField to be on top of the picture to allow the user to introduce a password but with the picture as background.
Here is the code:
package java;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
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;
import javax.swing.JPasswordField;
public class Java implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new Java());
}
#Override
public void run() {
JFrame f = new JFrame();
/*Keep on front*/
f.toFront();
f.repaint();
f.setAlwaysOnTop(true);
f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setUndecorated(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
f.setBounds(0,0,screenSize.width-5, screenSize.height-100);
double width = screenSize.getWidth();
double height = screenSize.getHeight();
System.out.println(width+" "+height);
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("C:\\image.jpg"));
} catch (IOException e1) {
e1.printStackTrace();
}
Image dimg = myPicture.getScaledInstance((int)width, (int)height,Image.SCALE_SMOOTH);
JLabel picLabel = new JLabel(new ImageIcon(dimg));
JPasswordField myTextfield = new JPasswordField("Password");
myTextfield.setEchoChar('*'); // U+26AB
picLabel.setPreferredSize(screenSize);
picLabel.setVerticalAlignment(JLabel.BOTTOM);
/*Depending of who I add first the image or the JPasswordField is showed*/
f.add(myTextfield);
f.add(picLabel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
First off, your code should be geared towards creating JPanels, and you should control the layout manager of this JPanel directly. Then you can place and display your JPanel in a JDialog not a JFrame, since much of your code appears to be trying to emulate a dialog's actions (such as keeping it on top and such).
That being sad, one of your big problems is that you're ignoring the layout manager that the JFrame's contentPane is using, the BorderLayout. By adding components to it in a default fashion, you will cover up anything that was added to the same position previously. Instead I suggest:
Create a JPanel
Draw your image as a background image in the JPanel's paintComponent methd.
Add your JLabel to your JPanel.
Display the JPanel in a JDialog not a JFrame.
For example:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class DialogExample extends JPanel {
private static final int COLUMN_COUNT = 10;
private static final int I_GAP = 3;
public static final String BKG_IMG_PATH = "http://upload.wikimedia.org/wikipedia/commons/"
+ "thumb/9/92/Camels_in_Jordan_valley_%284568207363%29.jpg/800px-Camels_in_Jordan_valley_"
+ "%284568207363%29.jpg";
private BufferedImage backgrndImage;
private JTextField userNameField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
private JPanel mainPanel = new JPanel(new GridBagLayout());
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public DialogExample(BufferedImage backgrndImage) {
this.backgrndImage = backgrndImage;
userNameField.setColumns(COLUMN_COUNT);
passwordField.setColumns(COLUMN_COUNT);
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
btnPanel.setOpaque(false);
btnPanel.add(okButton);
btnPanel.add(cancelButton);
GridBagConstraints gbc = getGbc(0, 0, GridBagConstraints.BOTH);
mainPanel.add(createLabel("User Name", Color.white), gbc);
gbc = getGbc(1, 0, GridBagConstraints.HORIZONTAL);
mainPanel.add(userNameField, gbc);
gbc = getGbc(0, 1, GridBagConstraints.BOTH);
mainPanel.add(createLabel("Password:", Color.white), gbc);
gbc = getGbc(1, 1, GridBagConstraints.HORIZONTAL);
mainPanel.add(passwordField, gbc);
gbc = getGbc(0, 2, GridBagConstraints.BOTH, 2, 1);
mainPanel.add(btnPanel, gbc);
mainPanel.setOpaque(false);
add(mainPanel);
}
private JLabel createLabel(String text, Color color) {
JLabel label = new JLabel(text);
label.setForeground(color);
return label;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgrndImage != null) {
g.drawImage(backgrndImage, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || backgrndImage == null) {
return super.getPreferredSize();
}
int imgW = backgrndImage.getWidth();
int imgH = backgrndImage.getHeight();
return new Dimension(imgW, imgH);
}
public static GridBagConstraints getGbc(int x, int y, int fill) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
gbc.fill = fill;
return gbc;
}
public static GridBagConstraints getGbc(int x, int y, int fill, int width,
int height) {
GridBagConstraints gbc = getGbc(x, y, fill);
gbc.gridwidth = width;
gbc.gridheight = height;
return gbc;
}
private static void createAndShowGui() throws IOException {
final JFrame frame = new JFrame("Frame");
final JDialog dialog = new JDialog(frame, "User Sign-In", ModalityType.APPLICATION_MODAL);
URL imgUrl = new URL(BKG_IMG_PATH);
BufferedImage img = ImageIO.read(imgUrl);
final DialogExample dlgExample = new DialogExample(img);
dialog.add(dlgExample);
dialog.pack();
JPanel mainPanel = new JPanel();
mainPanel.add(new JButton(new AbstractAction("Please Press Me!") {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(true);
}
}));
mainPanel.setPreferredSize(new Dimension(800, 650));
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(new Runnable() {
public void run() {
try {
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Just to give one example (amongst many other possibilities), here is a small snippet that shows how to handle this.
Btw, when you call f.pack(); f.setLocationRelativeTo(null);, then this call is useless: f.setBounds(0,0,screenSize.width-5, screenSize.height-100);
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.SwingUtilities;
public class BasicSwingTest2 {
private JFrame frame;
protected void initUI() throws MalformedURLException {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
askForPassword();
}
private void askForPassword() {
final JDialog dialog = new JDialog(frame);
dialog.setResizable(false);
BufferedImage myPicture = null;
try {
myPicture = ImageIO
.read(new URL("http://images.all-free-download.com/images/graphiclarge/blue_abstract_background_310971.jpg"));
} catch (IOException e1) {
e1.printStackTrace();
}
Image dimg = myPicture.getScaledInstance(Toolkit.getDefaultToolkit().getScreenSize().width * 2 / 3, Toolkit.getDefaultToolkit()
.getScreenSize().height * 2 / 3, Image.SCALE_SMOOTH);
JLabel picLabel = new JLabel(new ImageIcon(dimg));
picLabel.setLayout(new GridBagLayout());
final JPasswordField password = new JPasswordField(25);
password.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Password is " + new String(password.getPassword()));
dialog.setVisible(false);
}
});
picLabel.add(password);
dialog.add(picLabel);
dialog.setTitle("Enter your password");
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new BasicSwingTest2().initUI();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
}
This class generates a window or frame(Im not too sure what the proper title would be) that has a back button and a ship select button on the left side. I would like to add a panel that takes up the right half of the frame. I am trying to add some more options specific to "Ship Selection" so I am assuming a panel is the correct way to go about it but am not entirely sure. Thanks in advance.
private class OptionsPanel extends JPanel{
private Galaga parent;
public OptionsPanel(Galaga p) {
super();
parent = p;
//layout components however you wish
setLayout(null);
JButton backButton = new JButton("<< Back");
backButton.setBounds(5, 20, 100, 20);
backButton.setFont(new Font("Arial", Font.PLAIN, 15));
backButton.setForeground(Color.white);
backButton.setBackground(Color.black);
backButton.setOpaque(true);
backButton.setBorderPainted(false);
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
parent.getLayeredPane().remove(parent.getOptionsPanel());
parent.getLayeredPane().add(parent.getButtonPanel(), new Integer(10));
parent.invalidate();
}
});
add(backButton);
JButton shipSelectButton = new JButton("Ship Selection");
shipSelectButton.setBounds(10, 60, 200, 40);
shipSelectButton.setFont(new Font("Arial", Font.PLAIN, 20));
shipSelectButton.setForeground(Color.white);
shipSelectButton.setBackground(Color.black);
shipSelectButton.setOpaque(true);
shipSelectButton.setBorderPainted(false);
shipSelectButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
add(shipSelectButton);
}
}
}
The most basic option is to use a GridLayout
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LayoutExamples {
public static void main(String[] args) {
new LayoutExamples();
}
public LayoutExamples() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(new OptionsPanel());
frame.add(new OtherPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class OtherPane extends JPanel {
public OtherPane() {
setBackground(Color.RED);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 200);
}
}
public class OptionsPanel extends JPanel {
public OptionsPanel() {
super();
//layout components however you wish
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(8, 8, 8, 8);
gbc.anchor = GridBagConstraints.NORTHWEST;
JButton backButton = new JButton("<< Back");
backButton.setFont(new Font("Arial", Font.PLAIN, 15));
backButton.setForeground(Color.white);
backButton.setBackground(Color.black);
backButton.setOpaque(true);
backButton.setBorderPainted(false);
backButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
add(backButton, gbc);
JButton shipSelectButton = new JButton("Ship Selection");
shipSelectButton.setFont(new Font("Arial", Font.PLAIN, 20));
shipSelectButton.setForeground(Color.white);
shipSelectButton.setBackground(Color.black);
shipSelectButton.setOpaque(true);
shipSelectButton.setBorderPainted(false);
shipSelectButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
gbc.insets = new Insets(12, 8, 12, 12);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weighty = 1;
gbc.weightx = 1;
add(shipSelectButton, gbc);
}
}
}
Pixel perfect layouts are an illusion in modern UI design. You don't have control over how things like fonts or even a single line will be rendered. Differences in rendering pipelines and DPI settings (for example) will change the metrics/size requirements of the components between platforms.
Swing is designed to use layout managers, make appropriate use of them.
I want to add textfields dynamically on the click of a button but the value to be fetched and the button are in one class and the panel where i want to add the textboxes and sliders adjacent to the are in a different class. Code is -
public class TipSplitting extends JPanel
JLabel lblNoOfGuests = new JLabel("No. Of guests");
lblNoOfGuests.setBounds(10, 26, 95, 14);
add(lblNoOfGuests);
private JTextField noofguests = new JTextField();
noofguests.setBounds(179, 23, 86, 20);
add(noofguests);
noofguests.setColumns(10);
JButton btnTiptailoring = new JButton("TipTailoring");
btnTiptailoring.setBounds(117, 286, 89, 23);
add(btnTiptailoring);
public class TipTailoring extends JPanel {}
In this class I need to create the text fields dynamically according to the no. entered. In the variable noofguests and the click of the button in the previous class.
I can't really see what the problem, but here some simple demo code of what you describe.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestDynamicallyAddedTextFields {
private void initUI() {
JFrame frame = new JFrame(TestDynamicallyAddedTextFields.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel textfieldContainerPanel = new JPanel();
textfieldContainerPanel.setLayout(new GridBagLayout());
JLabel nrOfGuests = new JLabel("Nr. of guests");
final JFormattedTextField textfield = new JFormattedTextField();
textfield.setValue(Integer.valueOf(1));
textfield.setColumns(10);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textfield.getValue() != null) {
addTextFieldsToPanel((Integer) textfield.getValue(), textfieldContainerPanel);
}
}
});
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING));
panel.add(nrOfGuests);
panel.add(textfield);
panel.add(add);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(textfieldContainerPanel));
frame.setSize(300, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected void addTextFieldsToPanel(Integer value, JPanel textfieldContainerPanel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
for (int i = 0; i < value; i++) {
textfieldContainerPanel.add(new JTextField(20), gbc);
}
textfieldContainerPanel.revalidate();
textfieldContainerPanel.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestDynamicallyAddedTextFields().initUI();
}
});
}
}
And the result: