I have this code:
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();
}
}
});
}
}
Ho can I move the JPasswordField to a absolute position (X,Y)?? I've been trying different things like setPosition(int X, int Y) and nothing worked. I tryed playing too with the layout but not success either. I would like to have just a JPasswordField object and a button object on his right. that's it
Thank you
Start by creating a panel for the password field and button to reside on. Next, randomise a EmptyBorder and the Insets of a GridBagConstraints to define different locations within the parent container. Add the password/button panel to this container with these randomised constraints...
public class TestPane extends JPanel {
public TestPane() {
Random rnd = new Random();
JPanel panel = new JPanel();
JPasswordField pf = new JPasswordField(10);
JButton btn = new JButton("Login");
panel.add(pf);
panel.add(btn);
panel.setBorder(new EmptyBorder(rnd.nextInt(10), rnd.nextInt(10), rnd.nextInt(10), rnd.nextInt(10)));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(rnd.nextInt(100), rnd.nextInt(100), rnd.nextInt(100), rnd.nextInt(100));
add(panel, gbc);
}
}
The other choice would be to write your own custom layout manager...but if you can avoid it, the above example is MUCH simpler...
ps- You could randomise either the border OR the insets, maybe using a larger random range and get the same effect, I've simpler used both to demonstrate the point ;)
Updated with layout manager example
public class TestPane extends BackgroundImagePane {
public TestPane() throws IOException {
super(ImageIO.read(new File("Path/to/your/image")));
Random rnd = new Random();
JPanel panel = new JPanel();
panel.setOpaque(false);
JPasswordField pf = new JPasswordField(10);
JButton btn = new JButton("Login");
panel.add(pf);
panel.add(btn);
setLayout(new RandomLayoutManager());
Dimension size = getPreferredSize();
size.width -= panel.getPreferredSize().width;
size.height -= panel.getPreferredSize().height;
add(panel, new Point(rnd.nextInt(size.width), rnd.nextInt(size.height)));
}
}
public class RandomLayoutManager implements LayoutManager2 {
private Map<Component, Point> mapConstraints;
public RandomLayoutManager() {
mapConstraints = new WeakHashMap<>(25);
}
#Override
public void addLayoutComponent(String name, Component comp) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void removeLayoutComponent(Component comp) {
mapConstraints.remove(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
Area area = new Area();
for (Component comp : mapConstraints.keySet()) {
Point p = mapConstraints.get(comp);
Rectangle bounds = new Rectangle(p, comp.getPreferredSize());
area.add(new Area(bounds));
}
Rectangle bounds = area.getBounds();
Dimension size = bounds.getSize();
size.width += bounds.x;
size.height += bounds.y;
return size;
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
for (Component comp : mapConstraints.keySet()) {
Point p = mapConstraints.get(comp);
comp.setLocation(p);
comp.setSize(comp.getPreferredSize());
}
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints instanceof Point) {
mapConstraints.put(comp, (Point) constraints);
} else {
throw new IllegalArgumentException("cannot add to layout: constraint must be a java.awt.Point");
}
}
#Override
public Dimension maximumLayoutSize(Container target) {
return preferredLayoutSize(target);
}
#Override
public float getLayoutAlignmentX(Container target) {
return 0.5f;
}
#Override
public float getLayoutAlignmentY(Container target) {
return 0.5f;
}
#Override
public void invalidateLayout(Container target) {
}
}
public class BackgroundImagePane extends JPanel {
private Image image;
public BackgroundImagePane(Image img) {
this.image = img;
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth(this)) / 2;
int y = (getHeight() - image.getHeight(this)) / 2;
g.drawImage(image, x, y, this);
}
}
}
The BackgroundImagePane is based on this example, allowing the background image panel to be the container for the field panel and you should be well on your way...
You could use a null layout, but that takes too long and it doesn't re-size with the frame.
Like this:
public class TestPane{
public static void main (String[] args) {
Random rnd = new Random();
JFrame frame = new JFrame();
JPasswordField pf = new JPasswordField();
JButton btn = new JButton("Login");
frame.setSize(500, 500);
frame.setLayout(null);
btn.setBounds(y, x, width, height);
pf.setBounds(y, x, width, height);
frame.add(btn);
frame.add(pf);
}
}
And that should work.
If you want to use a null layout.
Related
I want to add a picture that will be in the panel and also on labels but I don't know how to do that.
my code:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JPanel mainPanel = new JPanel();
panel.setLayout(new GridLayout(5, 5));
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
{
JLabel label = new JLabel();
label.setPreferredSize(new Dimension(50, 50));
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.add(label);
}
mainPanel.add(panel);
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
My Picture:
https://i.stack.imgur.com/w0Ssy.png
What I want to make:
https://i.stack.imgur.com/ZLPqF.png
If you're going to use components do to this job, then you're going to need to do some juggling with the layout managers. Because of it's flexibility, I would use GridBagLayout, in fact, I'm pretty sure it's the only inbuilt layout that will allow you to do something like this...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.MatteBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new GamePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class GamePane extends JPanel {
public GamePane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 10; x++) {
GridPane gridPane;
if (y == 9) {
if (x == 9) {
gridPane = new GridPane(1, 1, 1, 1);
} else {
gridPane = new GridPane(1, 1, 1, 0);
}
} else if (x == 9) {
gridPane = new GridPane(1, 1, 0, 1);
} else {
gridPane = new GridPane(1, 1, 0, 0);
}
gbc.gridx = x;
gbc.gridy = y;
add(gridPane, gbc);
}
}
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 4;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new ShipPane(1, 4), gbc, 0);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new ShipPane(3, 1), gbc, 0);
}
}
public class Configuration {
public static int GRID_SIZE = 50;
}
public class GridPane extends JPanel {
public GridPane(int top, int left, int bottom, int right) {
setBorder(new MatteBorder(top, left, bottom, right, Color.DARK_GRAY));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(Configuration.GRID_SIZE, Configuration.GRID_SIZE);
}
}
public class ShipPane extends JPanel {
private int gridWidth, gridHeight;
public ShipPane(int gridWidth, int gridHeight) {
this.gridWidth = gridWidth;
this.gridHeight = gridHeight;
setOpaque(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(Configuration.GRID_SIZE * gridWidth, Configuration.GRID_SIZE * gridHeight);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(255, 0, 0, 128));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
Now, I'm just using a panel, but without much work, you could add a JLabel to the ShipPane
Now, having said that. I think I would approach this problem from an entirely "custom painting" route
The way to do this is to use JLabel.setIcon
JLabel l = ...;
l.setIcon(myIcon);
You can make an Icon from an Image using ImageIcon.
You can get an image by loading it from disk/url, or by creating your own by creating a BufferedImage and drawing to its Graphics object.
Please can someone help me, I'm trying to make a seat reservation part for my cinema ticket system assignment ... so the problem is i want the text of the button to show in the text area when selected and not show only the specific text when deselected .. but when i deselect a button the whole text area is cleared.
For e.g. when I select C1, C2, C3 - it shows in the text area correctly, but if I want to deselect C3, the text area must now show only C1 & C2. Instead, it clears the whole text area!
Can anyone spot the problem in the logic?
import java.awt.*;
import static java.awt.Color.blue;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class Cw_Test2 extends JFrame {
JButton btn_payment,btn_reset;
JButton buttons;
JTextField t1,t2;
public static void main(String[] args) {
// TODO code application logic here
new Cw_Test2();
}
public Cw_Test2()
{
Frame();
}
public void Frame()
{
this.setSize(1200,700); //width, height
this.setTitle("Seat Booking");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 6);
Font newFont = myFont.deriveFont(20F);
t1=new JTextField();
t1.setBounds(15, 240, 240,30);
JPanel thePanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
thePanel.setLayout(null);
JPanel ourPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border ourBorder = BorderFactory.createLineBorder(blue , 2);
ourPanel.setBorder(ourBorder);
ourPanel.setLayout(null);
ourPanel.setBounds(50,90, 1100,420);
JPanel newPanel = new JPanel()
{
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
};
};
//ourPanel.setBackground(Color.green);
Border newBorder = BorderFactory.createLineBorder(blue , 1);
newPanel.setBorder(newBorder);
newPanel.setLayout(null);
newPanel.setBounds(790,50, 270,340);
JLabel label1 = new JLabel( new ColorIcon(Color.GRAY, 400, 100) );
label1.setText( "SCREEN" );
label1.setHorizontalTextPosition(JLabel.CENTER);
label1.setVerticalTextPosition(JLabel.CENTER);
label1.setBounds(130,50, 400,30);
JLabel label2 = new JLabel(" CINEMA TICKET MACHINE ");
label2.setBounds(250,50,400,30);
label2.setFont(newFont);
JLabel label3 = new JLabel("Please Select Your Seat");
label3.setBounds(270,10,500,30);
label3.setFont(newFont);
JLabel label4 = new JLabel("Selected Seats:");
label4.setBounds(20,10,200,30);
label4.setFont(newFont);
btn_payment=new JButton("PROCEED TO PAY");
btn_payment.setBounds(35,290,200,30);
JLabel label6 = new JLabel("Center Stall");
label6.setBounds(285,172,200,30);
JPanel seatPane, seatPane1, seatPane2, seatPane3, seatPane4, seatPane5;
JToggleButton[] seat2 = new JToggleButton[8];
JTextArea chosen = new JTextArea();
chosen.setEditable(false);
chosen.setLineWrap(true);
chosen.setBounds(20, 60, 200, 100);
// Center Seats
seatPane1 = new JPanel();
seatPane1.setBounds(200,200,250,65);
seatPane1.setLayout(new FlowLayout());
for(int x=0; x<8; x++){
seat2[x] = new JToggleButton("C"+(x+1));
seatPane1.add(seat2[x]);
seat2[x].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
AbstractButton abstractButton = (AbstractButton) ev.getSource();
boolean selected = abstractButton.getModel().isSelected();
for(int x=0; x<8; x++){
if(seat2[x]==ev.getSource()){
if(selected){
chosen.append(seat2[x].getText()+",");
}else{
chosen.setText(seat2[x].getText().replace(seat2[x].getText(),""));
}
}
}
}
});
}
newPanel.add(chosen);
ourPanel.add(seatPane1);
ourPanel.add(label6);
thePanel.add(label2);
ourPanel.add(label3);
ourPanel.add(label1);
newPanel.add(btn_payment);
newPanel.add(label4);
ourPanel.add(newPanel);
thePanel.add(ourPanel);
add(thePanel);
setResizable(false);
this.setVisible(true);
}
public static class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
When any seat is selected or deselected, this code iterates an array of seats (in the method showSelectedSeats()) and updates the text area to show the seats that are selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class CinemaTicketMachine {
private JComponent ui = null;
private JToggleButton[] seats = new JToggleButton[80];
private JTextArea selectedSeats = new JTextArea(3, 40);
CinemaTicketMachine() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
selectedSeats.setLineWrap(true);
selectedSeats.setWrapStyleWord(true);
selectedSeats.setEditable(false);
ui.add(new JScrollPane(selectedSeats), BorderLayout.PAGE_END);
JPanel cinemaFloor = new JPanel(new BorderLayout(40, 0));
cinemaFloor.setBorder(new TitledBorder("Available Seats"));
ui.add(cinemaFloor, BorderLayout.CENTER);
JPanel leftStall = new JPanel(new GridLayout(0, 2, 2, 2));
JPanel centerStall = new JPanel(new GridLayout(0, 4, 2, 2));
JPanel rightStall = new JPanel(new GridLayout(0, 2, 2, 2));
cinemaFloor.add(leftStall, BorderLayout.WEST);
cinemaFloor.add(centerStall, BorderLayout.CENTER);
cinemaFloor.add(rightStall, BorderLayout.EAST);
ActionListener seatSelectionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showSelectedSeats();
}
};
for (int ii=0; ii <seats.length; ii++) {
JToggleButton tb = new JToggleButton("S-" + (ii+1));
tb.addActionListener(seatSelectionListener);
seats[ii] = tb;
int colIndex = ii%8;
if (colIndex<2) {
leftStall.add(tb);
} else if (colIndex<6) {
centerStall.add(tb);
} else {
rightStall.add(tb);
}
}
}
private void showSelectedSeats() {
StringBuilder sb = new StringBuilder();
for (int ii=0; ii<seats.length; ii++) {
JToggleButton tb = seats[ii];
if (tb.isSelected()) {
sb.append(tb.getText());
sb.append(", ");
}
}
String s = sb.toString();
if (s.length()>0) {
s = s.substring(0, s.length()-2);
}
selectedSeats.setText(s);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
CinemaTicketMachine o = new CinemaTicketMachine();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Im adding an array of JPanels inside a JScrollPane. The array of JPanels are being added to the JScrollPane but the scroll bars just wont show.
public class MyFrame extends JFrame {
private JPanel contentPane;
private JPanel panel_1;
private JScrollPane scrollPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 288, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panel_1 = new JPanel();
panel_1.setBounds(10, 114, 434, 136);
panel_1.setLayout(null);
scrollPane = new JScrollPane(panel_1);
scrollPane.setBounds(52, 57, 164, 126);
scrollPane.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Histogram", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE));
scrollPane.setLayout(new ScrollPaneLayout());
contentPane.add(scrollPane);
buildBar();
}
JPanel[] barPanel;
private void buildBar(){
int x=0,y=22,w=100,h=80,s=10,n=3;
barPanel = new JPanel[n];
for(int i=0; i<n; i++){
barPanel[i] = new JPanel();
barPanel[i].setBounds(x, y, w, h);
barPanel[i].setBackground(new Color(255,0,0));
panel_1.add(barPanel[i]);
panel_1.revalidate();
panel_1.repaint();
x = x + w + s;
}
}
}
I have been working on it for hours . Maybe there is something that I've missed out.
You're shooting yourself in the foot with these two lines:
panel_1.setBounds(10, 114, 434, 136);
panel_1.setLayout(null);
Both of which will mess up the JScrollPane's ability to use and display scrollbars. What you need to do is: not to use setBounds but rather have the components use their preferredSize, and avoid using null layout, since this won't change the container's preferredSize.
Yet another reason to studiously avoid null layouts.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class MyPanel2 extends JPanel {
private static final int PREF_W = 388;
private static final int PREF_H = PREF_W;
public static final int INNER_PREF_W = 434;
public static final int INNER_PREF_H = 126;
private static final int HISTO_PANEL_COUNT = 6;
private static final Dimension VP_SZ = new Dimension(164, 126);
private JPanel holderPanel = new JPanel(new GridLayout(0, 1));
public MyPanel2() {
int w = INNER_PREF_W;
int h = INNER_PREF_H;
for (int i = 0; i < HISTO_PANEL_COUNT; i++) {
holderPanel.add(new InnerPanel(w, h));
}
JScrollPane scrollPane = new JScrollPane(holderPanel);
scrollPane.getViewport().setPreferredSize(VP_SZ);
setLayout(new GridBagLayout());
add(scrollPane);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class InnerPanel extends JPanel {
private int w;
private int h;
public InnerPanel(int w, int h) {
this.w = w;
this.h = h;
setBorder(BorderFactory.createLineBorder(Color.BLUE));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0, y = 22, w = 100, h = 80, s = 10, n = 3;
g.setColor(Color.RED);
for (int i = 0; i < n; i++) {
g.fillRect(x, y, w, h);
x = x + w + s;
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(w, h);
}
}
private static void createAndShowGui() {
MyPanel2 mainPanel = new MyPanel2();
JFrame frame = new JFrame("MyPanel2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
JScrollPane relies on the preferredSize of your container to determine the scroll bar width. If you use a Layout, the preferredSize will be determined for you when components are added to the panel.
However, when you use:
contentPane.setLayout(null);
You are preventing the preferredSize from changing based on added components.
Try to use a layout which is applicable for your case.
In case you are very certain you do not want to use a Layout, in order to see the scroll bar, you may set the preferredSize of the container for every components you added by manually adjusting the preferredSize. That way, the scrollbar will still extend with newly added components.
I am currently using a Absolute layout where I want to place a String variable to the panel (this frame is similar to a popup dialog) with horizontal alignment. Here's a snippet of my code.
JLabel label = new JLabel(loggedInAs);
label.setBounds(10, 61, 314, 23);
label.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(label);
When I run this the text appears to start slightly to the right, however if I enter preset text to the label such as
JLabel label = new JLabel("Hello");
it will center. Is there anyway I can resolve this?
(I have also played with the miglayout but it turned out completely different when running it from my main JFrame)
An example:
Here is an example of what I mean by it being slightly to the right
I think that your problem is in use of absolute layout, since you're using hard coded numbers to place your JLabel. The label text is itself centered fine, but if you put a border around the label, you'll likely see that the label itself, not its text, is skewed to the right. The easiest solution is to let the layout managers do the lifting for you. For example, the code below creates a successfully logged in dialog that uses a combination of layout managers to achieve what it looks like you're trying to do in your image:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class LoginPanelEg extends JPanel {
private JTextField nameField = new JTextField(20);
private Action LoginAction = new LoginAction("Login");
public LoginPanelEg() {
nameField.setAction(LoginAction);
add(new JLabel("Login Name:"));
add(nameField);
add(new JButton(LoginAction));
}
private class LoginAction extends AbstractAction {
public LoginAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic); // alt-key comb
}
#Override
public void actionPerformed(ActionEvent e) {
LoginPanel loginPanel = new LoginPanel(nameField.getText());
Window win = SwingUtilities.getWindowAncestor(LoginPanelEg.this);
JDialog dialog = new JDialog(win, "Successfully Logged In", ModalityType.APPLICATION_MODAL);
dialog.add(loginPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("LoginPanelEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LoginPanelEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class LoginPanel extends JPanel {
private static final int PREF_W = 350;
private static final int PREF_H = 200;
private static final String SUCCESSFULLY_LOGGED = "Successfully logged in as:";
private static final int GAP = 20;
private static final Font PROMPT_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 14);
private static final Font NAME_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 12);
private JLabel successfullyLoggedLabel = new JLabel(SUCCESSFULLY_LOGGED, SwingConstants.CENTER);
private JLabel nameLabel = new JLabel("", SwingConstants.CENTER);
public LoginPanel() {
successfullyLoggedLabel.setFont(PROMPT_FONT);
nameLabel.setFont(NAME_FONT);
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.add(successfullyLoggedLabel, createGbc(0, 0));
innerPanel.add(nameLabel, createGbc(0, 1));
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(new CloseAction("Close")));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(innerPanel, BorderLayout.CENTER);
add(btnPanel, BorderLayout.PAGE_END);
}
LoginPanel(String name) {
this();
nameLabel.setText(name);
}
public void setName(String name) {
nameLabel.setText(name);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
return gbc;
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class CloseAction extends AbstractAction {
public CloseAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic); // alt-key comb
}
#Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
if (component == null) {
return;
}
Window win = SwingUtilities.getWindowAncestor(component);
if (win == null) {
return;
}
win.dispose();
}
}
}
I need to customize the knob of JSlider. I need to put my own knob's image over default knob of Jslider.
The problem is that currently two knobs are coming in response. One my own knob and second the default knob. Please tell me how i can i hide the default knob or any other solution.
Below code is used to do so.
public class ImageTest {
JSlider slider;
JLabel label;
public ImageTest()
{
JPanel panel = new BackgroundPanel();
slider = new BackgroundSlider();
slider.setMaximum(300);
slider.setMinimum(0);
slider.setValue(50);
slider.setExtent(10);
slider.addChangeListener(new MyChangeAction());
label = new JLabel("50");
panel.setLayout(new GridBagLayout());
panel.setSize(797,402);
slider.setOpaque(false);
slider.setPaintTrack(false);
label.setOpaque(false);
slider.setPreferredSize(new Dimension(340, 20));
GridBagConstraints gridBagConstraintsSlider = new GridBagConstraints();
gridBagConstraintsSlider.gridy = 0;
gridBagConstraintsSlider.gridx = 0;
gridBagConstraintsSlider.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraintsSlider.insets = new Insets(0, 283, 260, 0);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new Insets(0, 50, 240, 0);
panel.add(slider, gridBagConstraintsSlider);
panel.add(label, gridBagConstraints);
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setSize(797,402);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WindowUtil.locateCenter(frame);
}
public static void main(String[] args) {
ImageTest im= new ImageTest();
}
public class MyChangeAction implements ChangeListener{
public void stateChanged(ChangeEvent ce){
int value = slider.getValue();
String str = Integer.toString(value);
label.setText(str);
if(value==300)
{
label.setText("Max");
}
}
}
}
class BackgroundSlider extends JSlider
{
Image image;
public BackgroundSlider()
{
try
{
image = javax.imageio.ImageIO.read(new File("slider.png"));
}
catch (Exception e) { /*handled in paintComponent()*/ }
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
g.drawImage(image, this.getValue(),(int)this.getAlignmentY(),10,20,this);
g.setColor(Color.RED);
//draw a centered horizontal line
g.drawRect(15,this.getHeight()-1,this.getValue(),this.getHeight()+2);
g.fillRect(15,this.getHeight()-1,this.getValue(),this.getHeight()+2);
}
}
Thanks
Jyoti
To hide the knob, override the UIManager's Slider.horizontalThumbIcon property with an blank icon, like this:
public static void main(String[] args) throws Exception {
UIManager.getLookAndFeelDefaults().put("Slider.horizontalThumbIcon",new Icon(){
#Override
public int getIconHeight() {
return 0;
}
#Override
public int getIconWidth() {
return 0;
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
//do nothing
}
});
JFrame f = new JFrame();
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(1);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
f.add(slider);
f.setSize(200,200);
f.setVisible(true);
}
A solution with a different BasicSliderUI looks like this:
public class SuperSlider extends JSlider {
public SuperSlider(int min, int max, int value) {
super(min,max,value);
setUI(new SuperSliderUI(this));
}
private class SuperSliderUI extends BasicSliderUI {
#Override
public void paintThumb(Graphics g) {
}
}
}
The UIManager solution only works in the Metal LAF from what I can tell.
If you want to change the behavour of the UI then you need to change the UI. In this case you would need to the BasicSliderUI (or one of its sub classes). Then I believe you would need to override the paintThumb() method.