I want to create a "preview window" for my "main window", so if I take mouse pointer to a particular button or place then it show main window preview in a small window, and when I click on that "preview window" then it should return to the "main window". For example Windows 7 task bar creates a preview for each opened application. How can I can offer this feature to my users?
E.G.
An extremely simplistic implementation.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
class ShowPreviews {
class ToolTipListener extends MouseAdapter {
JWindow toolTip;
JLabel label;
Component preview;
ToolTipListener(Component preview) {
this.preview = preview;
}
#Override
public void mouseEntered(MouseEvent me) {
if (toolTip==null) {
toolTip = new JWindow();
label = new JLabel();
toolTip.add(label);
}
label.setIcon( new ImageIcon(
getScaledImageOfComponent(preview, .6) ) );
toolTip.pack();
Component c = (Component)me.getSource();
int x = c.getLocationOnScreen().x+(c.getWidth()/2);
int y = c.getLocationOnScreen().y+c.getHeight();
toolTip.setLocation(x,y);
toolTip.setVisible(true);
}
#Override
public void mouseExited(MouseEvent me) {
toolTip.setVisible(false);
toolTip.dispose();
}
public Image getScaledImageOfComponent(
Component component, double scale) {
BufferedImage bi = new BufferedImage(
(int)(component.getWidth()*scale),
(int)(component.getHeight()*scale),
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.scale(scale, scale);
component.paint(g);
g.dispose();
return bi;
}
}
ShowPreviews() {
JPanel gui = new JPanel(new BorderLayout(2,2));
final CardLayout cards = new CardLayout();
final JPanel cardPanel = new JPanel(cards);
JPanel treePanel = new JPanel();
JTree tree = new JTree();
tree.setVisibleRowCount(5);
tree.expandRow(2);
treePanel.add(new JScrollPane(tree));
cardPanel.add(treePanel, "tree");
JPanel labelPanel = new JPanel(new GridLayout(0,1,2,2));
for (int ii=1; ii<7; ii++) {
labelPanel.add(new JLabel("Label " + ii));
}
cardPanel.add(new JScrollPane(labelPanel), "label");
JToolBar uiSelectors = new JToolBar();
// we should use a ButtonGroup for the cards,
// but plain buttons look better on hover.
JButton treeButton = new JButton("Tree");
treeButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cards.show(cardPanel, "tree");
}
});
uiSelectors.add(treeButton);
treeButton.addMouseListener( new ToolTipListener(treePanel));
JButton labelButton = new JButton("Label");
labelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
cards.show(cardPanel, "label");
}
});
uiSelectors.add(labelButton);
labelButton.addMouseListener( new ToolTipListener(labelPanel));
gui.add(uiSelectors, BorderLayout.NORTH);
gui.add(cardPanel, BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
// start the GUI on the EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ShowPreviews();
}
});
}
}
Related
I have the main class that instantiates a GridBagLayout with a JLabel visbility set to false.
I would like to set the label visible when the program is running, I have tried this but it won't work. It will just display the default layout.
Main class:
gui = new gui();
gui.display();
gui.label.setVisible(true);
Gridbag layout class:
public JFrame frame;
public JLabel label1;
/**
* Launch the application.
*/
public static void display(){
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gridLayout window = new gridLayout();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
* Create the application.
*/
public gridLayout() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
#SuppressWarnings("static-access")
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 600, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
frame.getContentPane().setLayout(gridBagLayout);
}
label1 = new JLabel(new ImageIcon("hi"));
GridBagConstraints gbc_label1 = new GridBagConstraints();
gbc_label1.insets = new Insets(0, 0, 5, 5);
gbc_label1.gridx = 1;
gbc_label1.gridy = 1;
label1.setVisible(false);
frame.getContentPane().add(label1, gbc_label1);
You want to display a label while a programme is running, right? This has nothing to do with the layout manager.
I give you an example where the label is visible as long as a dialog (representing your task/programme) is displayed; and I hope you can adopt it to your needs. Possibly you have to put the programme/task in an own thread.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Y extends JFrame {
public static final long serialVersionUID = 100L;
public Y() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 240);
JLabel lb= new JLabel("Programme is running ...");
lb.setVisible(false);
add(lb, BorderLayout.CENTER);
JButton b= new JButton("Launch programme (dialog)");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lb.setVisible(true);
JDialog dlg= new JDialog(Y.this, "The dialog", true);
dlg.setSize(100, 100);
dlg.setVisible(true);
lb.setVisible(false);
}
});
add(b, BorderLayout.SOUTH);
setVisible(true);
}
static public void main(String args[]) {
EventQueue.invokeLater(Y::new);
}
}
Is it possible to create a button that won't be seen until the user clicks another button?
My goal is for the button to be invisible by default rather than when its clicked on. Then become visible when another action is performed. The code below is my original attempt at creating this.
public void but_roll1ActionPerformed(java.awt.event.ActionEvent evt)
{
if (!bal_but.isEnabled() && !gamble_but.isEnabled()) {
but_roll1.setVisible(true);
but_roll1.setEnabled(true);
d1 = diceRoll();
die1_display.setText(String.valueOf(d1));
but_roll1.setEnabled(false);
} else {
but_roll1.setVisible(false);
}
}
Two better strategies:
Put the button in a CardLayout with a second blank panel till needed.
Make the button disabled until the first button is clicked.
I prefer the 2nd as the 'path of least surprise' for the user. YMMV.
Initial view
View after 'effect' button actioned
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ButtonNotUsableTillAction {
private JComponent ui = null;
ButtonNotUsableTillAction() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridLayout(1, 0, 4, 4));
ui.setBorder(new EmptyBorder(4,4,4,4));
// first demo, using card layout
JPanel cardDemoPanel = new JPanel(new GridLayout(1, 0, 2, 2));
cardDemoPanel.setBorder(new TitledBorder("Card Layout"));
ui.add(cardDemoPanel);
JButton actionCardButton = new JButton("Action");
cardDemoPanel.add(actionCardButton);
CardLayout cardLayout = new CardLayout();
JPanel cardLayoutPanel = new JPanel(cardLayout);
cardDemoPanel.add(cardLayoutPanel);
cardLayoutPanel.add(new JPanel(), "panel");
cardLayoutPanel.add(new JButton("Effect"), "button");
cardLayout.show(cardLayoutPanel, "panel");
ActionListener flipCardListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardLayoutPanel, "button");
}
};
actionCardButton.addActionListener(flipCardListener);
// first demo, using disabled / enabled
JPanel enabledDemoPanel = new JPanel(new GridLayout(1, 0, 2, 2));
enabledDemoPanel.setBorder(new TitledBorder("Enabled"));
ui.add(enabledDemoPanel);
JButton actionEnabledButton = new JButton("Action");
enabledDemoPanel.add(actionEnabledButton);
JButton effectButton = new JButton("Effect");
enabledDemoPanel.add(effectButton);
effectButton.setEnabled(false);
ActionListener enableComponentListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
effectButton.setEnabled(true);
}
};
actionEnabledButton.addActionListener(enableComponentListener);
}
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) {
}
ButtonNotUsableTillAction o = new ButtonNotUsableTillAction();
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);
}
}
As #markspace mentioned, you need to revalidate the button's container after setting the button visible:
but_roll1.getParent().revalidate();
I got a java class called PleaseWait and want to call it whenever a heavy task is in progress. When my program does a heavy task, in the first row in my actionListener I set a variable of this class setVisible(true) then set setVisible(true) at the end of the actionListener.
Somehow the JPanel in this class does not appear when I call it, it's just a window with title as set and white blank content. Here's my code:
public class PleaseWait extends JFrame{
public PleaseWait(){
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenDimensions = toolkit.getScreenSize();
setSize(300,100); //set size based on screen size
setTitle("Please wait");
Container container = getContentPane();
setLocation(new Point(screenDimensions.width*1/4+200, screenDimensions.height*1/4+200)); //set location based on screen size
JPanel panel = new JPanel();
JLabel wait = new JLabel("Please wait");
Dimension buttonsSize = new Dimension(300,100);
panel.setPreferredSize(buttonsSize);
wait.setPreferredSize(buttonsSize);
panel.setLayout(new BorderLayout());
panel.add(wait, BorderLayout.CENTER);
container.add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false); //unresizable
}
The key is not in the code you've posted, but in this line:
and want to call it whenever a heavy task is in progress
You're running a "heavy" task, and while you're running it, Swing is not painting this GUI, because you're likely running that task on the Swing event thread, and doing so freezes the thread, and your GUI.
Solution: use a background thread such as is obtainable through a SwingWorker, to run the "heavy" task.
Other side issues:
This appears to be a "dependent" or "sub" window off of the main application. If so, it should not be a JFrame since an application should only have one main application window, but rather it should be a JDialog.
You're using setPreferredSize(...) and hard-coding your component sizes, something fraught with problems.
e.g.,
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestPleaseWait {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MainPanel mainPanel = new MainPanel();
JFrame frame = new JFrame("Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
#SuppressWarnings("serial")
class MainPanel extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 450;
public MainPanel() {
add(new JButton(new AbstractAction("Without Background Thread") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_O);
}
#Override
public void actionPerformed(ActionEvent e) {
final PleaseWait wait = new PleaseWait();
wait.setVisible(true);
try {
Thread.sleep(4000);
} catch (InterruptedException e1) {
}
wait.setVisible(false);
}
}));
add(new JButton(new AbstractAction("With Background Thread") {
private JDialog waitDialog = null;
private MyWaitPanel myWaitPanel = new MyWaitPanel();
{
putValue(MNEMONIC_KEY, KeyEvent.VK_W);
}
#Override
public void actionPerformed(ActionEvent e) {
if (waitDialog == null) {
Component component = MainPanel.this;
Window win = SwingUtilities.getWindowAncestor(component);
waitDialog = new JDialog(win, "Please Wait", ModalityType.APPLICATION_MODAL);
waitDialog.add(myWaitPanel);
waitDialog.pack();
waitDialog.setLocationRelativeTo(win);
}
new Thread(() -> {
try {
Thread.sleep(4000);
} catch (InterruptedException e1) {
}
SwingUtilities.invokeLater(() -> {
waitDialog.setVisible(false);
});
}).start();
waitDialog.setVisible(true);
}
}));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
#SuppressWarnings("serial")
class MyWaitPanel extends JPanel {
private JProgressBar progressBar = new JProgressBar();
public MyWaitPanel() {
progressBar.setIndeterminate(true);
JLabel waitLabel = new JLabel("Please Wait", SwingConstants.CENTER);
waitLabel.setFont(waitLabel.getFont().deriveFont(Font.BOLD, 40));
int ebGap = 10;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BorderLayout(ebGap, ebGap));
add(waitLabel, BorderLayout.PAGE_START);
add(progressBar);
}
}
#SuppressWarnings("serial")
class PleaseWait extends JFrame {
public PleaseWait() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenDimensions = toolkit.getScreenSize();
setSize(300, 100); // set size based on screen size
setTitle("Please wait");
Container container = getContentPane();
setLocation(new Point(screenDimensions.width * 1 / 4 + 200,
screenDimensions.height * 1 / 4 + 200));
JPanel panel = new JPanel();
JLabel wait = new JLabel("Please wait");
Dimension buttonsSize = new Dimension(300, 100);
panel.setPreferredSize(buttonsSize);
wait.setPreferredSize(buttonsSize);
panel.setLayout(new BorderLayout());
panel.add(wait, BorderLayout.CENTER);
container.add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false); // unresizable
}
}
Can I scroll a JPanel using JButtons added to a JToolBar?
When I generate a large number of thumbnails, they don't all fit onto the JPanel. I want to use an up/down arrow JButton to scroll. Can this be done, and if so, how?
NOTE: I am trying to do this without a JScrollPane because I want the custom arrow icons, not a standard scroll bar.
Here is an SSCCE:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class PicSlider2 {
private JButton thumbs;
private JButton[] thumbnails;
private JLabel picViewer;
private JPanel thumbPanel;
private JToolBar toolBar;
public PicSlider2() {
final JFrame frame = new JFrame("Picture Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
frame.setResizable(false);
frame.setLayout(new BorderLayout());
picViewer = new JLabel();
picViewer.setText("Image here");
picViewer.setHorizontalAlignment(JLabel.CENTER);
picViewer.setVerticalAlignment(JLabel.BOTTOM);
picViewer.setBorder(new LineBorder(Color.BLACK, 2));
JMenuBar frameMenuBar = new JMenuBar();
frame.setJMenuBar(frameMenuBar);
JMenu file = new JMenu("File");
frameMenuBar.add(file);
JMenuBar picViewerMenu = new JMenuBar();
picViewerMenu.setLayout(new FlowLayout(FlowLayout.LEFT));
thumbs = new JButton("THUMBNAILS");//an icon in actual program
thumbs.setPreferredSize(new Dimension(150,45));
thumbs.setToolTipText("Thumbnails");
thumbs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
picViewer.setVisible(false);
thumbPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
thumbPanel.setBorder(BorderFactory.createEmptyBorder(50,100,50,30));
thumbnails = new JButton[30];//example size, chosen so all buttons won't fit on one page
for (int i = 0; i < 30; i++) {
thumbnails[i] = new JButton(Integer.toString(i));
thumbnails[i].setPreferredSize(new Dimension(100, 100));
thumbnails[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("thumbnail clicked - opens full-size view of pic in the JLabel picViewer");
}
});
thumbPanel.add(thumbnails[i]);
thumbPanel.setVisible(true);
}
toolBar = new JToolBar(null, JToolBar.VERTICAL);
toolBar.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 30));
JButton up = new JButton("Up Arrow");
up.setPreferredSize(new Dimension(80,60));
up.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Up Arrow Stub - NEEDS TO SCROLL UP PAGE, as needed");
}
} );
JButton down = new JButton("Down Arrow");
down.setPreferredSize(new Dimension(80,60));
down.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Down Arrow Stub - NEEDS TO SCROLL DOWN PAGE, as needed");
}
} );
toolBar.add(Box.createGlue());
toolBar.add(up);
toolBar.add(Box.createVerticalStrut(40));
toolBar.add(down);
toolBar.add(Box.createGlue());
frame.getContentPane().add(thumbPanel, BorderLayout.CENTER);
frame.getContentPane().add(toolBar, BorderLayout.LINE_END);
}
});
picViewerMenu.add(thumbs);
frame.getContentPane().add(picViewerMenu, BorderLayout.SOUTH);
frame.add(picViewer, BorderLayout.CENTER);
frame.setLocation(300, 50);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PicSlider2 ps = new PicSlider2();
}
});
}
}
I am trying to do this without a JScrollPane because I want the custom arrow icons
You can use a JScrollPane and use the default scroll Action to create a button with your custom Icon:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;
public class ScrollPaneSSCCE extends JPanel
{
public ScrollPaneSSCCE()
{
setLayout( new BorderLayout() );
JTable table = new JTable(50, 5);
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
add(scrollPane);
JScrollBar vertical = scrollPane.getVerticalScrollBar();
JPanel east = new JPanel( new BorderLayout() );
add(east, BorderLayout.EAST);
JButton north = new JButton( new ActionMapAction("UP", vertical, "negativeUnitIncrement") );
east.add(north, BorderLayout.NORTH);
JButton south = new JButton( new ActionMapAction("DOWN", vertical, "positiveUnitIncrement") );
east.add(south, BorderLayout.SOUTH);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("ScrollPaneSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ScrollPaneSSCCE());
frame.setSize(200, 300);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
You will need the Action Map Action class which is just a simple wrapper class that gets the default Action from the ActionMap of the specified component.
You will need to set the scroll increment for you panel. Since your image size is 100 you might want to use:
vertical.setUnitIncrement( 100 );
I found a way to achieve your desired result by reordering the items on the JPanel. The JFrame needs to be declared outside of the constructor. I added an index variable for tracking the scroll position and a reloadThumbs() method for reloading the reordered thumbs.
This is the entire code after the changes:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class PicSlider2 {
private JButton thumbs;
private JButton[] thumbnails;
private JLabel picViewer;
private JPanel thumbPanel;
private JToolBar toolBar;
private int scrollIndex;
private final JFrame frame;
public PicSlider2() {
scrollIndex = 0;
frame = new JFrame("Picture Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(800, 600));
frame.setResizable(false);
frame.setLayout(new BorderLayout());
picViewer = new JLabel();
picViewer.setText("Image here");
picViewer.setHorizontalAlignment(JLabel.CENTER);
picViewer.setVerticalAlignment(JLabel.BOTTOM);
picViewer.setBorder(new LineBorder(Color.BLACK, 2));
JMenuBar frameMenuBar = new JMenuBar();
frame.setJMenuBar(frameMenuBar);
JMenu file = new JMenu("File");
frameMenuBar.add(file);
JMenuBar picViewerMenu = new JMenuBar();
picViewerMenu.setLayout(new FlowLayout(FlowLayout.LEFT));
thumbs = new JButton("THUMBNAILS");//an icon in actual program
thumbs.setPreferredSize(new Dimension(150,45));
thumbs.setToolTipText("Thumbnails");
thumbs.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
picViewer.setVisible(false);
thumbPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20,20));
thumbPanel.setBorder(BorderFactory.createEmptyBorder(50,100,50,30));
thumbnails = new JButton[30];//example size, chosen so all buttons won't fit on one page
for (int i = 0; i < 30; i++) {
thumbnails[i] = new JButton(Integer.toString(i));
thumbnails[i].setPreferredSize(new Dimension(100, 100));
thumbnails[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("thumbnail clicked - opens full-size view of pic in the JLabel picViewer");
}
});
thumbPanel.add(thumbnails[i]);
thumbPanel.setVisible(true);
}
toolBar = new JToolBar(null, JToolBar.VERTICAL);
toolBar.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 30));
JButton up = new JButton("Up Arrow");
up.setPreferredSize(new Dimension(80,60));
up.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Up Arrow Stub - NEEDS TO SCROLL UP PAGE, as needed");
if(scrollIndex > 3) scrollIndex -= 4;
else scrollIndex = 0;
reloadThumbs();
}
} );
JButton down = new JButton("Down Arrow");
down.setPreferredSize(new Dimension(80,60));
down.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Down Arrow Stub - NEEDS TO SCROLL DOWN PAGE, as needed");
if(scrollIndex < 27) scrollIndex += 4;
else scrollIndex = 30;
reloadThumbs();
}
} );
toolBar.add(Box.createGlue());
toolBar.add(up);
toolBar.add(Box.createVerticalStrut(40));
toolBar.add(down);
toolBar.add(Box.createGlue());
frame.getContentPane().add(thumbPanel, BorderLayout.CENTER);
frame.getContentPane().add(toolBar, BorderLayout.LINE_END);
}
});
picViewerMenu.add(thumbs);
frame.getContentPane().add(picViewerMenu, BorderLayout.SOUTH);
frame.add(picViewer, BorderLayout.CENTER);
frame.setLocation(300, 50);
frame.pack();
frame.setVisible(true);
}
private void reloadThumbs(){
thumbPanel.removeAll();
for(int i = scrollIndex; i < 30; ++i){
thumbPanel.add(thumbnails[i]);
}
for(int i = 0; i < scrollIndex; ++i){
thumbPanel.add(thumbnails[i]);
}
thumbPanel.revalidate();
frame.revalidate();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PicSlider2 ps = new PicSlider2();
}
});
}
}
I've made two buttons in frame .I want to know how to display different images on clicking different buttons?
is there another way out or i have to make panel?I am at beginner stage
package prac;
import java.awt.*;
import java.awt.event.*;
public class b extends Frame implements ActionListener{
String msg;
Button one,two;
b()
{ setSize(1000,500);
setVisible(true);
setLayout(new FlowLayout(FlowLayout.LEFT));
one=new Button("1");
two=new Button("2");
add(one);
add(two);
one.addActionListener(this);
two.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
msg=e.getActionCommand();
if(msg.equals("1"))
{
msg="Pressed 1";
}
else
msg="pressed 2";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,300);
}
public static void main(String s[])
{
new b();
}
}
Use JLabel and change the icon when button is clicked.
Some points:
call setVisible(true) in the end after adding all the component.
use JFrame#pack() method that automatically fit the components in the JFrame based on component's preferred dimension instead of calling JFrame#setSize() method.
sample code:
final JLabel jlabel = new JLabel();
add(jlabel);
final Image image1 = ImageIO.read(new File("resources/1.png"));
final Image image2 = ImageIO.read(new File("resources/2.png"));
JPanel panel = new JPanel();
JButton jbutton1 = new JButton("Show first image");
jbutton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image1));
}
});
JButton jbutton2 = new JButton("Show second image");
jbutton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jlabel.setIcon(new ImageIcon(image2));
}
});
panel.add(jbutton1);
panel.add(jbutton2);
add(panel, BorderLayout.NORTH);